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 
105ec532a9SColin Riley #include "RenderScriptRuntime.h"
115ec532a9SColin Riley 
125ec532a9SColin Riley #include "lldb/Core/ConstString.h"
135ec532a9SColin Riley #include "lldb/Core/Debugger.h"
145ec532a9SColin Riley #include "lldb/Core/Error.h"
155ec532a9SColin Riley #include "lldb/Core/Log.h"
165ec532a9SColin Riley #include "lldb/Core/PluginManager.h"
17*018f5a7eSEwan Crawford #include "lldb/Core/RegularExpression.h"
18a0f08674SEwan Crawford #include "lldb/Host/StringConvert.h"
195ec532a9SColin Riley #include "lldb/Symbol/Symbol.h"
204640cde1SColin Riley #include "lldb/Symbol/Type.h"
215ec532a9SColin Riley #include "lldb/Target/Process.h"
225ec532a9SColin Riley #include "lldb/Target/Target.h"
23*018f5a7eSEwan Crawford #include "lldb/Target/Thread.h"
245ec532a9SColin Riley #include "lldb/Interpreter/Args.h"
255ec532a9SColin Riley #include "lldb/Interpreter/Options.h"
265ec532a9SColin Riley #include "lldb/Interpreter/CommandInterpreter.h"
275ec532a9SColin Riley #include "lldb/Interpreter/CommandReturnObject.h"
285ec532a9SColin Riley #include "lldb/Interpreter/CommandObjectMultiword.h"
294640cde1SColin Riley #include "lldb/Breakpoint/StoppointCallbackContext.h"
304640cde1SColin Riley #include "lldb/Target/RegisterContext.h"
3115f2bd95SEwan Crawford #include "lldb/Expression/UserExpression.h"
324640cde1SColin Riley #include "lldb/Symbol/VariableList.h"
335ec532a9SColin Riley 
345ec532a9SColin Riley using namespace lldb;
355ec532a9SColin Riley using namespace lldb_private;
3698156583SEwan Crawford using namespace lldb_renderscript;
375ec532a9SColin Riley 
3878f339d1SEwan Crawford namespace {
3978f339d1SEwan Crawford 
4078f339d1SEwan Crawford // The empirical_type adds a basic level of validation to arbitrary data
4178f339d1SEwan Crawford // allowing us to track if data has been discovered and stored or not.
4278f339d1SEwan Crawford // An empirical_type will be marked as valid only if it has been explicitly assigned to.
4378f339d1SEwan Crawford template <typename type_t>
4478f339d1SEwan Crawford class empirical_type
4578f339d1SEwan Crawford {
4678f339d1SEwan Crawford   public:
4778f339d1SEwan Crawford     // Ctor. Contents is invalid when constructed.
4878f339d1SEwan Crawford     empirical_type()
4978f339d1SEwan Crawford         : valid(false)
5078f339d1SEwan Crawford     {}
5178f339d1SEwan Crawford 
5278f339d1SEwan Crawford     // Return true and copy contents to out if valid, else return false.
5378f339d1SEwan Crawford     bool get(type_t& out) const
5478f339d1SEwan Crawford     {
5578f339d1SEwan Crawford         if (valid)
5678f339d1SEwan Crawford             out = data;
5778f339d1SEwan Crawford         return valid;
5878f339d1SEwan Crawford     }
5978f339d1SEwan Crawford 
6078f339d1SEwan Crawford     // Return a pointer to the contents or nullptr if it was not valid.
6178f339d1SEwan Crawford     const type_t* get() const
6278f339d1SEwan Crawford     {
6378f339d1SEwan Crawford         return valid ? &data : nullptr;
6478f339d1SEwan Crawford     }
6578f339d1SEwan Crawford 
6678f339d1SEwan Crawford     // Assign data explicitly.
6778f339d1SEwan Crawford     void set(const type_t in)
6878f339d1SEwan Crawford     {
6978f339d1SEwan Crawford         data = in;
7078f339d1SEwan Crawford         valid = true;
7178f339d1SEwan Crawford     }
7278f339d1SEwan Crawford 
7378f339d1SEwan Crawford     // Mark contents as invalid.
7478f339d1SEwan Crawford     void invalidate()
7578f339d1SEwan Crawford     {
7678f339d1SEwan Crawford         valid = false;
7778f339d1SEwan Crawford     }
7878f339d1SEwan Crawford 
7978f339d1SEwan Crawford     // Returns true if this type contains valid data.
8078f339d1SEwan Crawford     bool isValid() const
8178f339d1SEwan Crawford     {
8278f339d1SEwan Crawford         return valid;
8378f339d1SEwan Crawford     }
8478f339d1SEwan Crawford 
8578f339d1SEwan Crawford     // Assignment operator.
8678f339d1SEwan Crawford     empirical_type<type_t>& operator = (const type_t in)
8778f339d1SEwan Crawford     {
8878f339d1SEwan Crawford         set(in);
8978f339d1SEwan Crawford         return *this;
9078f339d1SEwan Crawford     }
9178f339d1SEwan Crawford 
9278f339d1SEwan Crawford     // Dereference operator returns contents.
9378f339d1SEwan Crawford     // Warning: Will assert if not valid so use only when you know data is valid.
9478f339d1SEwan Crawford     const type_t& operator * () const
9578f339d1SEwan Crawford     {
9678f339d1SEwan Crawford         assert(valid);
9778f339d1SEwan Crawford         return data;
9878f339d1SEwan Crawford     }
9978f339d1SEwan Crawford 
10078f339d1SEwan Crawford   protected:
10178f339d1SEwan Crawford     bool valid;
10278f339d1SEwan Crawford     type_t data;
10378f339d1SEwan Crawford };
10478f339d1SEwan Crawford 
10578f339d1SEwan Crawford } // namespace {}
10678f339d1SEwan Crawford 
10778f339d1SEwan Crawford // The ScriptDetails class collects data associated with a single script instance.
10878f339d1SEwan Crawford struct RenderScriptRuntime::ScriptDetails
10978f339d1SEwan Crawford {
11078f339d1SEwan Crawford     ~ScriptDetails() {};
11178f339d1SEwan Crawford 
11278f339d1SEwan Crawford     enum ScriptType
11378f339d1SEwan Crawford     {
11478f339d1SEwan Crawford         eScript,
11578f339d1SEwan Crawford         eScriptC
11678f339d1SEwan Crawford     };
11778f339d1SEwan Crawford 
11878f339d1SEwan Crawford     // The derived type of the script.
11978f339d1SEwan Crawford     empirical_type<ScriptType> type;
12078f339d1SEwan Crawford     // The name of the original source file.
12178f339d1SEwan Crawford     empirical_type<std::string> resName;
12278f339d1SEwan Crawford     // Path to script .so file on the device.
12378f339d1SEwan Crawford     empirical_type<std::string> scriptDyLib;
12478f339d1SEwan Crawford     // Directory where kernel objects are cached on device.
12578f339d1SEwan Crawford     empirical_type<std::string> cacheDir;
12678f339d1SEwan Crawford     // Pointer to the context which owns this script.
12778f339d1SEwan Crawford     empirical_type<lldb::addr_t> context;
12878f339d1SEwan Crawford     // Pointer to the script object itself.
12978f339d1SEwan Crawford     empirical_type<lldb::addr_t> script;
13078f339d1SEwan Crawford };
13178f339d1SEwan Crawford 
13278f339d1SEwan Crawford // This AllocationDetails class collects data associated with a single
13378f339d1SEwan Crawford // allocation instance.
13478f339d1SEwan Crawford struct RenderScriptRuntime::AllocationDetails
13578f339d1SEwan Crawford {
13615f2bd95SEwan Crawford    // Taken from rsDefines.h
13715f2bd95SEwan Crawford    enum DataKind
13815f2bd95SEwan Crawford    {
13915f2bd95SEwan Crawford        RS_KIND_USER,
14015f2bd95SEwan Crawford        RS_KIND_PIXEL_L = 7,
14115f2bd95SEwan Crawford        RS_KIND_PIXEL_A,
14215f2bd95SEwan Crawford        RS_KIND_PIXEL_LA,
14315f2bd95SEwan Crawford        RS_KIND_PIXEL_RGB,
14415f2bd95SEwan Crawford        RS_KIND_PIXEL_RGBA,
14515f2bd95SEwan Crawford        RS_KIND_PIXEL_DEPTH,
14615f2bd95SEwan Crawford        RS_KIND_PIXEL_YUV,
14715f2bd95SEwan Crawford        RS_KIND_INVALID = 100
14815f2bd95SEwan Crawford    };
14978f339d1SEwan Crawford 
15015f2bd95SEwan Crawford    // Taken from rsDefines.h
15178f339d1SEwan Crawford    enum DataType
15278f339d1SEwan Crawford    {
15315f2bd95SEwan Crawford        RS_TYPE_NONE = 0,
15415f2bd95SEwan Crawford        RS_TYPE_FLOAT_16,
15515f2bd95SEwan Crawford        RS_TYPE_FLOAT_32,
15615f2bd95SEwan Crawford        RS_TYPE_FLOAT_64,
15715f2bd95SEwan Crawford        RS_TYPE_SIGNED_8,
15815f2bd95SEwan Crawford        RS_TYPE_SIGNED_16,
15915f2bd95SEwan Crawford        RS_TYPE_SIGNED_32,
16015f2bd95SEwan Crawford        RS_TYPE_SIGNED_64,
16115f2bd95SEwan Crawford        RS_TYPE_UNSIGNED_8,
16215f2bd95SEwan Crawford        RS_TYPE_UNSIGNED_16,
16315f2bd95SEwan Crawford        RS_TYPE_UNSIGNED_32,
16415f2bd95SEwan Crawford        RS_TYPE_UNSIGNED_64,
16515f2bd95SEwan Crawford        RS_TYPE_BOOLEAN
16678f339d1SEwan Crawford     };
16778f339d1SEwan Crawford 
16815f2bd95SEwan Crawford     struct Dimension
16978f339d1SEwan Crawford     {
17015f2bd95SEwan Crawford         uint32_t dim_1;
17115f2bd95SEwan Crawford         uint32_t dim_2;
17215f2bd95SEwan Crawford         uint32_t dim_3;
17315f2bd95SEwan Crawford         uint32_t cubeMap;
17415f2bd95SEwan Crawford 
17515f2bd95SEwan Crawford         Dimension()
17615f2bd95SEwan Crawford         {
17715f2bd95SEwan Crawford              dim_1 = 0;
17815f2bd95SEwan Crawford              dim_2 = 0;
17915f2bd95SEwan Crawford              dim_3 = 0;
18015f2bd95SEwan Crawford              cubeMap = 0;
18115f2bd95SEwan Crawford         }
18278f339d1SEwan Crawford     };
18378f339d1SEwan Crawford 
18455232f09SEwan Crawford     // Header for reading and writing allocation contents
18555232f09SEwan Crawford     // to a binary file.
18655232f09SEwan Crawford     struct FileHeader
18755232f09SEwan Crawford     {
18855232f09SEwan Crawford         uint8_t ident[4];      // ASCII 'RSAD' identifying the file
18955232f09SEwan Crawford         uint16_t hdr_size;     // Header size in bytes, for backwards compatability
19055232f09SEwan Crawford         uint16_t type;         // DataType enum
19155232f09SEwan Crawford         uint32_t kind;         // DataKind enum
19255232f09SEwan Crawford         uint32_t dims[3];      // Dimensions
19355232f09SEwan Crawford         uint32_t element_size; // Size of a single element, including padding
19455232f09SEwan Crawford     };
19555232f09SEwan Crawford 
19615f2bd95SEwan Crawford     // Monotonically increasing from 1
19715f2bd95SEwan Crawford     static unsigned int ID;
19815f2bd95SEwan Crawford 
19915f2bd95SEwan Crawford     // Maps Allocation DataType enum and vector size to printable strings
20015f2bd95SEwan Crawford     // using mapping from RenderScript numerical types summary documentation
20115f2bd95SEwan Crawford     static const char* RsDataTypeToString[][4];
20215f2bd95SEwan Crawford 
20315f2bd95SEwan Crawford     // Maps Allocation DataKind enum to printable strings
20415f2bd95SEwan Crawford     static const char* RsDataKindToString[];
20515f2bd95SEwan Crawford 
206a0f08674SEwan Crawford     // Maps allocation types to format sizes for printing.
207a0f08674SEwan Crawford     static const unsigned int RSTypeToFormat[][3];
208a0f08674SEwan Crawford 
20915f2bd95SEwan Crawford     // Give each allocation an ID as a way
21015f2bd95SEwan Crawford     // for commands to reference it.
21115f2bd95SEwan Crawford     const unsigned int id;
21215f2bd95SEwan Crawford 
21315f2bd95SEwan Crawford     empirical_type<DataType> type;            // Type of each data pointer stored by the allocation
21415f2bd95SEwan Crawford     empirical_type<DataKind> type_kind;       // Defines pixel type if Allocation is created from an image
21515f2bd95SEwan Crawford     empirical_type<uint32_t> type_vec_size;   // Vector size of each data point, e.g '4' for uchar4
21615f2bd95SEwan Crawford     empirical_type<Dimension> dimension;      // Dimensions of the Allocation
21715f2bd95SEwan Crawford     empirical_type<lldb::addr_t> address;     // Pointer to address of the RS Allocation
21815f2bd95SEwan Crawford     empirical_type<lldb::addr_t> data_ptr;    // Pointer to the data held by the Allocation
21915f2bd95SEwan Crawford     empirical_type<lldb::addr_t> type_ptr;    // Pointer to the RS Type of the Allocation
22015f2bd95SEwan Crawford     empirical_type<lldb::addr_t> element_ptr; // Pointer to the RS Element of the Type
22115f2bd95SEwan Crawford     empirical_type<lldb::addr_t> context;     // Pointer to the RS Context of the Allocation
222a0f08674SEwan Crawford     empirical_type<uint32_t> size;            // Size of the allocation
223a0f08674SEwan Crawford     empirical_type<uint32_t> stride;          // Stride between rows of the allocation
22415f2bd95SEwan Crawford 
22515f2bd95SEwan Crawford     // Give each allocation an id, so we can reference it in user commands.
22615f2bd95SEwan Crawford     AllocationDetails(): id(ID++)
22715f2bd95SEwan Crawford     {
22815f2bd95SEwan Crawford     }
22915f2bd95SEwan Crawford 
23015f2bd95SEwan Crawford };
23115f2bd95SEwan Crawford 
23215f2bd95SEwan Crawford unsigned int RenderScriptRuntime::AllocationDetails::ID = 1;
23315f2bd95SEwan Crawford 
23415f2bd95SEwan Crawford const char* RenderScriptRuntime::AllocationDetails::RsDataKindToString[] =
23515f2bd95SEwan Crawford {
23615f2bd95SEwan Crawford    "User",
23715f2bd95SEwan Crawford    "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7
23815f2bd95SEwan Crawford    "Undefined", "Undefined", "Undefined",
23915f2bd95SEwan Crawford    "L Pixel",
24015f2bd95SEwan Crawford    "A Pixel",
24115f2bd95SEwan Crawford    "LA Pixel",
24215f2bd95SEwan Crawford    "RGB Pixel",
24315f2bd95SEwan Crawford    "RGBA Pixel",
24415f2bd95SEwan Crawford    "Pixel Depth",
24515f2bd95SEwan Crawford    "YUV Pixel"
24615f2bd95SEwan Crawford };
24715f2bd95SEwan Crawford 
24815f2bd95SEwan Crawford const char* RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] =
24915f2bd95SEwan Crawford {
25015f2bd95SEwan Crawford     {"None", "None", "None", "None"},
25115f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
25215f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
25315f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
25415f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
25515f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
25615f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
25715f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
25815f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
25915f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
26015f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
26115f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
26215f2bd95SEwan Crawford     {"bool", "bool2", "bool3", "bool4"}
26378f339d1SEwan Crawford };
26478f339d1SEwan Crawford 
265a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
266a0f08674SEwan Crawford enum TypeToFormatIndex {
267a0f08674SEwan Crawford    eFormatSingle = 0,
268a0f08674SEwan Crawford    eFormatVector,
269a0f08674SEwan Crawford    eElementSize
270a0f08674SEwan Crawford };
271a0f08674SEwan Crawford 
272a0f08674SEwan Crawford // { format enum of single element, format enum of element vector, size of element}
273a0f08674SEwan Crawford const unsigned int RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] =
274a0f08674SEwan Crawford {
275a0f08674SEwan Crawford     {eFormatHex, eFormatHex, 1}, // RS_TYPE_NONE
276a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat16, 2}, // RS_TYPE_FLOAT_16
277a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)}, // RS_TYPE_FLOAT_32
278a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)}, // RS_TYPE_FLOAT_64
279a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)}, // RS_TYPE_SIGNED_8
280a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)}, // RS_TYPE_SIGNED_16
281a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)}, // RS_TYPE_SIGNED_32
282a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)}, // RS_TYPE_SIGNED_64
283a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)}, // RS_TYPE_UNSIGNED_8
284a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_16
285a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)}, // RS_TYPE_UNSIGNED_32
286a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)}, // RS_TYPE_UNSIGNED_64
287a0f08674SEwan Crawford     {eFormatBoolean, eFormatBoolean, sizeof(bool)} // RS_TYPE_BOOL
288a0f08674SEwan Crawford };
289a0f08674SEwan Crawford 
2905ec532a9SColin Riley //------------------------------------------------------------------
2915ec532a9SColin Riley // Static Functions
2925ec532a9SColin Riley //------------------------------------------------------------------
2935ec532a9SColin Riley LanguageRuntime *
2945ec532a9SColin Riley RenderScriptRuntime::CreateInstance(Process *process, lldb::LanguageType language)
2955ec532a9SColin Riley {
2965ec532a9SColin Riley 
2975ec532a9SColin Riley     if (language == eLanguageTypeExtRenderScript)
2985ec532a9SColin Riley         return new RenderScriptRuntime(process);
2995ec532a9SColin Riley     else
3005ec532a9SColin Riley         return NULL;
3015ec532a9SColin Riley }
3025ec532a9SColin Riley 
30398156583SEwan Crawford // Callback with a module to search for matching symbols.
30498156583SEwan Crawford // We first check that the module contains RS kernels.
30598156583SEwan Crawford // Then look for a symbol which matches our kernel name.
30698156583SEwan Crawford // The breakpoint address is finally set using the address of this symbol.
30798156583SEwan Crawford Searcher::CallbackReturn
30898156583SEwan Crawford RSBreakpointResolver::SearchCallback(SearchFilter &filter,
30998156583SEwan Crawford                                      SymbolContext &context,
31098156583SEwan Crawford                                      Address*,
31198156583SEwan Crawford                                      bool)
31298156583SEwan Crawford {
31398156583SEwan Crawford     ModuleSP module = context.module_sp;
31498156583SEwan Crawford 
31598156583SEwan Crawford     if (!module)
31698156583SEwan Crawford         return Searcher::eCallbackReturnContinue;
31798156583SEwan Crawford 
31898156583SEwan Crawford     // Is this a module containing renderscript kernels?
31998156583SEwan Crawford     if (nullptr == module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData))
32098156583SEwan Crawford         return Searcher::eCallbackReturnContinue;
32198156583SEwan Crawford 
32298156583SEwan Crawford     // Attempt to set a breakpoint on the kernel name symbol within the module library.
32398156583SEwan Crawford     // If it's not found, it's likely debug info is unavailable - try to set a
32498156583SEwan Crawford     // breakpoint on <name>.expand.
32598156583SEwan Crawford 
32698156583SEwan Crawford     const Symbol* kernel_sym = module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
32798156583SEwan Crawford     if (!kernel_sym)
32898156583SEwan Crawford     {
32998156583SEwan Crawford         std::string kernel_name_expanded(m_kernel_name.AsCString());
33098156583SEwan Crawford         kernel_name_expanded.append(".expand");
33198156583SEwan Crawford         kernel_sym = module->FindFirstSymbolWithNameAndType(ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
33298156583SEwan Crawford     }
33398156583SEwan Crawford 
33498156583SEwan Crawford     if (kernel_sym)
33598156583SEwan Crawford     {
33698156583SEwan Crawford         Address bp_addr = kernel_sym->GetAddress();
33798156583SEwan Crawford         if (filter.AddressPasses(bp_addr))
33898156583SEwan Crawford             m_breakpoint->AddLocation(bp_addr);
33998156583SEwan Crawford     }
34098156583SEwan Crawford 
34198156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
34298156583SEwan Crawford }
34398156583SEwan Crawford 
3445ec532a9SColin Riley void
3455ec532a9SColin Riley RenderScriptRuntime::Initialize()
3465ec532a9SColin Riley {
3474640cde1SColin Riley     PluginManager::RegisterPlugin(GetPluginNameStatic(), "RenderScript language support", CreateInstance, GetCommandObject);
3485ec532a9SColin Riley }
3495ec532a9SColin Riley 
3505ec532a9SColin Riley void
3515ec532a9SColin Riley RenderScriptRuntime::Terminate()
3525ec532a9SColin Riley {
3535ec532a9SColin Riley     PluginManager::UnregisterPlugin(CreateInstance);
3545ec532a9SColin Riley }
3555ec532a9SColin Riley 
3565ec532a9SColin Riley lldb_private::ConstString
3575ec532a9SColin Riley RenderScriptRuntime::GetPluginNameStatic()
3585ec532a9SColin Riley {
3595ec532a9SColin Riley     static ConstString g_name("renderscript");
3605ec532a9SColin Riley     return g_name;
3615ec532a9SColin Riley }
3625ec532a9SColin Riley 
363ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
364ef20b08fSColin Riley RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp)
365ef20b08fSColin Riley {
366ef20b08fSColin Riley     if (module_sp)
367ef20b08fSColin Riley     {
368ef20b08fSColin Riley         // Is this a module containing renderscript kernels?
369ef20b08fSColin Riley         const Symbol *info_sym = module_sp->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
370ef20b08fSColin Riley         if (info_sym)
371ef20b08fSColin Riley         {
372ef20b08fSColin Riley             return eModuleKindKernelObj;
373ef20b08fSColin Riley         }
3744640cde1SColin Riley 
3754640cde1SColin Riley         // Is this the main RS runtime library
3764640cde1SColin Riley         const ConstString rs_lib("libRS.so");
3774640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_lib)
3784640cde1SColin Riley         {
3794640cde1SColin Riley             return eModuleKindLibRS;
3804640cde1SColin Riley         }
3814640cde1SColin Riley 
3824640cde1SColin Riley         const ConstString rs_driverlib("libRSDriver.so");
3834640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_driverlib)
3844640cde1SColin Riley         {
3854640cde1SColin Riley             return eModuleKindDriver;
3864640cde1SColin Riley         }
3874640cde1SColin Riley 
38815f2bd95SEwan Crawford         const ConstString rs_cpureflib("libRSCpuRef.so");
3894640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib)
3904640cde1SColin Riley         {
3914640cde1SColin Riley             return eModuleKindImpl;
3924640cde1SColin Riley         }
3934640cde1SColin Riley 
394ef20b08fSColin Riley     }
395ef20b08fSColin Riley     return eModuleKindIgnored;
396ef20b08fSColin Riley }
397ef20b08fSColin Riley 
398ef20b08fSColin Riley bool
399ef20b08fSColin Riley RenderScriptRuntime::IsRenderScriptModule(const lldb::ModuleSP &module_sp)
400ef20b08fSColin Riley {
401ef20b08fSColin Riley     return GetModuleKind(module_sp) != eModuleKindIgnored;
402ef20b08fSColin Riley }
403ef20b08fSColin Riley 
404ef20b08fSColin Riley 
405ef20b08fSColin Riley void
406ef20b08fSColin Riley RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list )
407ef20b08fSColin Riley {
408ef20b08fSColin Riley     Mutex::Locker locker (module_list.GetMutex ());
409ef20b08fSColin Riley 
410ef20b08fSColin Riley     size_t num_modules = module_list.GetSize();
411ef20b08fSColin Riley     for (size_t i = 0; i < num_modules; i++)
412ef20b08fSColin Riley     {
413ef20b08fSColin Riley         auto mod = module_list.GetModuleAtIndex (i);
414ef20b08fSColin Riley         if (IsRenderScriptModule (mod))
415ef20b08fSColin Riley         {
416ef20b08fSColin Riley             LoadModule(mod);
417ef20b08fSColin Riley         }
418ef20b08fSColin Riley     }
419ef20b08fSColin Riley }
420ef20b08fSColin Riley 
421ef20b08fSColin Riley 
4225ec532a9SColin Riley //------------------------------------------------------------------
4235ec532a9SColin Riley // PluginInterface protocol
4245ec532a9SColin Riley //------------------------------------------------------------------
4255ec532a9SColin Riley lldb_private::ConstString
4265ec532a9SColin Riley RenderScriptRuntime::GetPluginName()
4275ec532a9SColin Riley {
4285ec532a9SColin Riley     return GetPluginNameStatic();
4295ec532a9SColin Riley }
4305ec532a9SColin Riley 
4315ec532a9SColin Riley uint32_t
4325ec532a9SColin Riley RenderScriptRuntime::GetPluginVersion()
4335ec532a9SColin Riley {
4345ec532a9SColin Riley     return 1;
4355ec532a9SColin Riley }
4365ec532a9SColin Riley 
4375ec532a9SColin Riley bool
4385ec532a9SColin Riley RenderScriptRuntime::IsVTableName(const char *name)
4395ec532a9SColin Riley {
4405ec532a9SColin Riley     return false;
4415ec532a9SColin Riley }
4425ec532a9SColin Riley 
4435ec532a9SColin Riley bool
4445ec532a9SColin Riley RenderScriptRuntime::GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic,
4450b6003f3SEnrico Granata                                               TypeAndOrName &class_type_or_name, Address &address,
4460b6003f3SEnrico Granata                                               Value::ValueType &value_type)
4475ec532a9SColin Riley {
4485ec532a9SColin Riley     return false;
4495ec532a9SColin Riley }
4505ec532a9SColin Riley 
451c74275bcSEnrico Granata TypeAndOrName
452c74275bcSEnrico Granata RenderScriptRuntime::FixUpDynamicType (const TypeAndOrName& type_and_or_name,
4537eed4877SEnrico Granata                                        ValueObject& static_value)
454c74275bcSEnrico Granata {
455c74275bcSEnrico Granata     return type_and_or_name;
456c74275bcSEnrico Granata }
457c74275bcSEnrico Granata 
4585ec532a9SColin Riley bool
4595ec532a9SColin Riley RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value)
4605ec532a9SColin Riley {
4615ec532a9SColin Riley     return false;
4625ec532a9SColin Riley }
4635ec532a9SColin Riley 
4645ec532a9SColin Riley lldb::BreakpointResolverSP
4655ec532a9SColin Riley RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp, bool throw_bp)
4665ec532a9SColin Riley {
4675ec532a9SColin Riley     BreakpointResolverSP resolver_sp;
4685ec532a9SColin Riley     return resolver_sp;
4695ec532a9SColin Riley }
4705ec532a9SColin Riley 
4714640cde1SColin Riley 
4724640cde1SColin Riley const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
4734640cde1SColin Riley {
4744640cde1SColin Riley     //rsdScript
47582780287SAidan Dodds     {
47682780287SAidan Dodds         "rsdScriptInit", //name
47782780287SAidan Dodds         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhjj", // symbol name 32 bit
47882780287SAidan Dodds         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhmj", // symbol name 64 bit
47982780287SAidan Dodds         0, // version
48082780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
48182780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureScriptInit1 // handler
48282780287SAidan Dodds     },
48382780287SAidan Dodds     {
48482780287SAidan Dodds         "rsdScriptInvokeForEach", // name
48582780287SAidan Dodds         "_Z22rsdScriptInvokeForEachPKN7android12renderscript7ContextEPNS0_6ScriptEjPKNS0_10AllocationEPS6_PKvjPK12RsScriptCall", // symbol name 32bit
48682780287SAidan Dodds         "_Z22rsdScriptInvokeForEachPKN7android12renderscript7ContextEPNS0_6ScriptEjPKNS0_10AllocationEPS6_PKvmPK12RsScriptCall", // symbol name 64bit
48782780287SAidan Dodds         0, // version
48882780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
48982780287SAidan Dodds         nullptr // handler
49082780287SAidan Dodds     },
49182780287SAidan Dodds     {
49282780287SAidan Dodds         "rsdScriptInvokeForEachMulti", // name
49382780287SAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall", // symbol name 32bit
49482780287SAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall", // symbol name 64bit
49582780287SAidan Dodds         0, // version
49682780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
49782780287SAidan Dodds         nullptr // handler
49882780287SAidan Dodds     },
49982780287SAidan Dodds     {
50082780287SAidan Dodds         "rsdScriptInvokeFunction", // name
50182780287SAidan Dodds         "_Z23rsdScriptInvokeFunctionPKN7android12renderscript7ContextEPNS0_6ScriptEjPKvj", // symbol name 32bit
50282780287SAidan Dodds         "_Z23rsdScriptInvokeFunctionPKN7android12renderscript7ContextEPNS0_6ScriptEjPKvm", // symbol name 64bit
50382780287SAidan Dodds         0, // version
50482780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
50582780287SAidan Dodds         nullptr // handler
50682780287SAidan Dodds     },
50782780287SAidan Dodds     {
50882780287SAidan Dodds         "rsdScriptSetGlobalVar", // name
50982780287SAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvj", // symbol name 32bit
51082780287SAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvm", // symbol name 64bit
51182780287SAidan Dodds         0, // version
51282780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
51382780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar1 // handler
51482780287SAidan Dodds     },
5154640cde1SColin Riley 
5164640cde1SColin Riley     //rsdAllocation
51782780287SAidan Dodds     {
51882780287SAidan Dodds         "rsdAllocationInit", // name
51982780287SAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 32bit
52082780287SAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 64bit
52182780287SAidan Dodds         0, // version
52282780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
52382780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureAllocationInit1 // handler
52482780287SAidan Dodds     },
52582780287SAidan Dodds     {
52682780287SAidan Dodds         "rsdAllocationRead2D", //name
52782780287SAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvjj", // symbol name 32bit
52882780287SAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvmm", // symbol name 64bit
52982780287SAidan Dodds         0, // version
53082780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
53182780287SAidan Dodds         nullptr // handler
53282780287SAidan Dodds     },
5334640cde1SColin Riley };
5344640cde1SColin Riley const size_t RenderScriptRuntime::s_runtimeHookCount = sizeof(s_runtimeHookDefns)/sizeof(s_runtimeHookDefns[0]);
5354640cde1SColin Riley 
5364640cde1SColin Riley 
5374640cde1SColin Riley bool
5384640cde1SColin Riley RenderScriptRuntime::HookCallback(void *baton, StoppointCallbackContext *ctx, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
5394640cde1SColin Riley {
5404640cde1SColin Riley     RuntimeHook* hook_info = (RuntimeHook*)baton;
5414640cde1SColin Riley     ExecutionContext context(ctx->exe_ctx_ref);
5424640cde1SColin Riley 
5434640cde1SColin Riley     RenderScriptRuntime *lang_rt = (RenderScriptRuntime *)context.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
5444640cde1SColin Riley 
5454640cde1SColin Riley     lang_rt->HookCallback(hook_info, context);
5464640cde1SColin Riley 
5474640cde1SColin Riley     return false;
5484640cde1SColin Riley }
5494640cde1SColin Riley 
5504640cde1SColin Riley 
5514640cde1SColin Riley void
5524640cde1SColin Riley RenderScriptRuntime::HookCallback(RuntimeHook* hook_info, ExecutionContext& context)
5534640cde1SColin Riley {
5544640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
5554640cde1SColin Riley 
5564640cde1SColin Riley     if (log)
5574640cde1SColin Riley         log->Printf ("RenderScriptRuntime::HookCallback - '%s' .", hook_info->defn->name);
5584640cde1SColin Riley 
5594640cde1SColin Riley     if (hook_info->defn->grabber)
5604640cde1SColin Riley     {
5614640cde1SColin Riley         (this->*(hook_info->defn->grabber))(hook_info, context);
5624640cde1SColin Riley     }
5634640cde1SColin Riley }
5644640cde1SColin Riley 
5654640cde1SColin Riley 
5664640cde1SColin Riley bool
56782780287SAidan Dodds RenderScriptRuntime::GetArgSimple(ExecutionContext &context, uint32_t arg, uint64_t *data)
5684640cde1SColin Riley {
5694640cde1SColin Riley     if (!data)
5704640cde1SColin Riley         return false;
5714640cde1SColin Riley 
57282780287SAidan Dodds     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
5734640cde1SColin Riley     Error error;
5744640cde1SColin Riley     RegisterContext* reg_ctx = context.GetRegisterContext();
5754640cde1SColin Riley     Process* process = context.GetProcessPtr();
57682780287SAidan Dodds     bool success = false; // return value
5774640cde1SColin Riley 
57882780287SAidan Dodds     if (!context.GetTargetPtr())
57982780287SAidan Dodds     {
58082780287SAidan Dodds         if (log)
58182780287SAidan Dodds             log->Printf("RenderScriptRuntime::GetArgSimple - Invalid target");
58282780287SAidan Dodds 
58382780287SAidan Dodds         return false;
58482780287SAidan Dodds     }
58582780287SAidan Dodds 
58682780287SAidan Dodds     switch (context.GetTargetPtr()->GetArchitecture().GetMachine())
58782780287SAidan Dodds     {
58882780287SAidan Dodds         case llvm::Triple::ArchType::x86:
5894640cde1SColin Riley         {
5904640cde1SColin Riley             uint64_t sp = reg_ctx->GetSP();
5914640cde1SColin Riley             uint32_t offset = (1 + arg) * sizeof(uint32_t);
59282780287SAidan Dodds             uint32_t result = 0;
59382780287SAidan Dodds             process->ReadMemory(sp + offset, &result, sizeof(uint32_t), error);
5944640cde1SColin Riley             if (error.Fail())
5954640cde1SColin Riley             {
5964640cde1SColin Riley                 if (log)
59782780287SAidan Dodds                     log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading X86 stack: %s.", error.AsCString());
5984640cde1SColin Riley             }
59982780287SAidan Dodds             else
6004640cde1SColin Riley             {
60182780287SAidan Dodds                 *data = result;
60282780287SAidan Dodds                 success = true;
60382780287SAidan Dodds             }
60482780287SAidan Dodds 
60582780287SAidan Dodds             break;
60682780287SAidan Dodds         }
60782780287SAidan Dodds         case llvm::Triple::ArchType::arm:
60882780287SAidan Dodds         {
60982780287SAidan Dodds             // arm 32 bit
6104640cde1SColin Riley             if (arg < 4)
6114640cde1SColin Riley             {
6124640cde1SColin Riley                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg);
6134640cde1SColin Riley                 RegisterValue rVal;
61402f1c5d1SEwan Crawford                 success = reg_ctx->ReadRegister(rArg, rVal);
61502f1c5d1SEwan Crawford                 if (success)
61602f1c5d1SEwan Crawford                 {
6174640cde1SColin Riley                     (*data) = rVal.GetAsUInt32();
61802f1c5d1SEwan Crawford                 }
61902f1c5d1SEwan Crawford                 else
62002f1c5d1SEwan Crawford                 {
62102f1c5d1SEwan Crawford                     if (log)
62202f1c5d1SEwan Crawford                         log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading ARM register: %d.", arg);
62302f1c5d1SEwan Crawford                 }
6244640cde1SColin Riley             }
6254640cde1SColin Riley             else
6264640cde1SColin Riley             {
6274640cde1SColin Riley                 uint64_t sp = reg_ctx->GetSP();
6284640cde1SColin Riley                 uint32_t offset = (arg-4) * sizeof(uint32_t);
6294640cde1SColin Riley                 process->ReadMemory(sp + offset, &data, sizeof(uint32_t), error);
6304640cde1SColin Riley                 if (error.Fail())
6314640cde1SColin Riley                 {
6324640cde1SColin Riley                     if (log)
63382780287SAidan Dodds                         log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading ARM stack: %s.", error.AsCString());
63482780287SAidan Dodds                 }
63582780287SAidan Dodds                 else
63682780287SAidan Dodds                 {
63782780287SAidan Dodds                     success = true;
6384640cde1SColin Riley                 }
6394640cde1SColin Riley             }
64082780287SAidan Dodds 
64182780287SAidan Dodds             break;
6424640cde1SColin Riley         }
64382780287SAidan Dodds         case llvm::Triple::ArchType::aarch64:
64482780287SAidan Dodds         {
64582780287SAidan Dodds             // arm 64 bit
64682780287SAidan Dodds             // first 8 arguments are in the registers
64782780287SAidan Dodds             if (arg < 8)
64882780287SAidan Dodds             {
64982780287SAidan Dodds                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg);
65082780287SAidan Dodds                 RegisterValue rVal;
65182780287SAidan Dodds                 success = reg_ctx->ReadRegister(rArg, rVal);
65282780287SAidan Dodds                 if (success)
65382780287SAidan Dodds                 {
65482780287SAidan Dodds                     *data = rVal.GetAsUInt64();
65582780287SAidan Dodds                 }
65682780287SAidan Dodds                 else
65782780287SAidan Dodds                 {
65882780287SAidan Dodds                     if (log)
65982780287SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple() - AARCH64 - Error while reading the argument #%d", arg);
66082780287SAidan Dodds                 }
66182780287SAidan Dodds             }
66282780287SAidan Dodds             else
66382780287SAidan Dodds             {
66482780287SAidan Dodds                 // @TODO: need to find the argument in the stack
66582780287SAidan Dodds                 if (log)
66682780287SAidan Dodds                     log->Printf("RenderScriptRuntime::GetArgSimple - AARCH64 - FOR #ARG >= 8 NOT IMPLEMENTED YET. Argument number: %d", arg);
66782780287SAidan Dodds             }
66882780287SAidan Dodds             break;
66982780287SAidan Dodds         }
67002f1c5d1SEwan Crawford         case llvm::Triple::ArchType::mips64el:
67102f1c5d1SEwan Crawford         {
67202f1c5d1SEwan Crawford             // read from the registers
67302f1c5d1SEwan Crawford             if (arg < 8)
67402f1c5d1SEwan Crawford             {
67502f1c5d1SEwan Crawford                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg + 4);
67602f1c5d1SEwan Crawford                 RegisterValue rVal;
67702f1c5d1SEwan Crawford                 success = reg_ctx->ReadRegister(rArg, rVal);
67802f1c5d1SEwan Crawford                 if (success)
67902f1c5d1SEwan Crawford                 {
68002f1c5d1SEwan Crawford                     (*data) = rVal.GetAsUInt64();
68102f1c5d1SEwan Crawford                 }
68202f1c5d1SEwan Crawford                 else
68302f1c5d1SEwan Crawford                 {
68402f1c5d1SEwan Crawford                     if (log)
68502f1c5d1SEwan Crawford                         log->Printf("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading the argument #%d", arg);
68602f1c5d1SEwan Crawford                 }
68702f1c5d1SEwan Crawford             }
68802f1c5d1SEwan Crawford 
68902f1c5d1SEwan Crawford             // read from the stack
69002f1c5d1SEwan Crawford             else
69102f1c5d1SEwan Crawford             {
69202f1c5d1SEwan Crawford                 uint64_t sp = reg_ctx->GetSP();
69302f1c5d1SEwan Crawford                 uint32_t offset = (arg - 8) * sizeof(uint64_t);
69402f1c5d1SEwan Crawford                 process->ReadMemory(sp + offset, &data, sizeof(uint64_t), error);
69502f1c5d1SEwan Crawford                 if (error.Fail())
69602f1c5d1SEwan Crawford                 {
69702f1c5d1SEwan Crawford                     if (log)
69802f1c5d1SEwan Crawford                         log->Printf ("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading Mips64 stack: %s.", error.AsCString());
69902f1c5d1SEwan Crawford                 }
70002f1c5d1SEwan Crawford                 else
70102f1c5d1SEwan Crawford                 {
70202f1c5d1SEwan Crawford                     success = true;
70302f1c5d1SEwan Crawford                 }
70402f1c5d1SEwan Crawford             }
70502f1c5d1SEwan Crawford 
70602f1c5d1SEwan Crawford             break;
70702f1c5d1SEwan Crawford         }
70882780287SAidan Dodds         default:
70982780287SAidan Dodds         {
71082780287SAidan Dodds             // invalid architecture
71182780287SAidan Dodds             if (log)
71282780287SAidan Dodds                 log->Printf("RenderScriptRuntime::GetArgSimple - Architecture not supported");
71382780287SAidan Dodds 
71482780287SAidan Dodds         }
71582780287SAidan Dodds     }
71682780287SAidan Dodds 
71782780287SAidan Dodds 
71882780287SAidan Dodds     return success;
7194640cde1SColin Riley }
7204640cde1SColin Riley 
7214640cde1SColin Riley void
7224640cde1SColin Riley RenderScriptRuntime::CaptureSetGlobalVar1(RuntimeHook* hook_info, ExecutionContext& context)
7234640cde1SColin Riley {
7244640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
7254640cde1SColin Riley 
7264640cde1SColin Riley     //Context, Script, int, data, length
7274640cde1SColin Riley 
72882780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
72982780287SAidan Dodds     uint64_t rs_script_u64 = 0U;
73082780287SAidan Dodds     uint64_t rs_id_u64 = 0U;
73182780287SAidan Dodds     uint64_t rs_data_u64 = 0U;
73282780287SAidan Dodds     uint64_t rs_length_u64 = 0U;
7334640cde1SColin Riley 
73482780287SAidan Dodds     bool success =
73582780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
73682780287SAidan Dodds         GetArgSimple(context, 1, &rs_script_u64) &&
73782780287SAidan Dodds         GetArgSimple(context, 2, &rs_id_u64) &&
73882780287SAidan Dodds         GetArgSimple(context, 3, &rs_data_u64) &&
73982780287SAidan Dodds         GetArgSimple(context, 4, &rs_length_u64);
7404640cde1SColin Riley 
74182780287SAidan Dodds     if (!success)
74282780287SAidan Dodds     {
74382780287SAidan Dodds         if (log)
74482780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureSetGlobalVar1 - Error while reading the function parameters");
74582780287SAidan Dodds         return;
74682780287SAidan Dodds     }
7474640cde1SColin Riley 
7484640cde1SColin Riley     if (log)
7494640cde1SColin Riley     {
7504640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64 ":%" PRIu64 "bytes.",
75182780287SAidan Dodds                         rs_context_u64, rs_script_u64, rs_id_u64, rs_data_u64, rs_length_u64);
7524640cde1SColin Riley 
75382780287SAidan Dodds         addr_t script_addr =  (addr_t)rs_script_u64;
7544640cde1SColin Riley         if (m_scriptMappings.find( script_addr ) != m_scriptMappings.end())
7554640cde1SColin Riley         {
7564640cde1SColin Riley             auto rsm = m_scriptMappings[script_addr];
75782780287SAidan Dodds             if (rs_id_u64 < rsm->m_globals.size())
7584640cde1SColin Riley             {
75982780287SAidan Dodds                 auto rsg = rsm->m_globals[rs_id_u64];
7604640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - Setting of '%s' within '%s' inferred", rsg.m_name.AsCString(),
7614640cde1SColin Riley                                 rsm->m_module->GetFileSpec().GetFilename().AsCString());
7624640cde1SColin Riley             }
7634640cde1SColin Riley         }
7644640cde1SColin Riley     }
7654640cde1SColin Riley }
7664640cde1SColin Riley 
7674640cde1SColin Riley void
7684640cde1SColin Riley RenderScriptRuntime::CaptureAllocationInit1(RuntimeHook* hook_info, ExecutionContext& context)
7694640cde1SColin Riley {
7704640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
7714640cde1SColin Riley 
7724640cde1SColin Riley     //Context, Alloc, bool
7734640cde1SColin Riley 
77482780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
77582780287SAidan Dodds     uint64_t rs_alloc_u64 = 0U;
77682780287SAidan Dodds     uint64_t rs_forceZero_u64 = 0U;
7774640cde1SColin Riley 
77882780287SAidan Dodds     bool success =
77982780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
78082780287SAidan Dodds         GetArgSimple(context, 1, &rs_alloc_u64) &&
78182780287SAidan Dodds         GetArgSimple(context, 2, &rs_forceZero_u64);
78282780287SAidan Dodds     if (!success) // error case
78382780287SAidan Dodds     {
78482780287SAidan Dodds         if (log)
78582780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureAllocationInit1 - Error while reading the function parameters");
78682780287SAidan Dodds         return; // abort
78782780287SAidan Dodds     }
7884640cde1SColin Riley 
7894640cde1SColin Riley     if (log)
7904640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureAllocationInit1 - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
79182780287SAidan Dodds                         rs_context_u64, rs_alloc_u64, rs_forceZero_u64);
79278f339d1SEwan Crawford 
79378f339d1SEwan Crawford     AllocationDetails* alloc = LookUpAllocation(rs_alloc_u64, true);
79478f339d1SEwan Crawford     if (alloc)
79578f339d1SEwan Crawford         alloc->context = rs_context_u64;
7964640cde1SColin Riley }
7974640cde1SColin Riley 
7984640cde1SColin Riley void
7994640cde1SColin Riley RenderScriptRuntime::CaptureScriptInit1(RuntimeHook* hook_info, ExecutionContext& context)
8004640cde1SColin Riley {
8014640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
8024640cde1SColin Riley 
8034640cde1SColin Riley     //Context, Script, resname Str, cachedir Str
8044640cde1SColin Riley     Error error;
8054640cde1SColin Riley     Process* process = context.GetProcessPtr();
8064640cde1SColin Riley 
80782780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
80882780287SAidan Dodds     uint64_t rs_script_u64 = 0U;
80982780287SAidan Dodds     uint64_t rs_resnameptr_u64 = 0U;
81082780287SAidan Dodds     uint64_t rs_cachedirptr_u64 = 0U;
8114640cde1SColin Riley 
8124640cde1SColin Riley     std::string resname;
8134640cde1SColin Riley     std::string cachedir;
8144640cde1SColin Riley 
81582780287SAidan Dodds     // read the function parameters
81682780287SAidan Dodds     bool success =
81782780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
81882780287SAidan Dodds         GetArgSimple(context, 1, &rs_script_u64) &&
81982780287SAidan Dodds         GetArgSimple(context, 2, &rs_resnameptr_u64) &&
82082780287SAidan Dodds         GetArgSimple(context, 3, &rs_cachedirptr_u64);
8214640cde1SColin Riley 
82282780287SAidan Dodds     if (!success)
82382780287SAidan Dodds     {
82482780287SAidan Dodds         if (log)
82582780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureScriptInit1 - Error while reading the function parameters");
82682780287SAidan Dodds         return;
82782780287SAidan Dodds     }
82882780287SAidan Dodds 
82982780287SAidan Dodds     process->ReadCStringFromMemory((lldb::addr_t)rs_resnameptr_u64, resname, error);
8304640cde1SColin Riley     if (error.Fail())
8314640cde1SColin Riley     {
8324640cde1SColin Riley         if (log)
8334640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading resname: %s.", error.AsCString());
8344640cde1SColin Riley 
8354640cde1SColin Riley     }
8364640cde1SColin Riley 
83782780287SAidan Dodds     process->ReadCStringFromMemory((lldb::addr_t)rs_cachedirptr_u64, cachedir, error);
8384640cde1SColin Riley     if (error.Fail())
8394640cde1SColin Riley     {
8404640cde1SColin Riley         if (log)
8414640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading cachedir: %s.", error.AsCString());
8424640cde1SColin Riley     }
8434640cde1SColin Riley 
8444640cde1SColin Riley     if (log)
8454640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
84682780287SAidan Dodds                      rs_context_u64, rs_script_u64, resname.c_str(), cachedir.c_str());
8474640cde1SColin Riley 
8484640cde1SColin Riley     if (resname.size() > 0)
8494640cde1SColin Riley     {
8504640cde1SColin Riley         StreamString strm;
8514640cde1SColin Riley         strm.Printf("librs.%s.so", resname.c_str());
8524640cde1SColin Riley 
85378f339d1SEwan Crawford         ScriptDetails* script = LookUpScript(rs_script_u64, true);
85478f339d1SEwan Crawford         if (script)
85578f339d1SEwan Crawford         {
85678f339d1SEwan Crawford             script->type = ScriptDetails::eScriptC;
85778f339d1SEwan Crawford             script->cacheDir = cachedir;
85878f339d1SEwan Crawford             script->resName = resname;
85978f339d1SEwan Crawford             script->scriptDyLib = strm.GetData();
86078f339d1SEwan Crawford             script->context = addr_t(rs_context_u64);
86178f339d1SEwan Crawford         }
8624640cde1SColin Riley 
8634640cde1SColin Riley         if (log)
8644640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - '%s' tagged with context 0x%" PRIx64 " and script 0x%" PRIx64 ".",
86582780287SAidan Dodds                          strm.GetData(), rs_context_u64, rs_script_u64);
8664640cde1SColin Riley     }
8674640cde1SColin Riley     else if (log)
8684640cde1SColin Riley     {
8694640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - resource name invalid, Script not tagged");
8704640cde1SColin Riley     }
8714640cde1SColin Riley 
8724640cde1SColin Riley }
8734640cde1SColin Riley 
8744640cde1SColin Riley void
8754640cde1SColin Riley RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind)
8764640cde1SColin Riley {
8774640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
8784640cde1SColin Riley 
8794640cde1SColin Riley     if (!module)
8804640cde1SColin Riley     {
8814640cde1SColin Riley         return;
8824640cde1SColin Riley     }
8834640cde1SColin Riley 
88482780287SAidan Dodds     Target &target = GetProcess()->GetTarget();
88582780287SAidan Dodds     llvm::Triple::ArchType targetArchType = target.GetArchitecture().GetMachine();
88682780287SAidan Dodds 
88782780287SAidan Dodds     if (targetArchType != llvm::Triple::ArchType::x86
88882780287SAidan Dodds         && targetArchType != llvm::Triple::ArchType::arm
88902f1c5d1SEwan Crawford         && targetArchType != llvm::Triple::ArchType::aarch64
89002f1c5d1SEwan Crawford         && targetArchType != llvm::Triple::ArchType::mips64el
89102f1c5d1SEwan Crawford     )
8924640cde1SColin Riley     {
8934640cde1SColin Riley         if (log)
89402f1c5d1SEwan Crawford             log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to hook runtime. Only X86, ARM, Mips64 supported currently.");
8954640cde1SColin Riley 
8964640cde1SColin Riley         return;
8974640cde1SColin Riley     }
8984640cde1SColin Riley 
89982780287SAidan Dodds     uint32_t archByteSize = target.GetArchitecture().GetAddressByteSize();
9004640cde1SColin Riley 
9014640cde1SColin Riley     for (size_t idx = 0; idx < s_runtimeHookCount; idx++)
9024640cde1SColin Riley     {
9034640cde1SColin Riley         const HookDefn* hook_defn = &s_runtimeHookDefns[idx];
9044640cde1SColin Riley         if (hook_defn->kind != kind) {
9054640cde1SColin Riley             continue;
9064640cde1SColin Riley         }
9074640cde1SColin Riley 
90882780287SAidan Dodds         const char* symbol_name = (archByteSize == 4) ? hook_defn->symbol_name_m32 : hook_defn->symbol_name_m64;
90982780287SAidan Dodds 
91082780287SAidan Dodds         const Symbol *sym = module->FindFirstSymbolWithNameAndType(ConstString(symbol_name), eSymbolTypeCode);
91182780287SAidan Dodds         if (!sym){
91282780287SAidan Dodds             if (log){
91382780287SAidan Dodds                 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - ERROR: Symbol '%s' related to the function %s not found", symbol_name, hook_defn->name);
91482780287SAidan Dodds             }
91582780287SAidan Dodds             continue;
91682780287SAidan Dodds         }
9174640cde1SColin Riley 
918358cf1eaSGreg Clayton         addr_t addr = sym->GetLoadAddress(&target);
9194640cde1SColin Riley         if (addr == LLDB_INVALID_ADDRESS)
9204640cde1SColin Riley         {
9214640cde1SColin Riley             if (log)
9224640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to resolve the address of hook function '%s' with symbol '%s'.",
92382780287SAidan Dodds                              hook_defn->name, symbol_name);
9244640cde1SColin Riley             continue;
9254640cde1SColin Riley         }
92682780287SAidan Dodds         else
92782780287SAidan Dodds         {
92882780287SAidan Dodds             if (log)
92982780287SAidan Dodds                 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - Function %s, address resolved at 0x%" PRIx64, hook_defn->name, addr);
93082780287SAidan Dodds         }
9314640cde1SColin Riley 
9324640cde1SColin Riley         RuntimeHookSP hook(new RuntimeHook());
9334640cde1SColin Riley         hook->address = addr;
9344640cde1SColin Riley         hook->defn = hook_defn;
9354640cde1SColin Riley         hook->bp_sp = target.CreateBreakpoint(addr, true, false);
9364640cde1SColin Riley         hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
9374640cde1SColin Riley         m_runtimeHooks[addr] = hook;
9384640cde1SColin Riley         if (log)
9394640cde1SColin Riley         {
9404640cde1SColin Riley             log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Successfully hooked '%s' in '%s' version %" PRIu64 " at 0x%" PRIx64 ".",
9414640cde1SColin Riley                 hook_defn->name, module->GetFileSpec().GetFilename().AsCString(), (uint64_t)hook_defn->version, (uint64_t)addr);
9424640cde1SColin Riley         }
9434640cde1SColin Riley     }
9444640cde1SColin Riley }
9454640cde1SColin Riley 
9464640cde1SColin Riley void
9474640cde1SColin Riley RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp)
9484640cde1SColin Riley {
9494640cde1SColin Riley     if (!rsmodule_sp)
9504640cde1SColin Riley         return;
9514640cde1SColin Riley 
9524640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
9534640cde1SColin Riley 
9544640cde1SColin Riley     const ModuleSP module = rsmodule_sp->m_module;
9554640cde1SColin Riley     const FileSpec& file = module->GetPlatformFileSpec();
9564640cde1SColin Riley 
95778f339d1SEwan Crawford     // Iterate over all of the scripts that we currently know of.
95878f339d1SEwan Crawford     // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
9594640cde1SColin Riley     for (const auto & rs_script : m_scripts)
9604640cde1SColin Riley     {
96178f339d1SEwan Crawford         // Extract the expected .so file path for this script.
96278f339d1SEwan Crawford         std::string dylib;
96378f339d1SEwan Crawford         if (!rs_script->scriptDyLib.get(dylib))
96478f339d1SEwan Crawford             continue;
96578f339d1SEwan Crawford 
96678f339d1SEwan Crawford         // Only proceed if the module that has loaded corresponds to this script.
96778f339d1SEwan Crawford         if (file.GetFilename() != ConstString(dylib.c_str()))
96878f339d1SEwan Crawford             continue;
96978f339d1SEwan Crawford 
97078f339d1SEwan Crawford         // Obtain the script address which we use as a key.
97178f339d1SEwan Crawford         lldb::addr_t script;
97278f339d1SEwan Crawford         if (!rs_script->script.get(script))
97378f339d1SEwan Crawford             continue;
97478f339d1SEwan Crawford 
97578f339d1SEwan Crawford         // If we have a script mapping for the current script.
97678f339d1SEwan Crawford         if (m_scriptMappings.find(script) != m_scriptMappings.end())
9774640cde1SColin Riley         {
97878f339d1SEwan Crawford             // if the module we have stored is different to the one we just received.
97978f339d1SEwan Crawford             if (m_scriptMappings[script] != rsmodule_sp)
9804640cde1SColin Riley             {
9814640cde1SColin Riley                 if (log)
9824640cde1SColin Riley                     log->Printf ("RenderScriptRuntime::FixupScriptDetails - Error: script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
98378f339d1SEwan Crawford                                     (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
9844640cde1SColin Riley             }
9854640cde1SColin Riley         }
98678f339d1SEwan Crawford         // We don't have a script mapping for the current script.
9874640cde1SColin Riley         else
9884640cde1SColin Riley         {
98978f339d1SEwan Crawford             // Obtain the script resource name.
99078f339d1SEwan Crawford             std::string resName;
99178f339d1SEwan Crawford             if (rs_script->resName.get(resName))
99278f339d1SEwan Crawford                 // Set the modules resource name.
99378f339d1SEwan Crawford                 rsmodule_sp->m_resname = resName;
99478f339d1SEwan Crawford             // Add Script/Module pair to map.
99578f339d1SEwan Crawford             m_scriptMappings[script] = rsmodule_sp;
9964640cde1SColin Riley             if (log)
9974640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::FixupScriptDetails - script %" PRIx64 " associated with rsmodule '%s'.",
99878f339d1SEwan Crawford                                 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
9994640cde1SColin Riley         }
10004640cde1SColin Riley     }
10014640cde1SColin Riley }
10024640cde1SColin Riley 
100315f2bd95SEwan Crawford // Uses the Target API to evaluate the expression passed as a parameter to the function
100415f2bd95SEwan Crawford // The result of that expression is returned an unsigned 64 bit int, via the result* paramter.
100515f2bd95SEwan Crawford // Function returns true on success, and false on failure
100615f2bd95SEwan Crawford bool
100715f2bd95SEwan Crawford RenderScriptRuntime::EvalRSExpression(const char* expression, StackFrame* frame_ptr, uint64_t* result)
100815f2bd95SEwan Crawford {
100915f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
101015f2bd95SEwan Crawford     if (log)
101115f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::EvalRSExpression(%s)", expression);
101215f2bd95SEwan Crawford 
101315f2bd95SEwan Crawford     ValueObjectSP expr_result;
101415f2bd95SEwan Crawford     // Perform the actual expression evaluation
101515f2bd95SEwan Crawford     GetProcess()->GetTarget().EvaluateExpression(expression, frame_ptr, expr_result);
101615f2bd95SEwan Crawford 
101715f2bd95SEwan Crawford     if (!expr_result)
101815f2bd95SEwan Crawford     {
101915f2bd95SEwan Crawford        if (log)
102015f2bd95SEwan Crawford            log->Printf("RenderScriptRuntime::EvalRSExpression -  Error: Couldn't evaluate expression");
102115f2bd95SEwan Crawford        return false;
102215f2bd95SEwan Crawford     }
102315f2bd95SEwan Crawford 
102415f2bd95SEwan Crawford     // The result of the expression is invalid
102515f2bd95SEwan Crawford     if (!expr_result->GetError().Success())
102615f2bd95SEwan Crawford     {
102715f2bd95SEwan Crawford         Error err = expr_result->GetError();
102815f2bd95SEwan Crawford         if (err.GetError() == UserExpression::kNoResult) // Expression returned void, so this is actually a success
102915f2bd95SEwan Crawford         {
103015f2bd95SEwan Crawford             if (log)
103115f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::EvalRSExpression - Expression returned void");
103215f2bd95SEwan Crawford 
103315f2bd95SEwan Crawford             result = nullptr;
103415f2bd95SEwan Crawford             return true;
103515f2bd95SEwan Crawford         }
103615f2bd95SEwan Crawford 
103715f2bd95SEwan Crawford         if (log)
103815f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::EvalRSExpression - Error evaluating expression result: %s", err.AsCString());
103915f2bd95SEwan Crawford         return false;
104015f2bd95SEwan Crawford     }
104115f2bd95SEwan Crawford 
104215f2bd95SEwan Crawford     bool success = false;
104315f2bd95SEwan Crawford     *result = expr_result->GetValueAsUnsigned(0, &success); // We only read the result as an unsigned int.
104415f2bd95SEwan Crawford 
104515f2bd95SEwan Crawford     if (!success)
104615f2bd95SEwan Crawford     {
104715f2bd95SEwan Crawford        if (log)
104815f2bd95SEwan Crawford            log->Printf("RenderScriptRuntime::EvalRSExpression -  Error: Couldn't convert expression result to unsigned int");
104915f2bd95SEwan Crawford        return false;
105015f2bd95SEwan Crawford     }
105115f2bd95SEwan Crawford 
105215f2bd95SEwan Crawford     return true;
105315f2bd95SEwan Crawford }
105415f2bd95SEwan Crawford 
105515f2bd95SEwan Crawford // Used to index expression format strings
105615f2bd95SEwan Crawford enum ExpressionStrings
105715f2bd95SEwan Crawford {
105815f2bd95SEwan Crawford    eExprGetOffsetPtr = 0,
105915f2bd95SEwan Crawford    eExprAllocGetType,
106015f2bd95SEwan Crawford    eExprTypeDimX,
106115f2bd95SEwan Crawford    eExprTypeDimY,
106215f2bd95SEwan Crawford    eExprTypeDimZ,
106315f2bd95SEwan Crawford    eExprTypeElemPtr,
106415f2bd95SEwan Crawford    eExprElementType,
106515f2bd95SEwan Crawford    eExprElementKind,
106615f2bd95SEwan Crawford    eExprElementVec
106715f2bd95SEwan Crawford };
106815f2bd95SEwan Crawford 
106915f2bd95SEwan Crawford // Format strings containing the expressions we may need to evaluate.
107015f2bd95SEwan Crawford const char runtimeExpressions[][256] =
107115f2bd95SEwan Crawford {
107215f2bd95SEwan Crawford  // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
107315f2bd95SEwan Crawford  "(int*)_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace(0x%lx, %u, %u, %u, 0, 0)",
107415f2bd95SEwan Crawford 
107515f2bd95SEwan Crawford  // Type* rsaAllocationGetType(Context*, Allocation*)
107615f2bd95SEwan Crawford  "(void*)rsaAllocationGetType(0x%lx, 0x%lx)",
107715f2bd95SEwan Crawford 
107815f2bd95SEwan Crawford  // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
107915f2bd95SEwan Crawford  // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ;
108015f2bd95SEwan Crawford  // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
108115f2bd95SEwan Crawford  // Need to specify 32 or 64 bit for uint_t since this differs between devices
108215f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[0]", // X dim
108315f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[1]", // Y dim
108415f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[2]", // Z dim
108515f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[5]", // Element ptr
108615f2bd95SEwan Crawford 
108715f2bd95SEwan Crawford  // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
108815f2bd95SEwan Crawford  // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData
108915f2bd95SEwan Crawford  "uint32_t data[6]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[0]", // Type
109015f2bd95SEwan Crawford  "uint32_t data[6]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[1]", // Kind
109115f2bd95SEwan Crawford  "uint32_t data[6]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[3]"  // Vector Size
109215f2bd95SEwan Crawford };
109315f2bd95SEwan Crawford 
109415f2bd95SEwan Crawford // JITs the RS runtime for the internal data pointer of an allocation.
109515f2bd95SEwan Crawford // Is passed x,y,z coordinates for the pointer to a specific element.
109615f2bd95SEwan Crawford // Then sets the data_ptr member in Allocation with the result.
109715f2bd95SEwan Crawford // Returns true on success, false otherwise
109815f2bd95SEwan Crawford bool
109915f2bd95SEwan Crawford RenderScriptRuntime::JITDataPointer(AllocationDetails* allocation, StackFrame* frame_ptr,
110015f2bd95SEwan Crawford                                     unsigned int x, unsigned int y, unsigned int z)
110115f2bd95SEwan Crawford {
110215f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
110315f2bd95SEwan Crawford 
110415f2bd95SEwan Crawford     if (!allocation->address.isValid())
110515f2bd95SEwan Crawford     {
110615f2bd95SEwan Crawford         if (log)
110715f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Failed to find allocation details");
110815f2bd95SEwan Crawford         return false;
110915f2bd95SEwan Crawford     }
111015f2bd95SEwan Crawford 
111115f2bd95SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprGetOffsetPtr];
111215f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
111315f2bd95SEwan Crawford     char buffer[max_expr_size];
111415f2bd95SEwan Crawford 
111515f2bd95SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->address.get(), x, y, z);
111615f2bd95SEwan Crawford     if (chars_written < 0)
111715f2bd95SEwan Crawford     {
111815f2bd95SEwan Crawford         if (log)
111915f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
112015f2bd95SEwan Crawford         return false;
112115f2bd95SEwan Crawford     }
112215f2bd95SEwan Crawford     else if (chars_written >= max_expr_size)
112315f2bd95SEwan Crawford     {
112415f2bd95SEwan Crawford         if (log)
112515f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Expression too long");
112615f2bd95SEwan Crawford         return false;
112715f2bd95SEwan Crawford     }
112815f2bd95SEwan Crawford 
112915f2bd95SEwan Crawford     uint64_t result = 0;
113015f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
113115f2bd95SEwan Crawford         return false;
113215f2bd95SEwan Crawford 
113315f2bd95SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
113415f2bd95SEwan Crawford     allocation->data_ptr = mem_ptr;
113515f2bd95SEwan Crawford 
113615f2bd95SEwan Crawford     return true;
113715f2bd95SEwan Crawford }
113815f2bd95SEwan Crawford 
113915f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
114015f2bd95SEwan Crawford // Then sets the type_ptr member in Allocation with the result.
114115f2bd95SEwan Crawford // Returns true on success, false otherwise
114215f2bd95SEwan Crawford bool
114315f2bd95SEwan Crawford RenderScriptRuntime::JITTypePointer(AllocationDetails* allocation, StackFrame* frame_ptr)
114415f2bd95SEwan Crawford {
114515f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
114615f2bd95SEwan Crawford 
114715f2bd95SEwan Crawford     if (!allocation->address.isValid() || !allocation->context.isValid())
114815f2bd95SEwan Crawford     {
114915f2bd95SEwan Crawford         if (log)
115015f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePointer - Failed to find allocation details");
115115f2bd95SEwan Crawford         return false;
115215f2bd95SEwan Crawford     }
115315f2bd95SEwan Crawford 
115415f2bd95SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprAllocGetType];
115515f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
115615f2bd95SEwan Crawford     char buffer[max_expr_size];
115715f2bd95SEwan Crawford 
115815f2bd95SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->context.get(), *allocation->address.get());
115915f2bd95SEwan Crawford     if (chars_written < 0)
116015f2bd95SEwan Crawford     {
116115f2bd95SEwan Crawford         if (log)
116215f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
116315f2bd95SEwan Crawford         return false;
116415f2bd95SEwan Crawford     }
116515f2bd95SEwan Crawford     else if (chars_written >= max_expr_size)
116615f2bd95SEwan Crawford     {
116715f2bd95SEwan Crawford         if (log)
116815f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePointer - Expression too long");
116915f2bd95SEwan Crawford         return false;
117015f2bd95SEwan Crawford     }
117115f2bd95SEwan Crawford 
117215f2bd95SEwan Crawford     uint64_t result = 0;
117315f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
117415f2bd95SEwan Crawford         return false;
117515f2bd95SEwan Crawford 
117615f2bd95SEwan Crawford     addr_t type_ptr = static_cast<lldb::addr_t>(result);
117715f2bd95SEwan Crawford     allocation->type_ptr = type_ptr;
117815f2bd95SEwan Crawford 
117915f2bd95SEwan Crawford     return true;
118015f2bd95SEwan Crawford }
118115f2bd95SEwan Crawford 
118215f2bd95SEwan Crawford // JITs the RS runtime for information about the dimensions and type of an allocation
118315f2bd95SEwan Crawford // Then sets dimension and element_ptr members in Allocation with the result.
118415f2bd95SEwan Crawford // Returns true on success, false otherwise
118515f2bd95SEwan Crawford bool
118615f2bd95SEwan Crawford RenderScriptRuntime::JITTypePacked(AllocationDetails* allocation, StackFrame* frame_ptr)
118715f2bd95SEwan Crawford {
118815f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
118915f2bd95SEwan Crawford 
119015f2bd95SEwan Crawford     if (!allocation->type_ptr.isValid() || !allocation->context.isValid())
119115f2bd95SEwan Crawford     {
119215f2bd95SEwan Crawford         if (log)
119315f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePacked - Failed to find allocation details");
119415f2bd95SEwan Crawford         return false;
119515f2bd95SEwan Crawford     }
119615f2bd95SEwan Crawford 
119715f2bd95SEwan Crawford     // Expression is different depending on if device is 32 or 64 bit
119815f2bd95SEwan Crawford     uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
119915f2bd95SEwan Crawford     const unsigned int bits = archByteSize == 4 ? 32 : 64;
120015f2bd95SEwan Crawford 
120115f2bd95SEwan Crawford     // We want 4 elements from packed data
120215f2bd95SEwan Crawford     const unsigned int num_exprs = 4;
120315f2bd95SEwan Crawford     assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) && "Invalid number of expressions");
120415f2bd95SEwan Crawford 
120515f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
120615f2bd95SEwan Crawford     char buffer[num_exprs][max_expr_size];
120715f2bd95SEwan Crawford     uint64_t results[num_exprs];
120815f2bd95SEwan Crawford 
120915f2bd95SEwan Crawford     for (unsigned int i = 0; i < num_exprs; ++i)
121015f2bd95SEwan Crawford     {
121115f2bd95SEwan Crawford         int chars_written = snprintf(buffer[i], max_expr_size, runtimeExpressions[eExprTypeDimX + i], bits,
121215f2bd95SEwan Crawford                                      *allocation->context.get(), *allocation->type_ptr.get());
121315f2bd95SEwan Crawford         if (chars_written < 0)
121415f2bd95SEwan Crawford         {
121515f2bd95SEwan Crawford             if (log)
121615f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
121715f2bd95SEwan Crawford             return false;
121815f2bd95SEwan Crawford         }
121915f2bd95SEwan Crawford         else if (chars_written >= max_expr_size)
122015f2bd95SEwan Crawford         {
122115f2bd95SEwan Crawford             if (log)
122215f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITTypePacked - Expression too long");
122315f2bd95SEwan Crawford             return false;
122415f2bd95SEwan Crawford         }
122515f2bd95SEwan Crawford 
122615f2bd95SEwan Crawford         // Perform expression evaluation
122715f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
122815f2bd95SEwan Crawford             return false;
122915f2bd95SEwan Crawford     }
123015f2bd95SEwan Crawford 
123115f2bd95SEwan Crawford     // Assign results to allocation members
123215f2bd95SEwan Crawford     AllocationDetails::Dimension dims;
123315f2bd95SEwan Crawford     dims.dim_1 = static_cast<uint32_t>(results[0]);
123415f2bd95SEwan Crawford     dims.dim_2 = static_cast<uint32_t>(results[1]);
123515f2bd95SEwan Crawford     dims.dim_3 = static_cast<uint32_t>(results[2]);
123615f2bd95SEwan Crawford     allocation->dimension = dims;
123715f2bd95SEwan Crawford 
123815f2bd95SEwan Crawford     addr_t elem_ptr = static_cast<lldb::addr_t>(results[3]);
123915f2bd95SEwan Crawford     allocation->element_ptr = elem_ptr;
124015f2bd95SEwan Crawford 
124115f2bd95SEwan Crawford     if (log)
124215f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::JITTypePacked - dims (%u, %u, %u) Element*: 0x%" PRIx64,
124315f2bd95SEwan Crawford                     dims.dim_1, dims.dim_2, dims.dim_3, elem_ptr);
124415f2bd95SEwan Crawford 
124515f2bd95SEwan Crawford     return true;
124615f2bd95SEwan Crawford }
124715f2bd95SEwan Crawford 
124815f2bd95SEwan Crawford // JITs the RS runtime for information about the Element of an allocation
124915f2bd95SEwan Crawford // Then sets type, type_vec_size, and type_kind members in Allocation with the result.
125015f2bd95SEwan Crawford // Returns true on success, false otherwise
125115f2bd95SEwan Crawford bool
125215f2bd95SEwan Crawford RenderScriptRuntime::JITElementPacked(AllocationDetails* allocation, StackFrame* frame_ptr)
125315f2bd95SEwan Crawford {
125415f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
125515f2bd95SEwan Crawford 
125615f2bd95SEwan Crawford     if (!allocation->element_ptr.isValid() || !allocation->context.isValid())
125715f2bd95SEwan Crawford     {
125815f2bd95SEwan Crawford         if (log)
125915f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITElementPacked - Failed to find allocation details");
126015f2bd95SEwan Crawford         return false;
126115f2bd95SEwan Crawford     }
126215f2bd95SEwan Crawford 
126315f2bd95SEwan Crawford     // We want 3 elements from packed data
126415f2bd95SEwan Crawford     const unsigned int num_exprs = 3;
126515f2bd95SEwan Crawford     assert(num_exprs == (eExprElementVec - eExprElementType + 1) && "Invalid number of expressions");
126615f2bd95SEwan Crawford 
126715f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
126815f2bd95SEwan Crawford     char buffer[num_exprs][max_expr_size];
126915f2bd95SEwan Crawford     uint64_t results[num_exprs];
127015f2bd95SEwan Crawford 
127115f2bd95SEwan Crawford     for (unsigned int i = 0; i < num_exprs; i++)
127215f2bd95SEwan Crawford     {
127315f2bd95SEwan Crawford         int chars_written = snprintf(buffer[i], max_expr_size, runtimeExpressions[eExprElementType + i], *allocation->context.get(), *allocation->element_ptr.get());
127415f2bd95SEwan Crawford         if (chars_written < 0)
127515f2bd95SEwan Crawford         {
127615f2bd95SEwan Crawford             if (log)
127715f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
127815f2bd95SEwan Crawford             return false;
127915f2bd95SEwan Crawford         }
128015f2bd95SEwan Crawford         else if (chars_written >= max_expr_size)
128115f2bd95SEwan Crawford         {
128215f2bd95SEwan Crawford             if (log)
128315f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITElementPacked - Expression too long");
128415f2bd95SEwan Crawford             return false;
128515f2bd95SEwan Crawford         }
128615f2bd95SEwan Crawford 
128715f2bd95SEwan Crawford         // Perform expression evaluation
128815f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
128915f2bd95SEwan Crawford             return false;
129015f2bd95SEwan Crawford     }
129115f2bd95SEwan Crawford 
129215f2bd95SEwan Crawford     // Assign results to allocation members
129315f2bd95SEwan Crawford     allocation->type = static_cast<RenderScriptRuntime::AllocationDetails::DataType>(results[0]);
129415f2bd95SEwan Crawford     allocation->type_kind = static_cast<RenderScriptRuntime::AllocationDetails::DataKind>(results[1]);
129515f2bd95SEwan Crawford     allocation->type_vec_size = static_cast<uint32_t>(results[2]);
129615f2bd95SEwan Crawford 
129715f2bd95SEwan Crawford     if (log)
129815f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::JITElementPacked - data type %u, pixel type %u, vector size %u",
129915f2bd95SEwan Crawford                     *allocation->type.get(), *allocation->type_kind.get(), *allocation->type_vec_size.get());
130015f2bd95SEwan Crawford 
130115f2bd95SEwan Crawford     return true;
130215f2bd95SEwan Crawford }
130315f2bd95SEwan Crawford 
1304a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
1305a0f08674SEwan Crawford // The `elem_size` paramter represents the size of a single element, including padding.
1306a0f08674SEwan Crawford // Which is needed as an offset from the last element pointer.
1307a0f08674SEwan Crawford // Using this offset minus the starting address we can calculate the size of the allocation.
1308a0f08674SEwan Crawford // Returns true on success, false otherwise
1309a0f08674SEwan Crawford bool
1310a0f08674SEwan Crawford RenderScriptRuntime::JITAllocationSize(AllocationDetails* allocation, StackFrame* frame_ptr,
1311a0f08674SEwan Crawford                                        const uint32_t elem_size)
1312a0f08674SEwan Crawford {
1313a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1314a0f08674SEwan Crawford 
1315a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->dimension.isValid()
1316a0f08674SEwan Crawford         || !allocation->data_ptr.isValid())
1317a0f08674SEwan Crawford     {
1318a0f08674SEwan Crawford         if (log)
1319a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Failed to find allocation details");
1320a0f08674SEwan Crawford         return false;
1321a0f08674SEwan Crawford     }
1322a0f08674SEwan Crawford 
1323a0f08674SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprGetOffsetPtr];
1324a0f08674SEwan Crawford     const int max_expr_size = 512; // Max expression size
1325a0f08674SEwan Crawford     char buffer[max_expr_size];
1326a0f08674SEwan Crawford 
1327a0f08674SEwan Crawford     // Find dimensions
1328a0f08674SEwan Crawford     unsigned int dim_x = allocation->dimension.get()->dim_1;
1329a0f08674SEwan Crawford     unsigned int dim_y = allocation->dimension.get()->dim_2;
1330a0f08674SEwan Crawford     unsigned int dim_z = allocation->dimension.get()->dim_3;
1331a0f08674SEwan Crawford 
1332a0f08674SEwan Crawford     // Calculate last element
1333a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 0 : dim_x - 1;
1334a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 0 : dim_y - 1;
1335a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 0 : dim_z - 1;
1336a0f08674SEwan Crawford 
1337a0f08674SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->address.get(),
1338a0f08674SEwan Crawford                                  dim_x, dim_y, dim_z);
1339a0f08674SEwan Crawford     if (chars_written < 0)
1340a0f08674SEwan Crawford     {
1341a0f08674SEwan Crawford         if (log)
1342a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Encoding error in snprintf()");
1343a0f08674SEwan Crawford         return false;
1344a0f08674SEwan Crawford     }
1345a0f08674SEwan Crawford     else if (chars_written >= max_expr_size)
1346a0f08674SEwan Crawford     {
1347a0f08674SEwan Crawford         if (log)
1348a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Expression too long");
1349a0f08674SEwan Crawford         return false;
1350a0f08674SEwan Crawford     }
1351a0f08674SEwan Crawford 
1352a0f08674SEwan Crawford     uint64_t result = 0;
1353a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1354a0f08674SEwan Crawford         return false;
1355a0f08674SEwan Crawford 
1356a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1357a0f08674SEwan Crawford     // Find pointer to last element and add on size of an element
1358a0f08674SEwan Crawford     allocation->size = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()) + elem_size;
1359a0f08674SEwan Crawford 
1360a0f08674SEwan Crawford     return true;
1361a0f08674SEwan Crawford }
1362a0f08674SEwan Crawford 
1363a0f08674SEwan Crawford // JITs the RS runtime for information about the stride between rows in the allocation.
1364a0f08674SEwan Crawford // This is done to detect padding, since allocated memory is 16-byte aligned.
1365a0f08674SEwan Crawford // Returns true on success, false otherwise
1366a0f08674SEwan Crawford bool
1367a0f08674SEwan Crawford RenderScriptRuntime::JITAllocationStride(AllocationDetails* allocation, StackFrame* frame_ptr)
1368a0f08674SEwan Crawford {
1369a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1370a0f08674SEwan Crawford 
1371a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->data_ptr.isValid())
1372a0f08674SEwan Crawford     {
1373a0f08674SEwan Crawford         if (log)
1374a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Failed to find allocation details");
1375a0f08674SEwan Crawford         return false;
1376a0f08674SEwan Crawford     }
1377a0f08674SEwan Crawford 
1378a0f08674SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprGetOffsetPtr];
1379a0f08674SEwan Crawford     const int max_expr_size = 512; // Max expression size
1380a0f08674SEwan Crawford     char buffer[max_expr_size];
1381a0f08674SEwan Crawford 
1382a0f08674SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->address.get(),
1383a0f08674SEwan Crawford                                  0, 1, 0);
1384a0f08674SEwan Crawford     if (chars_written < 0)
1385a0f08674SEwan Crawford     {
1386a0f08674SEwan Crawford         if (log)
1387a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Encoding error in snprintf()");
1388a0f08674SEwan Crawford         return false;
1389a0f08674SEwan Crawford     }
1390a0f08674SEwan Crawford     else if (chars_written >= max_expr_size)
1391a0f08674SEwan Crawford     {
1392a0f08674SEwan Crawford         if (log)
1393a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Expression too long");
1394a0f08674SEwan Crawford         return false;
1395a0f08674SEwan Crawford     }
1396a0f08674SEwan Crawford 
1397a0f08674SEwan Crawford     uint64_t result = 0;
1398a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1399a0f08674SEwan Crawford         return false;
1400a0f08674SEwan Crawford 
1401a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1402a0f08674SEwan Crawford     allocation->stride = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get());
1403a0f08674SEwan Crawford 
1404a0f08674SEwan Crawford     return true;
1405a0f08674SEwan Crawford }
1406a0f08674SEwan Crawford 
140715f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
140815f2bd95SEwan Crawford bool
140915f2bd95SEwan Crawford RenderScriptRuntime::RefreshAllocation(AllocationDetails* allocation, StackFrame* frame_ptr)
141015f2bd95SEwan Crawford {
141115f2bd95SEwan Crawford     // GetOffsetPointer()
141215f2bd95SEwan Crawford     if (!JITDataPointer(allocation, frame_ptr))
141315f2bd95SEwan Crawford         return false;
141415f2bd95SEwan Crawford 
141515f2bd95SEwan Crawford     // rsaAllocationGetType()
141615f2bd95SEwan Crawford     if (!JITTypePointer(allocation, frame_ptr))
141715f2bd95SEwan Crawford         return false;
141815f2bd95SEwan Crawford 
141915f2bd95SEwan Crawford     // rsaTypeGetNativeData()
142015f2bd95SEwan Crawford     if (!JITTypePacked(allocation, frame_ptr))
142115f2bd95SEwan Crawford         return false;
142215f2bd95SEwan Crawford 
142315f2bd95SEwan Crawford     // rsaElementGetNativeData()
142415f2bd95SEwan Crawford     if (!JITElementPacked(allocation, frame_ptr))
142515f2bd95SEwan Crawford         return false;
142615f2bd95SEwan Crawford 
142755232f09SEwan Crawford     // Use GetOffsetPointer() to infer size of the allocation
142855232f09SEwan Crawford     const unsigned int element_size = GetElementSize(allocation);
142955232f09SEwan Crawford     if (!JITAllocationSize(allocation, frame_ptr, element_size))
143055232f09SEwan Crawford         return false;
143155232f09SEwan Crawford 
143255232f09SEwan Crawford     return true;
143355232f09SEwan Crawford }
143455232f09SEwan Crawford 
143555232f09SEwan Crawford // Returns the size of a single allocation element including padding.
143655232f09SEwan Crawford // Assumes the relevant allocation information has already been jitted.
143755232f09SEwan Crawford unsigned int
143855232f09SEwan Crawford RenderScriptRuntime::GetElementSize(const AllocationDetails* allocation)
143955232f09SEwan Crawford {
144055232f09SEwan Crawford     const AllocationDetails::DataType type = *allocation->type.get();
144155232f09SEwan Crawford     assert(type >= AllocationDetails::RS_TYPE_NONE && type <= AllocationDetails::RS_TYPE_BOOLEAN
144255232f09SEwan Crawford                                                    && "Invalid allocation type");
144355232f09SEwan Crawford 
144455232f09SEwan Crawford     const unsigned int vec_size = *allocation->type_vec_size.get();
144555232f09SEwan Crawford     const unsigned int data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
144655232f09SEwan Crawford     const unsigned int padding = vec_size == 3 ? AllocationDetails::RSTypeToFormat[type][eElementSize] : 0;
144755232f09SEwan Crawford 
144855232f09SEwan Crawford     return data_size + padding;
144955232f09SEwan Crawford }
145055232f09SEwan Crawford 
145155232f09SEwan Crawford // Given an allocation, this function copies the allocation contents from device into a buffer on the heap.
145255232f09SEwan Crawford // Returning a shared pointer to the buffer containing the data.
145355232f09SEwan Crawford std::shared_ptr<uint8_t>
145455232f09SEwan Crawford RenderScriptRuntime::GetAllocationData(AllocationDetails* allocation, StackFrame* frame_ptr)
145555232f09SEwan Crawford {
145655232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
145755232f09SEwan Crawford 
145855232f09SEwan Crawford     // JIT all the allocation details
145955232f09SEwan Crawford     if (!allocation->data_ptr.isValid() || !allocation->type.isValid() || !allocation->type_vec_size.isValid()
146055232f09SEwan Crawford         || !allocation->size.isValid())
146155232f09SEwan Crawford     {
146255232f09SEwan Crawford         if (log)
146355232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - Allocation details not calculated yet, jitting info");
146455232f09SEwan Crawford 
146555232f09SEwan Crawford         if (!RefreshAllocation(allocation, frame_ptr))
146655232f09SEwan Crawford         {
146755232f09SEwan Crawford             if (log)
146855232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't JIT allocation details");
146955232f09SEwan Crawford             return nullptr;
147055232f09SEwan Crawford         }
147155232f09SEwan Crawford     }
147255232f09SEwan Crawford 
147355232f09SEwan Crawford     assert(allocation->data_ptr.isValid() && allocation->type.isValid() && allocation->type_vec_size.isValid()
147455232f09SEwan Crawford            && allocation->size.isValid() && "Allocation information not available");
147555232f09SEwan Crawford 
147655232f09SEwan Crawford     // Allocate a buffer to copy data into
147755232f09SEwan Crawford     const unsigned int size = *allocation->size.get();
147855232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
147955232f09SEwan Crawford     if (!buffer)
148055232f09SEwan Crawford     {
148155232f09SEwan Crawford         if (log)
148255232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't allocate a %u byte buffer", size);
148355232f09SEwan Crawford         return nullptr;
148455232f09SEwan Crawford     }
148555232f09SEwan Crawford 
148655232f09SEwan Crawford     // Read the inferior memory
148755232f09SEwan Crawford     Error error;
148855232f09SEwan Crawford     lldb::addr_t data_ptr = *allocation->data_ptr.get();
148955232f09SEwan Crawford     GetProcess()->ReadMemory(data_ptr, buffer.get(), size, error);
149055232f09SEwan Crawford     if (error.Fail())
149155232f09SEwan Crawford     {
149255232f09SEwan Crawford         if (log)
149355232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - '%s' Couldn't read %u bytes of allocation data from 0x%" PRIx64,
149455232f09SEwan Crawford                         error.AsCString(), size, data_ptr);
149555232f09SEwan Crawford         return nullptr;
149655232f09SEwan Crawford     }
149755232f09SEwan Crawford 
149855232f09SEwan Crawford     return buffer;
149955232f09SEwan Crawford }
150055232f09SEwan Crawford 
150155232f09SEwan Crawford // Function copies data from a binary file into an allocation.
150255232f09SEwan Crawford // There is a header at the start of the file, FileHeader, before the data content itself.
150355232f09SEwan Crawford // Information from this header is used to display warnings to the user about incompatabilities
150455232f09SEwan Crawford bool
150555232f09SEwan Crawford RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr)
150655232f09SEwan Crawford {
150755232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
150855232f09SEwan Crawford 
150955232f09SEwan Crawford     // Find allocation with the given id
151055232f09SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, alloc_id);
151155232f09SEwan Crawford     if (!alloc)
151255232f09SEwan Crawford         return false;
151355232f09SEwan Crawford 
151455232f09SEwan Crawford     if (log)
151555232f09SEwan Crawford         log->Printf("RenderScriptRuntime::LoadAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
151655232f09SEwan Crawford 
151755232f09SEwan Crawford     // JIT all the allocation details
151855232f09SEwan Crawford     if (!alloc->data_ptr.isValid() || !alloc->type.isValid() || !alloc->type_vec_size.isValid() || !alloc->size.isValid())
151955232f09SEwan Crawford     {
152055232f09SEwan Crawford         if (log)
152155232f09SEwan Crawford             log->Printf("RenderScriptRuntime::LoadAllocation - Allocation details not calculated yet, jitting info");
152255232f09SEwan Crawford 
152355232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
152455232f09SEwan Crawford         {
152555232f09SEwan Crawford             if (log)
152655232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::LoadAllocation - Couldn't JIT allocation details");
15274cfc9198SSylvestre Ledru             return false;
152855232f09SEwan Crawford         }
152955232f09SEwan Crawford     }
153055232f09SEwan Crawford 
153155232f09SEwan Crawford     assert(alloc->data_ptr.isValid() && alloc->type.isValid() && alloc->type_vec_size.isValid() && alloc->size.isValid()
153255232f09SEwan Crawford            && "Allocation information not available");
153355232f09SEwan Crawford 
153455232f09SEwan Crawford     // Check we can read from file
153555232f09SEwan Crawford     FileSpec file(filename, true);
153655232f09SEwan Crawford     if (!file.Exists())
153755232f09SEwan Crawford     {
153855232f09SEwan Crawford         strm.Printf("Error: File %s does not exist", filename);
153955232f09SEwan Crawford         strm.EOL();
154055232f09SEwan Crawford         return false;
154155232f09SEwan Crawford     }
154255232f09SEwan Crawford 
154355232f09SEwan Crawford     if (!file.Readable())
154455232f09SEwan Crawford     {
154555232f09SEwan Crawford         strm.Printf("Error: File %s does not have readable permissions", filename);
154655232f09SEwan Crawford         strm.EOL();
154755232f09SEwan Crawford         return false;
154855232f09SEwan Crawford     }
154955232f09SEwan Crawford 
155055232f09SEwan Crawford     // Read file into data buffer
155155232f09SEwan Crawford     DataBufferSP data_sp(file.ReadFileContents());
155255232f09SEwan Crawford 
155355232f09SEwan Crawford     // Cast start of buffer to FileHeader and use pointer to read metadata
155455232f09SEwan Crawford     void* file_buffer = data_sp->GetBytes();
155555232f09SEwan Crawford     const AllocationDetails::FileHeader* head = static_cast<AllocationDetails::FileHeader*>(file_buffer);
155655232f09SEwan Crawford 
155755232f09SEwan Crawford     // Advance buffer past header
155855232f09SEwan Crawford     file_buffer = static_cast<uint8_t*>(file_buffer) + head->hdr_size;
155955232f09SEwan Crawford 
156055232f09SEwan Crawford     if (log)
156155232f09SEwan Crawford         log->Printf("RenderScriptRuntime::LoadAllocation - header type %u, element size %u",
156255232f09SEwan Crawford                     head->type, head->element_size);
156355232f09SEwan Crawford 
156455232f09SEwan Crawford     // Check if the target allocation and file both have the same number of bytes for an Element
156555232f09SEwan Crawford     const unsigned int elem_size = GetElementSize(alloc);
156655232f09SEwan Crawford     if (elem_size != head->element_size)
156755232f09SEwan Crawford     {
156855232f09SEwan Crawford         strm.Printf("Warning: Mismatched Element sizes - file %u bytes, allocation %u bytes",
156955232f09SEwan Crawford                     head->element_size, elem_size);
157055232f09SEwan Crawford         strm.EOL();
157155232f09SEwan Crawford     }
157255232f09SEwan Crawford 
157355232f09SEwan Crawford     // Check if the target allocation and file both have the same integral type
157455232f09SEwan Crawford     const unsigned int type = static_cast<unsigned int>(*alloc->type.get());
157555232f09SEwan Crawford     if (type != head->type)
157655232f09SEwan Crawford     {
157755232f09SEwan Crawford         const char* file_type_cstr = AllocationDetails::RsDataTypeToString[head->type][0];
157855232f09SEwan Crawford         const char* alloc_type_cstr = AllocationDetails::RsDataTypeToString[type][0];
157955232f09SEwan Crawford 
158055232f09SEwan Crawford         strm.Printf("Warning: Mismatched Types - file '%s' type, allocation '%s' type",
158155232f09SEwan Crawford                     file_type_cstr, alloc_type_cstr);
158255232f09SEwan Crawford         strm.EOL();
158355232f09SEwan Crawford     }
158455232f09SEwan Crawford 
158555232f09SEwan Crawford     // Calculate size of allocation data in file
158655232f09SEwan Crawford     size_t length = data_sp->GetByteSize() - head->hdr_size;
158755232f09SEwan Crawford 
158855232f09SEwan Crawford     // Check if the target allocation and file both have the same total data size.
158955232f09SEwan Crawford     const unsigned int alloc_size = *alloc->size.get();
159055232f09SEwan Crawford     if (alloc_size != length)
159155232f09SEwan Crawford     {
159255232f09SEwan Crawford         strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64 " bytes, allocation 0x%x bytes",
159355232f09SEwan Crawford                     length, alloc_size);
159455232f09SEwan Crawford         strm.EOL();
159555232f09SEwan Crawford         length = alloc_size < length ? alloc_size : length; // Set length to copy to minimum
159655232f09SEwan Crawford     }
159755232f09SEwan Crawford 
159855232f09SEwan Crawford     // Copy file data from our buffer into the target allocation.
159955232f09SEwan Crawford     lldb::addr_t alloc_data = *alloc->data_ptr.get();
160055232f09SEwan Crawford     Error error;
160155232f09SEwan Crawford     size_t bytes_written = GetProcess()->WriteMemory(alloc_data, file_buffer, length, error);
160255232f09SEwan Crawford     if (!error.Success() || bytes_written != length)
160355232f09SEwan Crawford     {
160455232f09SEwan Crawford         strm.Printf("Error: Couldn't write data to allocation %s", error.AsCString());
160555232f09SEwan Crawford         strm.EOL();
160655232f09SEwan Crawford         return false;
160755232f09SEwan Crawford     }
160855232f09SEwan Crawford 
160955232f09SEwan Crawford     strm.Printf("Contents of file '%s' read into allocation %u", filename, alloc->id);
161055232f09SEwan Crawford     strm.EOL();
161155232f09SEwan Crawford 
161255232f09SEwan Crawford     return true;
161355232f09SEwan Crawford }
161455232f09SEwan Crawford 
161555232f09SEwan Crawford // Function copies allocation contents into a binary file.
161655232f09SEwan Crawford // This file can then be loaded later into a different allocation.
161755232f09SEwan Crawford // There is a header, FileHeader, before the allocation data containing meta-data.
161855232f09SEwan Crawford bool
161955232f09SEwan Crawford RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr)
162055232f09SEwan Crawford {
162155232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
162255232f09SEwan Crawford 
162355232f09SEwan Crawford     // Find allocation with the given id
162455232f09SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, alloc_id);
162555232f09SEwan Crawford     if (!alloc)
162655232f09SEwan Crawford         return false;
162755232f09SEwan Crawford 
162855232f09SEwan Crawford     if (log)
162955232f09SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
163055232f09SEwan Crawford 
163155232f09SEwan Crawford      // JIT all the allocation details
163255232f09SEwan Crawford     if (!alloc->data_ptr.isValid() || !alloc->type.isValid() || !alloc->type_vec_size.isValid()
163355232f09SEwan Crawford         || !alloc->type_kind.isValid() || !alloc->dimension.isValid())
163455232f09SEwan Crawford     {
163555232f09SEwan Crawford         if (log)
163655232f09SEwan Crawford             log->Printf("RenderScriptRuntime::SaveAllocation - Allocation details not calculated yet, jitting info");
163755232f09SEwan Crawford 
163855232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
163955232f09SEwan Crawford         {
164055232f09SEwan Crawford             if (log)
164155232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::SaveAllocation - Couldn't JIT allocation details");
16424cfc9198SSylvestre Ledru             return false;
164355232f09SEwan Crawford         }
164455232f09SEwan Crawford     }
164555232f09SEwan Crawford 
164655232f09SEwan Crawford     assert(alloc->data_ptr.isValid() && alloc->type.isValid() && alloc->type_vec_size.isValid() && alloc->type_kind.isValid()
164755232f09SEwan Crawford            && alloc->dimension.isValid() && "Allocation information not available");
164855232f09SEwan Crawford 
164955232f09SEwan Crawford     // Check we can create writable file
165055232f09SEwan Crawford     FileSpec file_spec(filename, true);
165155232f09SEwan Crawford     File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionTruncate);
165255232f09SEwan Crawford     if (!file)
165355232f09SEwan Crawford     {
165455232f09SEwan Crawford         strm.Printf("Error: Failed to open '%s' for writing", filename);
165555232f09SEwan Crawford         strm.EOL();
165655232f09SEwan Crawford         return false;
165755232f09SEwan Crawford     }
165855232f09SEwan Crawford 
165955232f09SEwan Crawford     // Read allocation into buffer of heap memory
166055232f09SEwan Crawford     const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
166155232f09SEwan Crawford     if (!buffer)
166255232f09SEwan Crawford     {
166355232f09SEwan Crawford         strm.Printf("Error: Couldn't read allocation data into buffer");
166455232f09SEwan Crawford         strm.EOL();
166555232f09SEwan Crawford         return false;
166655232f09SEwan Crawford     }
166755232f09SEwan Crawford 
166855232f09SEwan Crawford     // Create the file header
166955232f09SEwan Crawford     AllocationDetails::FileHeader head;
167055232f09SEwan Crawford     head.ident[0] = 'R'; head.ident[1] = 'S'; head.ident[2] = 'A'; head.ident[3] = 'D';
167155232f09SEwan Crawford     head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader));
167255232f09SEwan Crawford     head.type = static_cast<uint16_t>(*alloc->type.get());
167355232f09SEwan Crawford     head.kind = static_cast<uint32_t>(*alloc->type_kind.get());
16742d62328aSEwan Crawford     head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
16752d62328aSEwan Crawford     head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
16762d62328aSEwan Crawford     head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
167755232f09SEwan Crawford     head.element_size = static_cast<uint32_t>(GetElementSize(alloc));
167855232f09SEwan Crawford 
167955232f09SEwan Crawford     // Write the file header
168055232f09SEwan Crawford     size_t num_bytes = sizeof(AllocationDetails::FileHeader);
168155232f09SEwan Crawford     Error err = file.Write(static_cast<const void*>(&head), num_bytes);
168255232f09SEwan Crawford     if (!err.Success())
168355232f09SEwan Crawford     {
168455232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
168555232f09SEwan Crawford         strm.EOL();
168655232f09SEwan Crawford         return false;
168755232f09SEwan Crawford     }
168855232f09SEwan Crawford 
168955232f09SEwan Crawford     // Write allocation data to file
169055232f09SEwan Crawford     num_bytes = static_cast<size_t>(*alloc->size.get());
169155232f09SEwan Crawford     if (log)
169255232f09SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Writing %" PRIx64  "bytes from %p", num_bytes, buffer.get());
169355232f09SEwan Crawford 
169455232f09SEwan Crawford     err = file.Write(buffer.get(), num_bytes);
169555232f09SEwan Crawford     if (!err.Success())
169655232f09SEwan Crawford     {
169755232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
169855232f09SEwan Crawford         strm.EOL();
169955232f09SEwan Crawford         return false;
170055232f09SEwan Crawford     }
170155232f09SEwan Crawford 
170255232f09SEwan Crawford     strm.Printf("Allocation written to file '%s'", filename);
170355232f09SEwan Crawford     strm.EOL();
170415f2bd95SEwan Crawford     return true;
170515f2bd95SEwan Crawford }
170615f2bd95SEwan Crawford 
17075ec532a9SColin Riley bool
17085ec532a9SColin Riley RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp)
17095ec532a9SColin Riley {
17104640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
17114640cde1SColin Riley 
17125ec532a9SColin Riley     if (module_sp)
17135ec532a9SColin Riley     {
17145ec532a9SColin Riley         for (const auto &rs_module : m_rsmodules)
17155ec532a9SColin Riley         {
17164640cde1SColin Riley             if (rs_module->m_module == module_sp)
17177dc7771cSEwan Crawford             {
17187dc7771cSEwan Crawford                 // Check if the user has enabled automatically breaking on
17197dc7771cSEwan Crawford                 // all RS kernels.
17207dc7771cSEwan Crawford                 if (m_breakAllKernels)
17217dc7771cSEwan Crawford                     BreakOnModuleKernels(rs_module);
17227dc7771cSEwan Crawford 
17235ec532a9SColin Riley                 return false;
17245ec532a9SColin Riley             }
17257dc7771cSEwan Crawford         }
1726ef20b08fSColin Riley         bool module_loaded = false;
1727ef20b08fSColin Riley         switch (GetModuleKind(module_sp))
1728ef20b08fSColin Riley         {
1729ef20b08fSColin Riley             case eModuleKindKernelObj:
1730ef20b08fSColin Riley             {
17314640cde1SColin Riley                 RSModuleDescriptorSP module_desc;
17324640cde1SColin Riley                 module_desc.reset(new RSModuleDescriptor(module_sp));
17334640cde1SColin Riley                 if (module_desc->ParseRSInfo())
17345ec532a9SColin Riley                 {
17355ec532a9SColin Riley                     m_rsmodules.push_back(module_desc);
1736ef20b08fSColin Riley                     module_loaded = true;
17375ec532a9SColin Riley                 }
17384640cde1SColin Riley                 if (module_loaded)
17394640cde1SColin Riley                 {
17404640cde1SColin Riley                     FixupScriptDetails(module_desc);
17414640cde1SColin Riley                 }
1742ef20b08fSColin Riley                 break;
1743ef20b08fSColin Riley             }
1744ef20b08fSColin Riley             case eModuleKindDriver:
17454640cde1SColin Riley             {
17464640cde1SColin Riley                 if (!m_libRSDriver)
17474640cde1SColin Riley                 {
17484640cde1SColin Riley                     m_libRSDriver = module_sp;
17494640cde1SColin Riley                     LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
17504640cde1SColin Riley                 }
17514640cde1SColin Riley                 break;
17524640cde1SColin Riley             }
1753ef20b08fSColin Riley             case eModuleKindImpl:
17544640cde1SColin Riley             {
17554640cde1SColin Riley                 m_libRSCpuRef = module_sp;
17564640cde1SColin Riley                 break;
17574640cde1SColin Riley             }
1758ef20b08fSColin Riley             case eModuleKindLibRS:
17594640cde1SColin Riley             {
17604640cde1SColin Riley                 if (!m_libRS)
17614640cde1SColin Riley                 {
17624640cde1SColin Riley                     m_libRS = module_sp;
17634640cde1SColin Riley                     static ConstString gDbgPresentStr("gDebuggerPresent");
17644640cde1SColin Riley                     const Symbol* debug_present = m_libRS->FindFirstSymbolWithNameAndType(gDbgPresentStr, eSymbolTypeData);
17654640cde1SColin Riley                     if (debug_present)
17664640cde1SColin Riley                     {
17674640cde1SColin Riley                         Error error;
17684640cde1SColin Riley                         uint32_t flag = 0x00000001U;
17694640cde1SColin Riley                         Target &target = GetProcess()->GetTarget();
1770358cf1eaSGreg Clayton                         addr_t addr = debug_present->GetLoadAddress(&target);
17714640cde1SColin Riley                         GetProcess()->WriteMemory(addr, &flag, sizeof(flag), error);
17724640cde1SColin Riley                         if(error.Success())
17734640cde1SColin Riley                         {
17744640cde1SColin Riley                             if (log)
17754640cde1SColin Riley                                 log->Printf ("RenderScriptRuntime::LoadModule - Debugger present flag set on debugee");
17764640cde1SColin Riley 
17774640cde1SColin Riley                             m_debuggerPresentFlagged = true;
17784640cde1SColin Riley                         }
17794640cde1SColin Riley                         else if (log)
17804640cde1SColin Riley                         {
17814640cde1SColin Riley                             log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags '%s' ", error.AsCString());
17824640cde1SColin Riley                         }
17834640cde1SColin Riley                     }
17844640cde1SColin Riley                     else if (log)
17854640cde1SColin Riley                     {
17864640cde1SColin Riley                         log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags - symbol not found");
17874640cde1SColin Riley                     }
17884640cde1SColin Riley                 }
17894640cde1SColin Riley                 break;
17904640cde1SColin Riley             }
1791ef20b08fSColin Riley             default:
1792ef20b08fSColin Riley                 break;
1793ef20b08fSColin Riley         }
1794ef20b08fSColin Riley         if (module_loaded)
1795ef20b08fSColin Riley             Update();
1796ef20b08fSColin Riley         return module_loaded;
17975ec532a9SColin Riley     }
17985ec532a9SColin Riley     return false;
17995ec532a9SColin Riley }
18005ec532a9SColin Riley 
1801ef20b08fSColin Riley void
1802ef20b08fSColin Riley RenderScriptRuntime::Update()
1803ef20b08fSColin Riley {
1804ef20b08fSColin Riley     if (m_rsmodules.size() > 0)
1805ef20b08fSColin Riley     {
1806ef20b08fSColin Riley         if (!m_initiated)
1807ef20b08fSColin Riley         {
1808ef20b08fSColin Riley             Initiate();
1809ef20b08fSColin Riley         }
1810ef20b08fSColin Riley     }
1811ef20b08fSColin Riley }
1812ef20b08fSColin Riley 
1813ef20b08fSColin Riley 
18145ec532a9SColin Riley // The maximum line length of an .rs.info packet
18155ec532a9SColin Riley #define MAXLINE 500
18165ec532a9SColin Riley 
18175ec532a9SColin Riley // The .rs.info symbol in renderscript modules contains a string which needs to be parsed.
18185ec532a9SColin Riley // The string is basic and is parsed on a line by line basis.
18195ec532a9SColin Riley bool
18205ec532a9SColin Riley RSModuleDescriptor::ParseRSInfo()
18215ec532a9SColin Riley {
18225ec532a9SColin Riley     const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
18235ec532a9SColin Riley     if (info_sym)
18245ec532a9SColin Riley     {
1825358cf1eaSGreg Clayton         const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
18265ec532a9SColin Riley         const addr_t size = info_sym->GetByteSize();
18275ec532a9SColin Riley         const FileSpec fs = m_module->GetFileSpec();
18285ec532a9SColin Riley 
18295ec532a9SColin Riley         DataBufferSP buffer = fs.ReadFileContents(addr, size);
18305ec532a9SColin Riley 
18315ec532a9SColin Riley         if (!buffer)
18325ec532a9SColin Riley             return false;
18335ec532a9SColin Riley 
18345ec532a9SColin Riley         std::string info((const char *)buffer->GetBytes());
18355ec532a9SColin Riley 
18365ec532a9SColin Riley         std::vector<std::string> info_lines;
1837e8433cc1SBruce Mitchener         size_t lpos = info.find('\n');
18385ec532a9SColin Riley         while (lpos != std::string::npos)
18395ec532a9SColin Riley         {
18405ec532a9SColin Riley             info_lines.push_back(info.substr(0, lpos));
18415ec532a9SColin Riley             info = info.substr(lpos + 1);
1842e8433cc1SBruce Mitchener             lpos = info.find('\n');
18435ec532a9SColin Riley         }
18445ec532a9SColin Riley         size_t offset = 0;
18455ec532a9SColin Riley         while (offset < info_lines.size())
18465ec532a9SColin Riley         {
18475ec532a9SColin Riley             std::string line = info_lines[offset];
18485ec532a9SColin Riley             // Parse directives
18495ec532a9SColin Riley             uint32_t numDefns = 0;
18505ec532a9SColin Riley             if (sscanf(line.c_str(), "exportVarCount: %u", &numDefns) == 1)
18515ec532a9SColin Riley             {
18525ec532a9SColin Riley                 while (numDefns--)
18534640cde1SColin Riley                     m_globals.push_back(RSGlobalDescriptor(this, info_lines[++offset].c_str()));
18545ec532a9SColin Riley             }
18555ec532a9SColin Riley             else if (sscanf(line.c_str(), "exportFuncCount: %u", &numDefns) == 1)
18565ec532a9SColin Riley             {
18575ec532a9SColin Riley             }
18585ec532a9SColin Riley             else if (sscanf(line.c_str(), "exportForEachCount: %u", &numDefns) == 1)
18595ec532a9SColin Riley             {
18605ec532a9SColin Riley                 char name[MAXLINE];
18615ec532a9SColin Riley                 while (numDefns--)
18625ec532a9SColin Riley                 {
18635ec532a9SColin Riley                     uint32_t slot = 0;
18645ec532a9SColin Riley                     name[0] = '\0';
18655ec532a9SColin Riley                     if (sscanf(info_lines[++offset].c_str(), "%u - %s", &slot, &name[0]) == 2)
18665ec532a9SColin Riley                     {
18674640cde1SColin Riley                         m_kernels.push_back(RSKernelDescriptor(this, name, slot));
18684640cde1SColin Riley                     }
18694640cde1SColin Riley                 }
18704640cde1SColin Riley             }
18714640cde1SColin Riley             else if (sscanf(line.c_str(), "pragmaCount: %u", &numDefns) == 1)
18724640cde1SColin Riley             {
18734640cde1SColin Riley                 char name[MAXLINE];
18744640cde1SColin Riley                 char value[MAXLINE];
18754640cde1SColin Riley                 while (numDefns--)
18764640cde1SColin Riley                 {
18774640cde1SColin Riley                     name[0] = '\0';
18784640cde1SColin Riley                     value[0] = '\0';
18794640cde1SColin Riley                     if (sscanf(info_lines[++offset].c_str(), "%s - %s", &name[0], &value[0]) != 0
18804640cde1SColin Riley                         && (name[0] != '\0'))
18814640cde1SColin Riley                     {
18824640cde1SColin Riley                         m_pragmas[std::string(name)] = value;
18835ec532a9SColin Riley                     }
18845ec532a9SColin Riley                 }
18855ec532a9SColin Riley             }
18865ec532a9SColin Riley             else if (sscanf(line.c_str(), "objectSlotCount: %u", &numDefns) == 1)
18875ec532a9SColin Riley             {
18885ec532a9SColin Riley             }
18895ec532a9SColin Riley 
18905ec532a9SColin Riley             offset++;
18915ec532a9SColin Riley         }
18925ec532a9SColin Riley         return m_kernels.size() > 0;
18935ec532a9SColin Riley     }
18945ec532a9SColin Riley     return false;
18955ec532a9SColin Riley }
18965ec532a9SColin Riley 
18975ec532a9SColin Riley bool
18985ec532a9SColin Riley RenderScriptRuntime::ProbeModules(const ModuleList module_list)
18995ec532a9SColin Riley {
19005ec532a9SColin Riley     bool rs_found = false;
19015ec532a9SColin Riley     size_t num_modules = module_list.GetSize();
19025ec532a9SColin Riley     for (size_t i = 0; i < num_modules; i++)
19035ec532a9SColin Riley     {
19045ec532a9SColin Riley         auto module = module_list.GetModuleAtIndex(i);
19055ec532a9SColin Riley         rs_found |= LoadModule(module);
19065ec532a9SColin Riley     }
19075ec532a9SColin Riley     return rs_found;
19085ec532a9SColin Riley }
19095ec532a9SColin Riley 
19105ec532a9SColin Riley void
19114640cde1SColin Riley RenderScriptRuntime::Status(Stream &strm) const
19124640cde1SColin Riley {
19134640cde1SColin Riley     if (m_libRS)
19144640cde1SColin Riley     {
19154640cde1SColin Riley         strm.Printf("Runtime Library discovered.");
19164640cde1SColin Riley         strm.EOL();
19174640cde1SColin Riley     }
19184640cde1SColin Riley     if (m_libRSDriver)
19194640cde1SColin Riley     {
19204640cde1SColin Riley         strm.Printf("Runtime Driver discovered.");
19214640cde1SColin Riley         strm.EOL();
19224640cde1SColin Riley     }
19234640cde1SColin Riley     if (m_libRSCpuRef)
19244640cde1SColin Riley     {
19254640cde1SColin Riley         strm.Printf("CPU Reference Implementation discovered.");
19264640cde1SColin Riley         strm.EOL();
19274640cde1SColin Riley     }
19284640cde1SColin Riley 
19294640cde1SColin Riley     if (m_runtimeHooks.size())
19304640cde1SColin Riley     {
19314640cde1SColin Riley         strm.Printf("Runtime functions hooked:");
19324640cde1SColin Riley         strm.EOL();
19334640cde1SColin Riley         for (auto b : m_runtimeHooks)
19344640cde1SColin Riley         {
19354640cde1SColin Riley             strm.Indent(b.second->defn->name);
19364640cde1SColin Riley             strm.EOL();
19374640cde1SColin Riley         }
19384640cde1SColin Riley         strm.EOL();
19394640cde1SColin Riley     }
19404640cde1SColin Riley     else
19414640cde1SColin Riley     {
19424640cde1SColin Riley         strm.Printf("Runtime is not hooked.");
19434640cde1SColin Riley         strm.EOL();
19444640cde1SColin Riley     }
19454640cde1SColin Riley }
19464640cde1SColin Riley 
19474640cde1SColin Riley void
19484640cde1SColin Riley RenderScriptRuntime::DumpContexts(Stream &strm) const
19494640cde1SColin Riley {
19504640cde1SColin Riley     strm.Printf("Inferred RenderScript Contexts:");
19514640cde1SColin Riley     strm.EOL();
19524640cde1SColin Riley     strm.IndentMore();
19534640cde1SColin Riley 
19544640cde1SColin Riley     std::map<addr_t, uint64_t> contextReferences;
19554640cde1SColin Riley 
195678f339d1SEwan Crawford     // Iterate over all of the currently discovered scripts.
195778f339d1SEwan Crawford     // Note: We cant push or pop from m_scripts inside this loop or it may invalidate script.
19584640cde1SColin Riley     for (const auto & script : m_scripts)
19594640cde1SColin Riley     {
196078f339d1SEwan Crawford         if (!script->context.isValid())
196178f339d1SEwan Crawford             continue;
196278f339d1SEwan Crawford         lldb::addr_t context = *script->context;
196378f339d1SEwan Crawford 
196478f339d1SEwan Crawford         if (contextReferences.find(context) != contextReferences.end())
19654640cde1SColin Riley         {
196678f339d1SEwan Crawford             contextReferences[context]++;
19674640cde1SColin Riley         }
19684640cde1SColin Riley         else
19694640cde1SColin Riley         {
197078f339d1SEwan Crawford             contextReferences[context] = 1;
19714640cde1SColin Riley         }
19724640cde1SColin Riley     }
19734640cde1SColin Riley 
19744640cde1SColin Riley     for (const auto& cRef : contextReferences)
19754640cde1SColin Riley     {
19764640cde1SColin Riley         strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances", cRef.first, cRef.second);
19774640cde1SColin Riley         strm.EOL();
19784640cde1SColin Riley     }
19794640cde1SColin Riley     strm.IndentLess();
19804640cde1SColin Riley }
19814640cde1SColin Riley 
19824640cde1SColin Riley void
19834640cde1SColin Riley RenderScriptRuntime::DumpKernels(Stream &strm) const
19844640cde1SColin Riley {
19854640cde1SColin Riley     strm.Printf("RenderScript Kernels:");
19864640cde1SColin Riley     strm.EOL();
19874640cde1SColin Riley     strm.IndentMore();
19884640cde1SColin Riley     for (const auto &module : m_rsmodules)
19894640cde1SColin Riley     {
19904640cde1SColin Riley         strm.Printf("Resource '%s':",module->m_resname.c_str());
19914640cde1SColin Riley         strm.EOL();
19924640cde1SColin Riley         for (const auto &kernel : module->m_kernels)
19934640cde1SColin Riley         {
19944640cde1SColin Riley             strm.Indent(kernel.m_name.AsCString());
19954640cde1SColin Riley             strm.EOL();
19964640cde1SColin Riley         }
19974640cde1SColin Riley     }
19984640cde1SColin Riley     strm.IndentLess();
19994640cde1SColin Riley }
20004640cde1SColin Riley 
2001a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails*
2002a0f08674SEwan Crawford RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id)
2003a0f08674SEwan Crawford {
2004a0f08674SEwan Crawford     AllocationDetails* alloc = nullptr;
2005a0f08674SEwan Crawford 
2006a0f08674SEwan Crawford     // See if we can find allocation using id as an index;
2007a0f08674SEwan Crawford     if (alloc_id <= m_allocations.size() && alloc_id != 0
2008a0f08674SEwan Crawford         && m_allocations[alloc_id-1]->id == alloc_id)
2009a0f08674SEwan Crawford     {
2010a0f08674SEwan Crawford         alloc = m_allocations[alloc_id-1].get();
2011a0f08674SEwan Crawford         return alloc;
2012a0f08674SEwan Crawford     }
2013a0f08674SEwan Crawford 
2014a0f08674SEwan Crawford     // Fallback to searching
2015a0f08674SEwan Crawford     for (const auto & a : m_allocations)
2016a0f08674SEwan Crawford     {
2017a0f08674SEwan Crawford        if (a->id == alloc_id)
2018a0f08674SEwan Crawford        {
2019a0f08674SEwan Crawford            alloc = a.get();
2020a0f08674SEwan Crawford            break;
2021a0f08674SEwan Crawford        }
2022a0f08674SEwan Crawford     }
2023a0f08674SEwan Crawford 
2024a0f08674SEwan Crawford     if (alloc == nullptr)
2025a0f08674SEwan Crawford     {
2026a0f08674SEwan Crawford         strm.Printf("Error: Couldn't find allocation with id matching %u", alloc_id);
2027a0f08674SEwan Crawford         strm.EOL();
2028a0f08674SEwan Crawford     }
2029a0f08674SEwan Crawford 
2030a0f08674SEwan Crawford     return alloc;
2031a0f08674SEwan Crawford }
2032a0f08674SEwan Crawford 
2033a0f08674SEwan Crawford // Prints the contents of an allocation to the output stream, which may be a file
2034a0f08674SEwan Crawford bool
2035a0f08674SEwan Crawford RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame* frame_ptr, const uint32_t id)
2036a0f08674SEwan Crawford {
2037a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2038a0f08674SEwan Crawford 
2039a0f08674SEwan Crawford     // Check we can find the desired allocation
2040a0f08674SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, id);
2041a0f08674SEwan Crawford     if (!alloc)
2042a0f08674SEwan Crawford         return false; // FindAllocByID() will print error message for us here
2043a0f08674SEwan Crawford 
2044a0f08674SEwan Crawford     if (log)
2045a0f08674SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
2046a0f08674SEwan Crawford 
2047a0f08674SEwan Crawford     // Check we have information about the allocation, if not calculate it
2048a0f08674SEwan Crawford     if (!alloc->data_ptr.isValid() || !alloc->type.isValid() ||
2049a0f08674SEwan Crawford         !alloc->type_vec_size.isValid() || !alloc->dimension.isValid())
2050a0f08674SEwan Crawford     {
2051a0f08674SEwan Crawford         if (log)
2052a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::DumpAllocation - Allocation details not calculated yet, jitting info");
2053a0f08674SEwan Crawford 
2054a0f08674SEwan Crawford         // JIT all the allocation information
2055a0f08674SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
2056a0f08674SEwan Crawford         {
2057a0f08674SEwan Crawford             strm.Printf("Error: Couldn't JIT allocation details");
2058a0f08674SEwan Crawford             strm.EOL();
2059a0f08674SEwan Crawford             return false;
2060a0f08674SEwan Crawford         }
2061a0f08674SEwan Crawford     }
2062a0f08674SEwan Crawford 
2063a0f08674SEwan Crawford     // Establish format and size of each data element
2064a0f08674SEwan Crawford     const unsigned int vec_size = *alloc->type_vec_size.get();
2065a0f08674SEwan Crawford     const AllocationDetails::DataType type = *alloc->type.get();
2066a0f08674SEwan Crawford 
2067a0f08674SEwan Crawford     assert(type >= AllocationDetails::RS_TYPE_NONE && type <= AllocationDetails::RS_TYPE_BOOLEAN
2068a0f08674SEwan Crawford                                                    && "Invalid allocation type");
2069a0f08674SEwan Crawford 
2070a0f08674SEwan Crawford     lldb::Format format = vec_size == 1 ? static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatSingle])
2071a0f08674SEwan Crawford                                         : static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatVector]);
2072a0f08674SEwan Crawford 
2073a0f08674SEwan Crawford     const unsigned int data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
2074a0f08674SEwan Crawford     // Renderscript pads vector 3 elements to vector 4
2075a0f08674SEwan Crawford     const unsigned int elem_padding = vec_size == 3 ? AllocationDetails::RSTypeToFormat[type][eElementSize] : 0;
2076a0f08674SEwan Crawford 
2077a0f08674SEwan Crawford     if (log)
2078a0f08674SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - Element size %u bytes, element padding %u bytes",
2079a0f08674SEwan Crawford                     data_size, elem_padding);
2080a0f08674SEwan Crawford 
208155232f09SEwan Crawford     // Allocate a buffer to copy data into
208255232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
208355232f09SEwan Crawford     if (!buffer)
208455232f09SEwan Crawford     {
208555232f09SEwan Crawford         strm.Printf("Error: Couldn't allocate a read allocation data into memory");
208655232f09SEwan Crawford         strm.EOL();
208755232f09SEwan Crawford         return false;
208855232f09SEwan Crawford     }
208955232f09SEwan Crawford 
2090a0f08674SEwan Crawford     // Calculate stride between rows as there may be padding at end of rows since
2091a0f08674SEwan Crawford     // allocated memory is 16-byte aligned
2092a0f08674SEwan Crawford     if (!alloc->stride.isValid())
2093a0f08674SEwan Crawford     {
2094a0f08674SEwan Crawford         if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
2095a0f08674SEwan Crawford             alloc->stride = 0;
2096a0f08674SEwan Crawford         else if (!JITAllocationStride(alloc, frame_ptr))
2097a0f08674SEwan Crawford         {
2098a0f08674SEwan Crawford             strm.Printf("Error: Couldn't calculate allocation row stride");
2099a0f08674SEwan Crawford             strm.EOL();
2100a0f08674SEwan Crawford             return false;
2101a0f08674SEwan Crawford         }
2102a0f08674SEwan Crawford     }
2103a0f08674SEwan Crawford     const unsigned int stride = *alloc->stride.get();
2104a0f08674SEwan Crawford     const unsigned int size = *alloc->size.get(); //size of last element
2105a0f08674SEwan Crawford 
2106a0f08674SEwan Crawford     if (log)
2107a0f08674SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - stride %u bytes, size %u bytes", stride, size);
2108a0f08674SEwan Crawford 
2109a0f08674SEwan Crawford     // Find dimensions used to index loops, so need to be non-zero
2110a0f08674SEwan Crawford     unsigned int dim_x = alloc->dimension.get()->dim_1;
2111a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 1 : dim_x;
2112a0f08674SEwan Crawford 
2113a0f08674SEwan Crawford     unsigned int dim_y = alloc->dimension.get()->dim_2;
2114a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 1 : dim_y;
2115a0f08674SEwan Crawford 
2116a0f08674SEwan Crawford     unsigned int dim_z = alloc->dimension.get()->dim_3;
2117a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 1 : dim_z;
2118a0f08674SEwan Crawford 
211955232f09SEwan Crawford     // Use data extractor to format output
212055232f09SEwan Crawford     const uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
212155232f09SEwan Crawford     DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(), archByteSize);
212255232f09SEwan Crawford 
2123a0f08674SEwan Crawford     unsigned int offset = 0;   // Offset in buffer to next element to be printed
2124a0f08674SEwan Crawford     unsigned int prev_row = 0; // Offset to the start of the previous row
2125a0f08674SEwan Crawford 
2126a0f08674SEwan Crawford     // Iterate over allocation dimensions, printing results to user
2127a0f08674SEwan Crawford     strm.Printf("Data (X, Y, Z):");
2128a0f08674SEwan Crawford     for (unsigned int z = 0; z < dim_z; ++z)
2129a0f08674SEwan Crawford     {
2130a0f08674SEwan Crawford         for (unsigned int y = 0; y < dim_y; ++y)
2131a0f08674SEwan Crawford         {
2132a0f08674SEwan Crawford             // Use stride to index start of next row.
2133a0f08674SEwan Crawford             if (!(y==0 && z==0))
2134a0f08674SEwan Crawford                 offset = prev_row + stride;
2135a0f08674SEwan Crawford             prev_row = offset;
2136a0f08674SEwan Crawford 
2137a0f08674SEwan Crawford             // Print each element in the row individually
2138a0f08674SEwan Crawford             for (unsigned int x = 0; x < dim_x; ++x)
2139a0f08674SEwan Crawford             {
2140a0f08674SEwan Crawford                 strm.Printf("\n(%u, %u, %u) = ", x, y, z);
2141a0f08674SEwan Crawford                 alloc_data.Dump(&strm, offset, format, data_size, 1, 1, LLDB_INVALID_ADDRESS, 0, 0);
2142a0f08674SEwan Crawford                 offset += data_size + elem_padding;
2143a0f08674SEwan Crawford             }
2144a0f08674SEwan Crawford         }
2145a0f08674SEwan Crawford     }
2146a0f08674SEwan Crawford     strm.EOL();
2147a0f08674SEwan Crawford 
2148a0f08674SEwan Crawford     return true;
2149a0f08674SEwan Crawford }
2150a0f08674SEwan Crawford 
215115f2bd95SEwan Crawford // Prints infomation regarding all the currently loaded allocations.
215215f2bd95SEwan Crawford // These details are gathered by jitting the runtime, which has as latency.
215315f2bd95SEwan Crawford void
215415f2bd95SEwan Crawford RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame* frame_ptr, bool recompute)
215515f2bd95SEwan Crawford {
215615f2bd95SEwan Crawford     strm.Printf("RenderScript Allocations:");
215715f2bd95SEwan Crawford     strm.EOL();
215815f2bd95SEwan Crawford     strm.IndentMore();
215915f2bd95SEwan Crawford 
216015f2bd95SEwan Crawford     for (auto &alloc : m_allocations)
216115f2bd95SEwan Crawford     {
216215f2bd95SEwan Crawford         // JIT the allocation info if we haven't done it, or the user forces us to.
216315f2bd95SEwan Crawford         bool do_refresh = !alloc->data_ptr.isValid() || recompute;
216415f2bd95SEwan Crawford 
216515f2bd95SEwan Crawford         // JIT current allocation information
216615f2bd95SEwan Crawford         if (do_refresh && !RefreshAllocation(alloc.get(), frame_ptr))
216715f2bd95SEwan Crawford         {
216815f2bd95SEwan Crawford             strm.Printf("Error: Couldn't evaluate details for allocation %u\n", alloc->id);
216915f2bd95SEwan Crawford             continue;
217015f2bd95SEwan Crawford         }
217115f2bd95SEwan Crawford 
217215f2bd95SEwan Crawford         strm.Printf("%u:\n",alloc->id);
217315f2bd95SEwan Crawford         strm.IndentMore();
217415f2bd95SEwan Crawford 
217515f2bd95SEwan Crawford         strm.Indent("Context: ");
217615f2bd95SEwan Crawford         if (!alloc->context.isValid())
217715f2bd95SEwan Crawford             strm.Printf("unknown\n");
217815f2bd95SEwan Crawford         else
217915f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
218015f2bd95SEwan Crawford 
218115f2bd95SEwan Crawford         strm.Indent("Address: ");
218215f2bd95SEwan Crawford         if (!alloc->address.isValid())
218315f2bd95SEwan Crawford             strm.Printf("unknown\n");
218415f2bd95SEwan Crawford         else
218515f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
218615f2bd95SEwan Crawford 
218715f2bd95SEwan Crawford         strm.Indent("Data pointer: ");
218815f2bd95SEwan Crawford         if (!alloc->data_ptr.isValid())
218915f2bd95SEwan Crawford             strm.Printf("unknown\n");
219015f2bd95SEwan Crawford         else
219115f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
219215f2bd95SEwan Crawford 
219315f2bd95SEwan Crawford         strm.Indent("Dimensions: ");
219415f2bd95SEwan Crawford         if (!alloc->dimension.isValid())
219515f2bd95SEwan Crawford             strm.Printf("unknown\n");
219615f2bd95SEwan Crawford         else
219715f2bd95SEwan Crawford             strm.Printf("(%d, %d, %d)\n", alloc->dimension.get()->dim_1,
219815f2bd95SEwan Crawford                                           alloc->dimension.get()->dim_2,
219915f2bd95SEwan Crawford                                           alloc->dimension.get()->dim_3);
220015f2bd95SEwan Crawford 
220115f2bd95SEwan Crawford         strm.Indent("Data Type: ");
220215f2bd95SEwan Crawford         if (!alloc->type.isValid() || !alloc->type_vec_size.isValid())
220315f2bd95SEwan Crawford             strm.Printf("unknown\n");
220415f2bd95SEwan Crawford         else
220515f2bd95SEwan Crawford         {
220615f2bd95SEwan Crawford             const int vector_size = *alloc->type_vec_size.get();
220715f2bd95SEwan Crawford             const AllocationDetails::DataType type = *alloc->type.get();
220815f2bd95SEwan Crawford 
220915f2bd95SEwan Crawford             if (vector_size > 4 || vector_size < 1 ||
221015f2bd95SEwan Crawford                 type < AllocationDetails::RS_TYPE_NONE || type > AllocationDetails::RS_TYPE_BOOLEAN)
221115f2bd95SEwan Crawford                 strm.Printf("invalid type\n");
221215f2bd95SEwan Crawford             else
221315f2bd95SEwan Crawford                 strm.Printf("%s\n", AllocationDetails::RsDataTypeToString[static_cast<unsigned int>(type)][vector_size-1]);
221415f2bd95SEwan Crawford         }
221515f2bd95SEwan Crawford 
221615f2bd95SEwan Crawford         strm.Indent("Data Kind: ");
221715f2bd95SEwan Crawford         if (!alloc->type_kind.isValid())
221815f2bd95SEwan Crawford             strm.Printf("unknown\n");
221915f2bd95SEwan Crawford         else
222015f2bd95SEwan Crawford         {
222115f2bd95SEwan Crawford             const AllocationDetails::DataKind kind = *alloc->type_kind.get();
222215f2bd95SEwan Crawford             if (kind < AllocationDetails::RS_KIND_USER || kind > AllocationDetails::RS_KIND_PIXEL_YUV)
222315f2bd95SEwan Crawford                 strm.Printf("invalid kind\n");
222415f2bd95SEwan Crawford             else
222515f2bd95SEwan Crawford                 strm.Printf("%s\n", AllocationDetails::RsDataKindToString[static_cast<unsigned int>(kind)]);
222615f2bd95SEwan Crawford         }
222715f2bd95SEwan Crawford 
222815f2bd95SEwan Crawford         strm.EOL();
222915f2bd95SEwan Crawford         strm.IndentLess();
223015f2bd95SEwan Crawford     }
223115f2bd95SEwan Crawford     strm.IndentLess();
223215f2bd95SEwan Crawford }
223315f2bd95SEwan Crawford 
22347dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
22357dc7771cSEwan Crawford void
22367dc7771cSEwan Crawford RenderScriptRuntime::BreakOnModuleKernels(const RSModuleDescriptorSP rsmodule_sp)
22377dc7771cSEwan Crawford {
22387dc7771cSEwan Crawford     for (const auto &kernel : rsmodule_sp->m_kernels)
22397dc7771cSEwan Crawford     {
22407dc7771cSEwan Crawford         // Don't set breakpoint on 'root' kernel
22417dc7771cSEwan Crawford         if (strcmp(kernel.m_name.AsCString(), "root") == 0)
22427dc7771cSEwan Crawford             continue;
22437dc7771cSEwan Crawford 
22447dc7771cSEwan Crawford         CreateKernelBreakpoint(kernel.m_name);
22457dc7771cSEwan Crawford     }
22467dc7771cSEwan Crawford }
22477dc7771cSEwan Crawford 
22487dc7771cSEwan Crawford // Method is internally called by the 'kernel breakpoint all' command to
22497dc7771cSEwan Crawford // enable or disable breaking on all kernels.
22507dc7771cSEwan Crawford //
22517dc7771cSEwan Crawford // When do_break is true we want to enable this functionality.
22527dc7771cSEwan Crawford // When do_break is false we want to disable it.
22537dc7771cSEwan Crawford void
22547dc7771cSEwan Crawford RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target)
22557dc7771cSEwan Crawford {
225654782db7SEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
22577dc7771cSEwan Crawford 
22587dc7771cSEwan Crawford     InitSearchFilter(target);
22597dc7771cSEwan Crawford 
22607dc7771cSEwan Crawford     // Set breakpoints on all the kernels
22617dc7771cSEwan Crawford     if (do_break && !m_breakAllKernels)
22627dc7771cSEwan Crawford     {
22637dc7771cSEwan Crawford         m_breakAllKernels = true;
22647dc7771cSEwan Crawford 
22657dc7771cSEwan Crawford         for (const auto &module : m_rsmodules)
22667dc7771cSEwan Crawford             BreakOnModuleKernels(module);
22677dc7771cSEwan Crawford 
22687dc7771cSEwan Crawford         if (log)
22697dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::SetBreakAllKernels(True)"
22707dc7771cSEwan Crawford                         "- breakpoints set on all currently loaded kernels");
22717dc7771cSEwan Crawford     }
22727dc7771cSEwan Crawford     else if (!do_break && m_breakAllKernels) // Breakpoints won't be set on any new kernels.
22737dc7771cSEwan Crawford     {
22747dc7771cSEwan Crawford         m_breakAllKernels = false;
22757dc7771cSEwan Crawford 
22767dc7771cSEwan Crawford         if (log)
22777dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::SetBreakAllKernels(False) - breakpoints no longer automatically set");
22787dc7771cSEwan Crawford     }
22797dc7771cSEwan Crawford }
22807dc7771cSEwan Crawford 
22817dc7771cSEwan Crawford // Given the name of a kernel this function creates a breakpoint using our
22827dc7771cSEwan Crawford // own breakpoint resolver, and returns the Breakpoint shared pointer.
22837dc7771cSEwan Crawford BreakpointSP
22847dc7771cSEwan Crawford RenderScriptRuntime::CreateKernelBreakpoint(const ConstString& name)
22857dc7771cSEwan Crawford {
228654782db7SEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
22877dc7771cSEwan Crawford 
22887dc7771cSEwan Crawford     if (!m_filtersp)
22897dc7771cSEwan Crawford     {
22907dc7771cSEwan Crawford         if (log)
22917dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::CreateKernelBreakpoint - Error: No breakpoint search filter set");
22927dc7771cSEwan Crawford         return nullptr;
22937dc7771cSEwan Crawford     }
22947dc7771cSEwan Crawford 
22957dc7771cSEwan Crawford     BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
22967dc7771cSEwan Crawford     BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(m_filtersp, resolver_sp, false, false, false);
22977dc7771cSEwan Crawford 
229854782db7SEwan Crawford     // Give RS breakpoints a specific name, so the user can manipulate them as a group.
229954782db7SEwan Crawford     Error err;
230054782db7SEwan Crawford     if (!bp->AddName("RenderScriptKernel", err) && log)
230154782db7SEwan Crawford         log->Printf("RenderScriptRuntime::CreateKernelBreakpoint: Error setting break name, %s", err.AsCString());
230254782db7SEwan Crawford 
23037dc7771cSEwan Crawford     return bp;
23047dc7771cSEwan Crawford }
23057dc7771cSEwan Crawford 
2306*018f5a7eSEwan Crawford // Given an expression for a variable this function tries to calculate the variable's value.
2307*018f5a7eSEwan Crawford // If this is possible it returns true and sets the uint64_t parameter to the variables unsigned value.
2308*018f5a7eSEwan Crawford // Otherwise function returns false.
2309*018f5a7eSEwan Crawford bool
2310*018f5a7eSEwan Crawford RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp, const char* var_name, uint64_t& val)
2311*018f5a7eSEwan Crawford {
2312*018f5a7eSEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2313*018f5a7eSEwan Crawford     Error error;
2314*018f5a7eSEwan Crawford     VariableSP var_sp;
2315*018f5a7eSEwan Crawford 
2316*018f5a7eSEwan Crawford     // Find variable in stack frame
2317*018f5a7eSEwan Crawford     ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(var_name,
2318*018f5a7eSEwan Crawford                                                                        eNoDynamicValues,
2319*018f5a7eSEwan Crawford                                                                        StackFrame::eExpressionPathOptionCheckPtrVsMember |
2320*018f5a7eSEwan Crawford                                                                        StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
2321*018f5a7eSEwan Crawford                                                                        var_sp,
2322*018f5a7eSEwan Crawford                                                                        error));
2323*018f5a7eSEwan Crawford     if (!error.Success())
2324*018f5a7eSEwan Crawford     {
2325*018f5a7eSEwan Crawford         if (log)
2326*018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't find '%s' in frame", var_name);
2327*018f5a7eSEwan Crawford 
2328*018f5a7eSEwan Crawford         return false;
2329*018f5a7eSEwan Crawford     }
2330*018f5a7eSEwan Crawford 
2331*018f5a7eSEwan Crawford     // Find the unsigned int value for the variable
2332*018f5a7eSEwan Crawford     bool success = false;
2333*018f5a7eSEwan Crawford     val = value_sp->GetValueAsUnsigned(0, &success);
2334*018f5a7eSEwan Crawford     if (!success)
2335*018f5a7eSEwan Crawford     {
2336*018f5a7eSEwan Crawford         if (log)
2337*018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't parse '%s' as an unsigned int", var_name);
2338*018f5a7eSEwan Crawford 
2339*018f5a7eSEwan Crawford         return false;
2340*018f5a7eSEwan Crawford     }
2341*018f5a7eSEwan Crawford 
2342*018f5a7eSEwan Crawford     return true;
2343*018f5a7eSEwan Crawford }
2344*018f5a7eSEwan Crawford 
2345*018f5a7eSEwan Crawford // Callback when a kernel breakpoint hits and we're looking for a specific coordinate.
2346*018f5a7eSEwan Crawford // Baton parameter contains a pointer to the target coordinate we want to break on.
2347*018f5a7eSEwan Crawford // Function then checks the .expand frame for the current coordinate and breaks to user if it matches.
2348*018f5a7eSEwan Crawford // Parameter 'break_id' is the id of the Breakpoint which made the callback.
2349*018f5a7eSEwan Crawford // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
2350*018f5a7eSEwan Crawford // a single logical breakpoint can have multiple addresses.
2351*018f5a7eSEwan Crawford bool
2352*018f5a7eSEwan Crawford RenderScriptRuntime::KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx,
2353*018f5a7eSEwan Crawford                                          user_id_t break_id, user_id_t break_loc_id)
2354*018f5a7eSEwan Crawford {
2355*018f5a7eSEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
2356*018f5a7eSEwan Crawford 
2357*018f5a7eSEwan Crawford     assert(baton && "Error: null baton in conditional kernel breakpoint callback");
2358*018f5a7eSEwan Crawford 
2359*018f5a7eSEwan Crawford     // Coordinate we want to stop on
2360*018f5a7eSEwan Crawford     const int* target_coord = static_cast<const int*>(baton);
2361*018f5a7eSEwan Crawford 
2362*018f5a7eSEwan Crawford     if (log)
2363*018f5a7eSEwan Crawford         log->Printf("RenderScriptRuntime::KernelBreakpointHit - Break ID %" PRIu64 ", target coord (%d, %d, %d)",
2364*018f5a7eSEwan Crawford                     break_id, target_coord[0], target_coord[1], target_coord[2]);
2365*018f5a7eSEwan Crawford 
2366*018f5a7eSEwan Crawford     // Go up one stack frame to .expand kernel
2367*018f5a7eSEwan Crawford     ExecutionContext context(ctx->exe_ctx_ref);
2368*018f5a7eSEwan Crawford     ThreadSP thread_sp = context.GetThreadSP();
2369*018f5a7eSEwan Crawford     if (!thread_sp->SetSelectedFrameByIndex(1))
2370*018f5a7eSEwan Crawford     {
2371*018f5a7eSEwan Crawford         if (log)
2372*018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't go up stack frame");
2373*018f5a7eSEwan Crawford 
2374*018f5a7eSEwan Crawford        return false;
2375*018f5a7eSEwan Crawford     }
2376*018f5a7eSEwan Crawford 
2377*018f5a7eSEwan Crawford     StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
2378*018f5a7eSEwan Crawford     if (!frame_sp)
2379*018f5a7eSEwan Crawford     {
2380*018f5a7eSEwan Crawford         if (log)
2381*018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't select .expand stack frame");
2382*018f5a7eSEwan Crawford 
2383*018f5a7eSEwan Crawford         return false;
2384*018f5a7eSEwan Crawford     }
2385*018f5a7eSEwan Crawford 
2386*018f5a7eSEwan Crawford     // Get values for variables in .expand frame that tell us the current kernel invocation
2387*018f5a7eSEwan Crawford     const char* coord_expressions[] = {"rsIndex", "p->current.y", "p->current.z"};
2388*018f5a7eSEwan Crawford     uint64_t current_coord[3] = {0, 0, 0};
2389*018f5a7eSEwan Crawford 
2390*018f5a7eSEwan Crawford     for(int i = 0; i < 3; ++i)
2391*018f5a7eSEwan Crawford     {
2392*018f5a7eSEwan Crawford         if (!GetFrameVarAsUnsigned(frame_sp, coord_expressions[i], current_coord[i]))
2393*018f5a7eSEwan Crawford             return false;
2394*018f5a7eSEwan Crawford 
2395*018f5a7eSEwan Crawford         if (log)
2396*018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit, %s = %" PRIu64, coord_expressions[i], current_coord[i]);
2397*018f5a7eSEwan Crawford     }
2398*018f5a7eSEwan Crawford 
2399*018f5a7eSEwan Crawford     // Check if the current kernel invocation coordinate matches our target coordinate
2400*018f5a7eSEwan Crawford     if (current_coord[0] == static_cast<uint64_t>(target_coord[0]) &&
2401*018f5a7eSEwan Crawford         current_coord[1] == static_cast<uint64_t>(target_coord[1]) &&
2402*018f5a7eSEwan Crawford         current_coord[2] == static_cast<uint64_t>(target_coord[2]))
2403*018f5a7eSEwan Crawford     {
2404*018f5a7eSEwan Crawford         if (log)
2405*018f5a7eSEwan Crawford              log->Printf("RenderScriptRuntime::KernelBreakpointHit, BREAKING %" PRIu64 ", %" PRIu64 ", %" PRIu64,
2406*018f5a7eSEwan Crawford                          current_coord[0], current_coord[1], current_coord[2]);
2407*018f5a7eSEwan Crawford 
2408*018f5a7eSEwan Crawford         BreakpointSP breakpoint_sp = context.GetTargetPtr()->GetBreakpointByID(break_id);
2409*018f5a7eSEwan Crawford         assert(breakpoint_sp != nullptr && "Error: Couldn't find breakpoint matching break id for callback");
2410*018f5a7eSEwan Crawford         breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint should only be hit once.
2411*018f5a7eSEwan Crawford         return true;
2412*018f5a7eSEwan Crawford     }
2413*018f5a7eSEwan Crawford 
2414*018f5a7eSEwan Crawford     // No match on coordinate
2415*018f5a7eSEwan Crawford     return false;
2416*018f5a7eSEwan Crawford }
2417*018f5a7eSEwan Crawford 
2418*018f5a7eSEwan Crawford // Tries to set a breakpoint on the start of a kernel, resolved using the kernel name.
2419*018f5a7eSEwan Crawford // Argument 'coords', represents a three dimensional coordinate which can be used to specify
2420*018f5a7eSEwan Crawford // a single kernel instance to break on. If this is set then we add a callback to the breakpoint.
24214640cde1SColin Riley void
2422*018f5a7eSEwan Crawford RenderScriptRuntime::PlaceBreakpointOnKernel(Stream &strm, const char* name, const std::array<int,3> coords,
2423*018f5a7eSEwan Crawford                                              Error& error, TargetSP target)
24244640cde1SColin Riley {
24254640cde1SColin Riley     if (!name)
24264640cde1SColin Riley     {
24274640cde1SColin Riley         error.SetErrorString("invalid kernel name");
24284640cde1SColin Riley         return;
24294640cde1SColin Riley     }
24304640cde1SColin Riley 
24317dc7771cSEwan Crawford     InitSearchFilter(target);
243298156583SEwan Crawford 
24334640cde1SColin Riley     ConstString kernel_name(name);
24347dc7771cSEwan Crawford     BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
2435*018f5a7eSEwan Crawford 
2436*018f5a7eSEwan Crawford     // We have a conditional breakpoint on a specific coordinate
2437*018f5a7eSEwan Crawford     if (coords[0] != -1)
2438*018f5a7eSEwan Crawford     {
2439*018f5a7eSEwan Crawford         strm.Printf("Conditional kernel breakpoint on coordinate %d, %d, %d", coords[0], coords[1], coords[2]);
2440*018f5a7eSEwan Crawford         strm.EOL();
2441*018f5a7eSEwan Crawford 
2442*018f5a7eSEwan Crawford         // Allocate memory for the baton, and copy over coordinate
2443*018f5a7eSEwan Crawford         int* baton = new int[3];
2444*018f5a7eSEwan Crawford         baton[0] = coords[0]; baton[1] = coords[1]; baton[2] = coords[2];
2445*018f5a7eSEwan Crawford 
2446*018f5a7eSEwan Crawford         // Create a callback that will be invoked everytime the breakpoint is hit.
2447*018f5a7eSEwan Crawford         // The baton object passed to the handler is the target coordinate we want to break on.
2448*018f5a7eSEwan Crawford         bp->SetCallback(KernelBreakpointHit, baton, true);
2449*018f5a7eSEwan Crawford 
2450*018f5a7eSEwan Crawford         // Store a shared pointer to the baton, so the memory will eventually be cleaned up after destruction
2451*018f5a7eSEwan Crawford         m_conditional_breaks[bp->GetID()] = std::shared_ptr<int>(baton);
2452*018f5a7eSEwan Crawford     }
2453*018f5a7eSEwan Crawford 
245498156583SEwan Crawford     if (bp)
245598156583SEwan Crawford         bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
24564640cde1SColin Riley 
24574640cde1SColin Riley     return;
24584640cde1SColin Riley }
24594640cde1SColin Riley 
24604640cde1SColin Riley void
24615ec532a9SColin Riley RenderScriptRuntime::DumpModules(Stream &strm) const
24625ec532a9SColin Riley {
24635ec532a9SColin Riley     strm.Printf("RenderScript Modules:");
24645ec532a9SColin Riley     strm.EOL();
24655ec532a9SColin Riley     strm.IndentMore();
24665ec532a9SColin Riley     for (const auto &module : m_rsmodules)
24675ec532a9SColin Riley     {
24684640cde1SColin Riley         module->Dump(strm);
24695ec532a9SColin Riley     }
24705ec532a9SColin Riley     strm.IndentLess();
24715ec532a9SColin Riley }
24725ec532a9SColin Riley 
247378f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails*
247478f339d1SEwan Crawford RenderScriptRuntime::LookUpScript(addr_t address, bool create)
247578f339d1SEwan Crawford {
247678f339d1SEwan Crawford     for (const auto & s : m_scripts)
247778f339d1SEwan Crawford     {
247878f339d1SEwan Crawford         if (s->script.isValid())
247978f339d1SEwan Crawford             if (*s->script == address)
248078f339d1SEwan Crawford                 return s.get();
248178f339d1SEwan Crawford     }
248278f339d1SEwan Crawford     if (create)
248378f339d1SEwan Crawford     {
248478f339d1SEwan Crawford         std::unique_ptr<ScriptDetails> s(new ScriptDetails);
248578f339d1SEwan Crawford         s->script = address;
248678f339d1SEwan Crawford         m_scripts.push_back(std::move(s));
2487d10ca9deSEwan Crawford         return m_scripts.back().get();
248878f339d1SEwan Crawford     }
248978f339d1SEwan Crawford     return nullptr;
249078f339d1SEwan Crawford }
249178f339d1SEwan Crawford 
249278f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails*
249378f339d1SEwan Crawford RenderScriptRuntime::LookUpAllocation(addr_t address, bool create)
249478f339d1SEwan Crawford {
249578f339d1SEwan Crawford     for (const auto & a : m_allocations)
249678f339d1SEwan Crawford     {
249778f339d1SEwan Crawford         if (a->address.isValid())
249878f339d1SEwan Crawford             if (*a->address == address)
249978f339d1SEwan Crawford                 return a.get();
250078f339d1SEwan Crawford     }
250178f339d1SEwan Crawford     if (create)
250278f339d1SEwan Crawford     {
250378f339d1SEwan Crawford         std::unique_ptr<AllocationDetails> a(new AllocationDetails);
250478f339d1SEwan Crawford         a->address = address;
250578f339d1SEwan Crawford         m_allocations.push_back(std::move(a));
2506d10ca9deSEwan Crawford         return m_allocations.back().get();
250778f339d1SEwan Crawford     }
250878f339d1SEwan Crawford     return nullptr;
250978f339d1SEwan Crawford }
251078f339d1SEwan Crawford 
25115ec532a9SColin Riley void
25125ec532a9SColin Riley RSModuleDescriptor::Dump(Stream &strm) const
25135ec532a9SColin Riley {
25145ec532a9SColin Riley     strm.Indent();
25155ec532a9SColin Riley     m_module->GetFileSpec().Dump(&strm);
25164640cde1SColin Riley     if(m_module->GetNumCompileUnits())
25174640cde1SColin Riley     {
25184640cde1SColin Riley         strm.Indent("Debug info loaded.");
25194640cde1SColin Riley     }
25204640cde1SColin Riley     else
25214640cde1SColin Riley     {
25224640cde1SColin Riley         strm.Indent("Debug info does not exist.");
25234640cde1SColin Riley     }
25245ec532a9SColin Riley     strm.EOL();
25255ec532a9SColin Riley     strm.IndentMore();
25265ec532a9SColin Riley     strm.Indent();
2527189598edSColin Riley     strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
25285ec532a9SColin Riley     strm.EOL();
25295ec532a9SColin Riley     strm.IndentMore();
25305ec532a9SColin Riley     for (const auto &global : m_globals)
25315ec532a9SColin Riley     {
25325ec532a9SColin Riley         global.Dump(strm);
25335ec532a9SColin Riley     }
25345ec532a9SColin Riley     strm.IndentLess();
25355ec532a9SColin Riley     strm.Indent();
2536189598edSColin Riley     strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
25375ec532a9SColin Riley     strm.EOL();
25385ec532a9SColin Riley     strm.IndentMore();
25395ec532a9SColin Riley     for (const auto &kernel : m_kernels)
25405ec532a9SColin Riley     {
25415ec532a9SColin Riley         kernel.Dump(strm);
25425ec532a9SColin Riley     }
25434640cde1SColin Riley     strm.Printf("Pragmas: %"  PRIu64 , static_cast<uint64_t>(m_pragmas.size()));
25444640cde1SColin Riley     strm.EOL();
25454640cde1SColin Riley     strm.IndentMore();
25464640cde1SColin Riley     for (const auto &key_val : m_pragmas)
25474640cde1SColin Riley     {
25484640cde1SColin Riley         strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
25494640cde1SColin Riley         strm.EOL();
25504640cde1SColin Riley     }
25515ec532a9SColin Riley     strm.IndentLess(4);
25525ec532a9SColin Riley }
25535ec532a9SColin Riley 
25545ec532a9SColin Riley void
25555ec532a9SColin Riley RSGlobalDescriptor::Dump(Stream &strm) const
25565ec532a9SColin Riley {
25575ec532a9SColin Riley     strm.Indent(m_name.AsCString());
25584640cde1SColin Riley     VariableList var_list;
25594640cde1SColin Riley     m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
25604640cde1SColin Riley     if (var_list.GetSize() == 1)
25614640cde1SColin Riley     {
25624640cde1SColin Riley         auto var = var_list.GetVariableAtIndex(0);
25634640cde1SColin Riley         auto type = var->GetType();
25644640cde1SColin Riley         if(type)
25654640cde1SColin Riley         {
25664640cde1SColin Riley             strm.Printf(" - ");
25674640cde1SColin Riley             type->DumpTypeName(&strm);
25684640cde1SColin Riley         }
25694640cde1SColin Riley         else
25704640cde1SColin Riley         {
25714640cde1SColin Riley             strm.Printf(" - Unknown Type");
25724640cde1SColin Riley         }
25734640cde1SColin Riley     }
25744640cde1SColin Riley     else
25754640cde1SColin Riley     {
25764640cde1SColin Riley         strm.Printf(" - variable identified, but not found in binary");
25774640cde1SColin Riley         const Symbol* s = m_module->m_module->FindFirstSymbolWithNameAndType(m_name, eSymbolTypeData);
25784640cde1SColin Riley         if (s)
25794640cde1SColin Riley         {
25804640cde1SColin Riley             strm.Printf(" (symbol exists) ");
25814640cde1SColin Riley         }
25824640cde1SColin Riley     }
25834640cde1SColin Riley 
25845ec532a9SColin Riley     strm.EOL();
25855ec532a9SColin Riley }
25865ec532a9SColin Riley 
25875ec532a9SColin Riley void
25885ec532a9SColin Riley RSKernelDescriptor::Dump(Stream &strm) const
25895ec532a9SColin Riley {
25905ec532a9SColin Riley     strm.Indent(m_name.AsCString());
25915ec532a9SColin Riley     strm.EOL();
25925ec532a9SColin Riley }
25935ec532a9SColin Riley 
25945ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleProbe : public CommandObjectParsed
25955ec532a9SColin Riley {
25965ec532a9SColin Riley   private:
25975ec532a9SColin Riley   public:
25985ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleProbe(CommandInterpreter &interpreter)
25995ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module probe",
26005ec532a9SColin Riley                               "Initiates a Probe of all loaded modules for kernels and other renderscript objects.",
26015ec532a9SColin Riley                               "renderscript module probe",
2602e87764f2SEnrico Granata                               eCommandRequiresTarget | eCommandRequiresProcess | eCommandProcessMustBeLaunched)
26035ec532a9SColin Riley     {
26045ec532a9SColin Riley     }
26055ec532a9SColin Riley 
26065ec532a9SColin Riley     ~CommandObjectRenderScriptRuntimeModuleProbe() {}
26075ec532a9SColin Riley 
26085ec532a9SColin Riley     bool
26095ec532a9SColin Riley     DoExecute(Args &command, CommandReturnObject &result)
26105ec532a9SColin Riley     {
26115ec532a9SColin Riley         const size_t argc = command.GetArgumentCount();
26125ec532a9SColin Riley         if (argc == 0)
26135ec532a9SColin Riley         {
26145ec532a9SColin Riley             Target *target = m_exe_ctx.GetTargetPtr();
26155ec532a9SColin Riley             RenderScriptRuntime *runtime =
26165ec532a9SColin Riley                 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
26175ec532a9SColin Riley             auto module_list = target->GetImages();
26185ec532a9SColin Riley             bool new_rs_details = runtime->ProbeModules(module_list);
26195ec532a9SColin Riley             if (new_rs_details)
26205ec532a9SColin Riley             {
26215ec532a9SColin Riley                 result.AppendMessage("New renderscript modules added to runtime model.");
26225ec532a9SColin Riley             }
26235ec532a9SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
26245ec532a9SColin Riley             return true;
26255ec532a9SColin Riley         }
26265ec532a9SColin Riley 
26275ec532a9SColin Riley         result.AppendErrorWithFormat("'%s' takes no arguments", m_cmd_name.c_str());
26285ec532a9SColin Riley         result.SetStatus(eReturnStatusFailed);
26295ec532a9SColin Riley         return false;
26305ec532a9SColin Riley     }
26315ec532a9SColin Riley };
26325ec532a9SColin Riley 
26335ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed
26345ec532a9SColin Riley {
26355ec532a9SColin Riley   private:
26365ec532a9SColin Riley   public:
26375ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
26385ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module dump",
26395ec532a9SColin Riley                               "Dumps renderscript specific information for all modules.", "renderscript module dump",
2640e87764f2SEnrico Granata                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
26415ec532a9SColin Riley     {
26425ec532a9SColin Riley     }
26435ec532a9SColin Riley 
26445ec532a9SColin Riley     ~CommandObjectRenderScriptRuntimeModuleDump() {}
26455ec532a9SColin Riley 
26465ec532a9SColin Riley     bool
26475ec532a9SColin Riley     DoExecute(Args &command, CommandReturnObject &result)
26485ec532a9SColin Riley     {
26495ec532a9SColin Riley         RenderScriptRuntime *runtime =
26505ec532a9SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
26515ec532a9SColin Riley         runtime->DumpModules(result.GetOutputStream());
26525ec532a9SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
26535ec532a9SColin Riley         return true;
26545ec532a9SColin Riley     }
26555ec532a9SColin Riley };
26565ec532a9SColin Riley 
26575ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword
26585ec532a9SColin Riley {
26595ec532a9SColin Riley   private:
26605ec532a9SColin Riley   public:
26615ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
26625ec532a9SColin Riley         : CommandObjectMultiword(interpreter, "renderscript module", "Commands that deal with renderscript modules.",
26635ec532a9SColin Riley                                  NULL)
26645ec532a9SColin Riley     {
26655ec532a9SColin Riley         LoadSubCommand("probe", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleProbe(interpreter)));
26665ec532a9SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(interpreter)));
26675ec532a9SColin Riley     }
26685ec532a9SColin Riley 
26695ec532a9SColin Riley     ~CommandObjectRenderScriptRuntimeModule() {}
26705ec532a9SColin Riley };
26715ec532a9SColin Riley 
26724640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed
26734640cde1SColin Riley {
26744640cde1SColin Riley   private:
26754640cde1SColin Riley   public:
26764640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
26774640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript kernel list",
26784640cde1SColin Riley                               "Lists renderscript kernel names and associated script resources.", "renderscript kernel list",
26794640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
26804640cde1SColin Riley     {
26814640cde1SColin Riley     }
26824640cde1SColin Riley 
26834640cde1SColin Riley     ~CommandObjectRenderScriptRuntimeKernelList() {}
26844640cde1SColin Riley 
26854640cde1SColin Riley     bool
26864640cde1SColin Riley     DoExecute(Args &command, CommandReturnObject &result)
26874640cde1SColin Riley     {
26884640cde1SColin Riley         RenderScriptRuntime *runtime =
26894640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
26904640cde1SColin Riley         runtime->DumpKernels(result.GetOutputStream());
26914640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
26924640cde1SColin Riley         return true;
26934640cde1SColin Riley     }
26944640cde1SColin Riley };
26954640cde1SColin Riley 
26967dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointSet : public CommandObjectParsed
26974640cde1SColin Riley {
26984640cde1SColin Riley   private:
26994640cde1SColin Riley   public:
27007dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointSet(CommandInterpreter &interpreter)
27017dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint set",
2702*018f5a7eSEwan Crawford                               "Sets a breakpoint on a renderscript kernel.", "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
2703*018f5a7eSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), m_options(interpreter)
27044640cde1SColin Riley     {
27054640cde1SColin Riley     }
27064640cde1SColin Riley 
2707*018f5a7eSEwan Crawford     virtual Options*
2708*018f5a7eSEwan Crawford     GetOptions()
2709*018f5a7eSEwan Crawford     {
2710*018f5a7eSEwan Crawford         return &m_options;
2711*018f5a7eSEwan Crawford     }
2712*018f5a7eSEwan Crawford 
2713*018f5a7eSEwan Crawford     class CommandOptions : public Options
2714*018f5a7eSEwan Crawford     {
2715*018f5a7eSEwan Crawford       public:
2716*018f5a7eSEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter)
2717*018f5a7eSEwan Crawford         {
2718*018f5a7eSEwan Crawford         }
2719*018f5a7eSEwan Crawford 
2720*018f5a7eSEwan Crawford         virtual
2721*018f5a7eSEwan Crawford         ~CommandOptions()
2722*018f5a7eSEwan Crawford         {
2723*018f5a7eSEwan Crawford         }
2724*018f5a7eSEwan Crawford 
2725*018f5a7eSEwan Crawford         virtual Error
2726*018f5a7eSEwan Crawford         SetOptionValue(uint32_t option_idx, const char *option_arg)
2727*018f5a7eSEwan Crawford         {
2728*018f5a7eSEwan Crawford             Error error;
2729*018f5a7eSEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
2730*018f5a7eSEwan Crawford 
2731*018f5a7eSEwan Crawford             switch (short_option)
2732*018f5a7eSEwan Crawford             {
2733*018f5a7eSEwan Crawford                 case 'c':
2734*018f5a7eSEwan Crawford                     if (!ParseCoordinate(option_arg))
2735*018f5a7eSEwan Crawford                         error.SetErrorStringWithFormat("Couldn't parse coordinate '%s', should be in format 'x,y,z'.", option_arg);
2736*018f5a7eSEwan Crawford                     break;
2737*018f5a7eSEwan Crawford                 default:
2738*018f5a7eSEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
2739*018f5a7eSEwan Crawford                     break;
2740*018f5a7eSEwan Crawford             }
2741*018f5a7eSEwan Crawford             return error;
2742*018f5a7eSEwan Crawford         }
2743*018f5a7eSEwan Crawford 
2744*018f5a7eSEwan Crawford         // -c takes an argument of the form 'num[,num][,num]'.
2745*018f5a7eSEwan Crawford         // Where 'id_cstr' is this argument with the whitespace trimmed.
2746*018f5a7eSEwan Crawford         // Missing coordinates are defaulted to zero.
2747*018f5a7eSEwan Crawford         bool
2748*018f5a7eSEwan Crawford         ParseCoordinate(const char* id_cstr)
2749*018f5a7eSEwan Crawford         {
2750*018f5a7eSEwan Crawford             RegularExpression regex;
2751*018f5a7eSEwan Crawford             RegularExpression::Match regex_match(3);
2752*018f5a7eSEwan Crawford 
2753*018f5a7eSEwan Crawford             bool matched = false;
2754*018f5a7eSEwan Crawford             if(regex.Compile("^([0-9]+),([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
2755*018f5a7eSEwan Crawford                 matched = true;
2756*018f5a7eSEwan Crawford             else if(regex.Compile("^([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
2757*018f5a7eSEwan Crawford                 matched = true;
2758*018f5a7eSEwan Crawford             else if(regex.Compile("^([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
2759*018f5a7eSEwan Crawford                 matched = true;
2760*018f5a7eSEwan Crawford             for(uint32_t i = 0; i < 3; i++)
2761*018f5a7eSEwan Crawford             {
2762*018f5a7eSEwan Crawford                 std::string group;
2763*018f5a7eSEwan Crawford                 if(regex_match.GetMatchAtIndex(id_cstr, i + 1, group))
2764*018f5a7eSEwan Crawford                     m_coord[i] = (uint32_t)strtoul(group.c_str(), NULL, 0);
2765*018f5a7eSEwan Crawford                 else
2766*018f5a7eSEwan Crawford                     m_coord[i] = 0;
2767*018f5a7eSEwan Crawford             }
2768*018f5a7eSEwan Crawford             return matched;
2769*018f5a7eSEwan Crawford         }
2770*018f5a7eSEwan Crawford 
2771*018f5a7eSEwan Crawford         void
2772*018f5a7eSEwan Crawford         OptionParsingStarting()
2773*018f5a7eSEwan Crawford         {
2774*018f5a7eSEwan Crawford             // -1 means the -c option hasn't been set
2775*018f5a7eSEwan Crawford             m_coord[0] = -1;
2776*018f5a7eSEwan Crawford             m_coord[1] = -1;
2777*018f5a7eSEwan Crawford             m_coord[2] = -1;
2778*018f5a7eSEwan Crawford         }
2779*018f5a7eSEwan Crawford 
2780*018f5a7eSEwan Crawford         const OptionDefinition*
2781*018f5a7eSEwan Crawford         GetDefinitions()
2782*018f5a7eSEwan Crawford         {
2783*018f5a7eSEwan Crawford             return g_option_table;
2784*018f5a7eSEwan Crawford         }
2785*018f5a7eSEwan Crawford 
2786*018f5a7eSEwan Crawford         static OptionDefinition g_option_table[];
2787*018f5a7eSEwan Crawford         std::array<int,3> m_coord;
2788*018f5a7eSEwan Crawford     };
2789*018f5a7eSEwan Crawford 
27907dc7771cSEwan Crawford     ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() {}
27914640cde1SColin Riley 
27924640cde1SColin Riley     bool
27934640cde1SColin Riley     DoExecute(Args &command, CommandReturnObject &result)
27944640cde1SColin Riley     {
27954640cde1SColin Riley         const size_t argc = command.GetArgumentCount();
2796*018f5a7eSEwan Crawford         if (argc < 1)
27974640cde1SColin Riley         {
2798*018f5a7eSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of kernel name, and an optional coordinate.", m_cmd_name.c_str());
2799*018f5a7eSEwan Crawford             result.SetStatus(eReturnStatusFailed);
2800*018f5a7eSEwan Crawford             return false;
2801*018f5a7eSEwan Crawford         }
2802*018f5a7eSEwan Crawford 
28034640cde1SColin Riley         RenderScriptRuntime *runtime =
28044640cde1SColin Riley                 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
28054640cde1SColin Riley 
28064640cde1SColin Riley         Error error;
2807*018f5a7eSEwan Crawford         runtime->PlaceBreakpointOnKernel(result.GetOutputStream(), command.GetArgumentAtIndex(0), m_options.m_coord,
280898156583SEwan Crawford                                          error, m_exe_ctx.GetTargetSP());
28094640cde1SColin Riley 
28104640cde1SColin Riley         if (error.Success())
28114640cde1SColin Riley         {
28124640cde1SColin Riley             result.AppendMessage("Breakpoint(s) created");
28134640cde1SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
28144640cde1SColin Riley             return true;
28154640cde1SColin Riley         }
28164640cde1SColin Riley         result.SetStatus(eReturnStatusFailed);
28174640cde1SColin Riley         result.AppendErrorWithFormat("Error: %s", error.AsCString());
28184640cde1SColin Riley         return false;
28194640cde1SColin Riley    }
28204640cde1SColin Riley 
2821*018f5a7eSEwan Crawford     private:
2822*018f5a7eSEwan Crawford         CommandOptions m_options;
28234640cde1SColin Riley };
28244640cde1SColin Riley 
2825*018f5a7eSEwan Crawford OptionDefinition
2826*018f5a7eSEwan Crawford CommandObjectRenderScriptRuntimeKernelBreakpointSet::CommandOptions::g_option_table[] =
2827*018f5a7eSEwan Crawford {
2828*018f5a7eSEwan Crawford     { LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeValue,
2829*018f5a7eSEwan Crawford       "Set a breakpoint on a single invocation of the kernel with specified coordinate.\n"
2830*018f5a7eSEwan Crawford       "Coordinate takes the form 'x[,y][,z] where x,y,z are positive integers representing kernel dimensions. "
2831*018f5a7eSEwan Crawford       "Any unset dimensions will be defaulted to zero."},
2832*018f5a7eSEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
2833*018f5a7eSEwan Crawford };
2834*018f5a7eSEwan Crawford 
2835*018f5a7eSEwan Crawford 
28367dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointAll : public CommandObjectParsed
28377dc7771cSEwan Crawford {
28387dc7771cSEwan Crawford   private:
28397dc7771cSEwan Crawford   public:
28407dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointAll(CommandInterpreter &interpreter)
28417dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint all",
28427dc7771cSEwan Crawford                               "Automatically sets a breakpoint on all renderscript kernels that are or will be loaded.\n"
28437dc7771cSEwan Crawford                               "Disabling option means breakpoints will no longer be set on any kernels loaded in the future, "
28447dc7771cSEwan Crawford                               "but does not remove currently set breakpoints.",
28457dc7771cSEwan Crawford                               "renderscript kernel breakpoint all <enable/disable>",
28467dc7771cSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
28477dc7771cSEwan Crawford     {
28487dc7771cSEwan Crawford     }
28497dc7771cSEwan Crawford 
28507dc7771cSEwan Crawford     ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() {}
28517dc7771cSEwan Crawford 
28527dc7771cSEwan Crawford     bool
28537dc7771cSEwan Crawford     DoExecute(Args &command, CommandReturnObject &result)
28547dc7771cSEwan Crawford     {
28557dc7771cSEwan Crawford         const size_t argc = command.GetArgumentCount();
28567dc7771cSEwan Crawford         if (argc != 1)
28577dc7771cSEwan Crawford         {
28587dc7771cSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
28597dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
28607dc7771cSEwan Crawford             return false;
28617dc7771cSEwan Crawford         }
28627dc7771cSEwan Crawford 
28637dc7771cSEwan Crawford         RenderScriptRuntime *runtime =
28647dc7771cSEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
28657dc7771cSEwan Crawford 
28667dc7771cSEwan Crawford         bool do_break = false;
28677dc7771cSEwan Crawford         const char* argument = command.GetArgumentAtIndex(0);
28687dc7771cSEwan Crawford         if (strcmp(argument, "enable") == 0)
28697dc7771cSEwan Crawford         {
28707dc7771cSEwan Crawford             do_break = true;
28717dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will be set on all kernels.");
28727dc7771cSEwan Crawford         }
28737dc7771cSEwan Crawford         else if (strcmp(argument, "disable") == 0)
28747dc7771cSEwan Crawford         {
28757dc7771cSEwan Crawford             do_break = false;
28767dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will not be set on any new kernels.");
28777dc7771cSEwan Crawford         }
28787dc7771cSEwan Crawford         else
28797dc7771cSEwan Crawford         {
28807dc7771cSEwan Crawford             result.AppendErrorWithFormat("Argument must be either 'enable' or 'disable'");
28817dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
28827dc7771cSEwan Crawford             return false;
28837dc7771cSEwan Crawford         }
28847dc7771cSEwan Crawford 
28857dc7771cSEwan Crawford         runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
28867dc7771cSEwan Crawford 
28877dc7771cSEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
28887dc7771cSEwan Crawford         return true;
28897dc7771cSEwan Crawford     }
28907dc7771cSEwan Crawford };
28917dc7771cSEwan Crawford 
28927dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpoint : public CommandObjectMultiword
28937dc7771cSEwan Crawford {
28947dc7771cSEwan Crawford   private:
28957dc7771cSEwan Crawford   public:
28967dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpoint(CommandInterpreter &interpreter)
28977dc7771cSEwan Crawford         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that generate breakpoints on renderscript kernels.",
28987dc7771cSEwan Crawford                                  nullptr)
28997dc7771cSEwan Crawford     {
29007dc7771cSEwan Crawford         LoadSubCommand("set", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(interpreter)));
29017dc7771cSEwan Crawford         LoadSubCommand("all", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(interpreter)));
29027dc7771cSEwan Crawford     }
29037dc7771cSEwan Crawford 
29047dc7771cSEwan Crawford     ~CommandObjectRenderScriptRuntimeKernelBreakpoint() {}
29057dc7771cSEwan Crawford };
29067dc7771cSEwan Crawford 
29074640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword
29084640cde1SColin Riley {
29094640cde1SColin Riley   private:
29104640cde1SColin Riley   public:
29114640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
29124640cde1SColin Riley         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that deal with renderscript kernels.",
29134640cde1SColin Riley                                  NULL)
29144640cde1SColin Riley     {
29154640cde1SColin Riley         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(interpreter)));
29164640cde1SColin Riley         LoadSubCommand("breakpoint", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
29174640cde1SColin Riley     }
29184640cde1SColin Riley 
29194640cde1SColin Riley     ~CommandObjectRenderScriptRuntimeKernel() {}
29204640cde1SColin Riley };
29214640cde1SColin Riley 
29224640cde1SColin Riley class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed
29234640cde1SColin Riley {
29244640cde1SColin Riley   private:
29254640cde1SColin Riley   public:
29264640cde1SColin Riley     CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
29274640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript context dump",
29284640cde1SColin Riley                               "Dumps renderscript context information.", "renderscript context dump",
29294640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
29304640cde1SColin Riley     {
29314640cde1SColin Riley     }
29324640cde1SColin Riley 
29334640cde1SColin Riley     ~CommandObjectRenderScriptRuntimeContextDump() {}
29344640cde1SColin Riley 
29354640cde1SColin Riley     bool
29364640cde1SColin Riley     DoExecute(Args &command, CommandReturnObject &result)
29374640cde1SColin Riley     {
29384640cde1SColin Riley         RenderScriptRuntime *runtime =
29394640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
29404640cde1SColin Riley         runtime->DumpContexts(result.GetOutputStream());
29414640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
29424640cde1SColin Riley         return true;
29434640cde1SColin Riley     }
29444640cde1SColin Riley };
29454640cde1SColin Riley 
29464640cde1SColin Riley class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword
29474640cde1SColin Riley {
29484640cde1SColin Riley   private:
29494640cde1SColin Riley   public:
29504640cde1SColin Riley     CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
29514640cde1SColin Riley         : CommandObjectMultiword(interpreter, "renderscript context", "Commands that deal with renderscript contexts.",
29524640cde1SColin Riley                                  NULL)
29534640cde1SColin Riley     {
29544640cde1SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(interpreter)));
29554640cde1SColin Riley     }
29564640cde1SColin Riley 
29574640cde1SColin Riley     ~CommandObjectRenderScriptRuntimeContext() {}
29584640cde1SColin Riley };
29594640cde1SColin Riley 
2960a0f08674SEwan Crawford 
2961a0f08674SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationDump : public CommandObjectParsed
2962a0f08674SEwan Crawford {
2963a0f08674SEwan Crawford   private:
2964a0f08674SEwan Crawford   public:
2965a0f08674SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationDump(CommandInterpreter &interpreter)
2966a0f08674SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation dump",
2967a0f08674SEwan Crawford                               "Displays the contents of a particular allocation", "renderscript allocation dump <ID>",
2968a0f08674SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter)
2969a0f08674SEwan Crawford     {
2970a0f08674SEwan Crawford     }
2971a0f08674SEwan Crawford 
2972a0f08674SEwan Crawford     virtual Options*
2973a0f08674SEwan Crawford     GetOptions()
2974a0f08674SEwan Crawford     {
2975a0f08674SEwan Crawford         return &m_options;
2976a0f08674SEwan Crawford     }
2977a0f08674SEwan Crawford 
2978a0f08674SEwan Crawford     class CommandOptions : public Options
2979a0f08674SEwan Crawford     {
2980a0f08674SEwan Crawford       public:
2981a0f08674SEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter)
2982a0f08674SEwan Crawford         {
2983a0f08674SEwan Crawford         }
2984a0f08674SEwan Crawford 
2985a0f08674SEwan Crawford         virtual
2986a0f08674SEwan Crawford         ~CommandOptions()
2987a0f08674SEwan Crawford         {
2988a0f08674SEwan Crawford         }
2989a0f08674SEwan Crawford 
2990a0f08674SEwan Crawford         virtual Error
2991a0f08674SEwan Crawford         SetOptionValue(uint32_t option_idx, const char *option_arg)
2992a0f08674SEwan Crawford         {
2993a0f08674SEwan Crawford             Error error;
2994a0f08674SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
2995a0f08674SEwan Crawford 
2996a0f08674SEwan Crawford             switch (short_option)
2997a0f08674SEwan Crawford             {
2998a0f08674SEwan Crawford                 case 'f':
2999a0f08674SEwan Crawford                     m_outfile.SetFile(option_arg, true);
3000a0f08674SEwan Crawford                     if (m_outfile.Exists())
3001a0f08674SEwan Crawford                     {
3002a0f08674SEwan Crawford                         m_outfile.Clear();
3003a0f08674SEwan Crawford                         error.SetErrorStringWithFormat("file already exists: '%s'", option_arg);
3004a0f08674SEwan Crawford                     }
3005a0f08674SEwan Crawford                     break;
3006a0f08674SEwan Crawford                 default:
3007a0f08674SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3008a0f08674SEwan Crawford                     break;
3009a0f08674SEwan Crawford             }
3010a0f08674SEwan Crawford             return error;
3011a0f08674SEwan Crawford         }
3012a0f08674SEwan Crawford 
3013a0f08674SEwan Crawford         void
3014a0f08674SEwan Crawford         OptionParsingStarting()
3015a0f08674SEwan Crawford         {
3016a0f08674SEwan Crawford             m_outfile.Clear();
3017a0f08674SEwan Crawford         }
3018a0f08674SEwan Crawford 
3019a0f08674SEwan Crawford         const OptionDefinition*
3020a0f08674SEwan Crawford         GetDefinitions()
3021a0f08674SEwan Crawford         {
3022a0f08674SEwan Crawford             return g_option_table;
3023a0f08674SEwan Crawford         }
3024a0f08674SEwan Crawford 
3025a0f08674SEwan Crawford         static OptionDefinition g_option_table[];
3026a0f08674SEwan Crawford         FileSpec m_outfile;
3027a0f08674SEwan Crawford     };
3028a0f08674SEwan Crawford 
3029a0f08674SEwan Crawford     ~CommandObjectRenderScriptRuntimeAllocationDump() {}
3030a0f08674SEwan Crawford 
3031a0f08674SEwan Crawford     bool
3032a0f08674SEwan Crawford     DoExecute(Args &command, CommandReturnObject &result)
3033a0f08674SEwan Crawford     {
3034a0f08674SEwan Crawford         const size_t argc = command.GetArgumentCount();
3035a0f08674SEwan Crawford         if (argc < 1)
3036a0f08674SEwan Crawford         {
3037a0f08674SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. As well as an optional -f argument",
3038a0f08674SEwan Crawford                                          m_cmd_name.c_str());
3039a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3040a0f08674SEwan Crawford             return false;
3041a0f08674SEwan Crawford         }
3042a0f08674SEwan Crawford 
3043a0f08674SEwan Crawford         RenderScriptRuntime *runtime =
3044a0f08674SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
3045a0f08674SEwan Crawford 
3046a0f08674SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
3047a0f08674SEwan Crawford         bool convert_complete = false;
3048a0f08674SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
3049a0f08674SEwan Crawford         if (!convert_complete)
3050a0f08674SEwan Crawford         {
3051a0f08674SEwan Crawford             result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
3052a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3053a0f08674SEwan Crawford             return false;
3054a0f08674SEwan Crawford         }
3055a0f08674SEwan Crawford 
3056a0f08674SEwan Crawford         Stream* output_strm = nullptr;
3057a0f08674SEwan Crawford         StreamFile outfile_stream;
3058a0f08674SEwan Crawford         const FileSpec &outfile_spec = m_options.m_outfile; // Dump allocation to file instead
3059a0f08674SEwan Crawford         if (outfile_spec)
3060a0f08674SEwan Crawford         {
3061a0f08674SEwan Crawford             // Open output file
3062a0f08674SEwan Crawford             char path[256];
3063a0f08674SEwan Crawford             outfile_spec.GetPath(path, sizeof(path));
3064a0f08674SEwan Crawford             if (outfile_stream.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate).Success())
3065a0f08674SEwan Crawford             {
3066a0f08674SEwan Crawford                 output_strm = &outfile_stream;
3067a0f08674SEwan Crawford                 result.GetOutputStream().Printf("Results written to '%s'", path);
3068a0f08674SEwan Crawford                 result.GetOutputStream().EOL();
3069a0f08674SEwan Crawford             }
3070a0f08674SEwan Crawford             else
3071a0f08674SEwan Crawford             {
3072a0f08674SEwan Crawford                 result.AppendErrorWithFormat("Couldn't open file '%s'", path);
3073a0f08674SEwan Crawford                 result.SetStatus(eReturnStatusFailed);
3074a0f08674SEwan Crawford                 return false;
3075a0f08674SEwan Crawford             }
3076a0f08674SEwan Crawford         }
3077a0f08674SEwan Crawford         else
3078a0f08674SEwan Crawford             output_strm = &result.GetOutputStream();
3079a0f08674SEwan Crawford 
3080a0f08674SEwan Crawford         assert(output_strm != nullptr);
3081a0f08674SEwan Crawford         bool success = runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
3082a0f08674SEwan Crawford 
3083a0f08674SEwan Crawford         if (success)
3084a0f08674SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
3085a0f08674SEwan Crawford         else
3086a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3087a0f08674SEwan Crawford 
3088a0f08674SEwan Crawford         return true;
3089a0f08674SEwan Crawford     }
3090a0f08674SEwan Crawford 
3091a0f08674SEwan Crawford     private:
3092a0f08674SEwan Crawford         CommandOptions m_options;
3093a0f08674SEwan Crawford };
3094a0f08674SEwan Crawford 
3095a0f08674SEwan Crawford OptionDefinition
3096a0f08674SEwan Crawford CommandObjectRenderScriptRuntimeAllocationDump::CommandOptions::g_option_table[] =
3097a0f08674SEwan Crawford {
3098a0f08674SEwan Crawford     { LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename,
3099a0f08674SEwan Crawford       "Print results to specified file instead of command line."},
3100a0f08674SEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
3101a0f08674SEwan Crawford };
3102a0f08674SEwan Crawford 
3103a0f08674SEwan Crawford 
310415f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationList : public CommandObjectParsed
310515f2bd95SEwan Crawford {
310615f2bd95SEwan Crawford   public:
310715f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationList(CommandInterpreter &interpreter)
310815f2bd95SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation list",
310915f2bd95SEwan Crawford                               "List renderscript allocations and their information.", "renderscript allocation list",
311015f2bd95SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter)
311115f2bd95SEwan Crawford     {
311215f2bd95SEwan Crawford     }
311315f2bd95SEwan Crawford 
311415f2bd95SEwan Crawford     virtual Options*
311515f2bd95SEwan Crawford     GetOptions()
311615f2bd95SEwan Crawford     {
311715f2bd95SEwan Crawford         return &m_options;
311815f2bd95SEwan Crawford     }
311915f2bd95SEwan Crawford 
312015f2bd95SEwan Crawford     class CommandOptions : public Options
312115f2bd95SEwan Crawford     {
312215f2bd95SEwan Crawford       public:
312315f2bd95SEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter), m_refresh(false)
312415f2bd95SEwan Crawford         {
312515f2bd95SEwan Crawford         }
312615f2bd95SEwan Crawford 
312715f2bd95SEwan Crawford         virtual
312815f2bd95SEwan Crawford         ~CommandOptions()
312915f2bd95SEwan Crawford         {
313015f2bd95SEwan Crawford         }
313115f2bd95SEwan Crawford 
313215f2bd95SEwan Crawford         virtual Error
313315f2bd95SEwan Crawford         SetOptionValue(uint32_t option_idx, const char *option_arg)
313415f2bd95SEwan Crawford         {
313515f2bd95SEwan Crawford             Error error;
313615f2bd95SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
313715f2bd95SEwan Crawford 
313815f2bd95SEwan Crawford             switch (short_option)
313915f2bd95SEwan Crawford             {
314015f2bd95SEwan Crawford                 case 'r':
314115f2bd95SEwan Crawford                     m_refresh = true;
314215f2bd95SEwan Crawford                     break;
314315f2bd95SEwan Crawford                 default:
314415f2bd95SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
314515f2bd95SEwan Crawford                     break;
314615f2bd95SEwan Crawford             }
314715f2bd95SEwan Crawford             return error;
314815f2bd95SEwan Crawford         }
314915f2bd95SEwan Crawford 
315015f2bd95SEwan Crawford         void
315115f2bd95SEwan Crawford         OptionParsingStarting()
315215f2bd95SEwan Crawford         {
315315f2bd95SEwan Crawford             m_refresh = false;
315415f2bd95SEwan Crawford         }
315515f2bd95SEwan Crawford 
315615f2bd95SEwan Crawford         const OptionDefinition*
315715f2bd95SEwan Crawford         GetDefinitions()
315815f2bd95SEwan Crawford         {
315915f2bd95SEwan Crawford             return g_option_table;
316015f2bd95SEwan Crawford         }
316115f2bd95SEwan Crawford 
316215f2bd95SEwan Crawford         static OptionDefinition g_option_table[];
316315f2bd95SEwan Crawford         bool m_refresh;
316415f2bd95SEwan Crawford     };
316515f2bd95SEwan Crawford 
316615f2bd95SEwan Crawford     ~CommandObjectRenderScriptRuntimeAllocationList() {}
316715f2bd95SEwan Crawford 
316815f2bd95SEwan Crawford     bool
316915f2bd95SEwan Crawford     DoExecute(Args &command, CommandReturnObject &result)
317015f2bd95SEwan Crawford     {
317115f2bd95SEwan Crawford         RenderScriptRuntime *runtime =
317215f2bd95SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
317315f2bd95SEwan Crawford         runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(), m_options.m_refresh);
317415f2bd95SEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
317515f2bd95SEwan Crawford         return true;
317615f2bd95SEwan Crawford     }
317715f2bd95SEwan Crawford 
317815f2bd95SEwan Crawford   private:
317915f2bd95SEwan Crawford     CommandOptions m_options;
318015f2bd95SEwan Crawford };
318115f2bd95SEwan Crawford 
318215f2bd95SEwan Crawford OptionDefinition
318315f2bd95SEwan Crawford CommandObjectRenderScriptRuntimeAllocationList::CommandOptions::g_option_table[] =
318415f2bd95SEwan Crawford {
318515f2bd95SEwan Crawford     { LLDB_OPT_SET_1, false, "refresh", 'r', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone,
318615f2bd95SEwan Crawford       "Recompute allocation details."},
318715f2bd95SEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
318815f2bd95SEwan Crawford };
318915f2bd95SEwan Crawford 
319015f2bd95SEwan Crawford 
319155232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationLoad : public CommandObjectParsed
319255232f09SEwan Crawford {
319355232f09SEwan Crawford   private:
319455232f09SEwan Crawford   public:
319555232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationLoad(CommandInterpreter &interpreter)
319655232f09SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation load",
319755232f09SEwan Crawford                               "Loads renderscript allocation contents from a file.", "renderscript allocation load <ID> <filename>",
319855232f09SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
319955232f09SEwan Crawford     {
320055232f09SEwan Crawford     }
320155232f09SEwan Crawford 
320255232f09SEwan Crawford     ~CommandObjectRenderScriptRuntimeAllocationLoad() {}
320355232f09SEwan Crawford 
320455232f09SEwan Crawford     bool
320555232f09SEwan Crawford     DoExecute(Args &command, CommandReturnObject &result)
320655232f09SEwan Crawford     {
320755232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
320855232f09SEwan Crawford         if (argc != 2)
320955232f09SEwan Crawford         {
321055232f09SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str());
321155232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
321255232f09SEwan Crawford             return false;
321355232f09SEwan Crawford         }
321455232f09SEwan Crawford 
321555232f09SEwan Crawford         RenderScriptRuntime *runtime =
321655232f09SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
321755232f09SEwan Crawford 
321855232f09SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
321955232f09SEwan Crawford         bool convert_complete = false;
322055232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
322155232f09SEwan Crawford         if (!convert_complete)
322255232f09SEwan Crawford         {
322355232f09SEwan Crawford             result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr);
322455232f09SEwan Crawford             result.SetStatus (eReturnStatusFailed);
322555232f09SEwan Crawford             return false;
322655232f09SEwan Crawford         }
322755232f09SEwan Crawford 
322855232f09SEwan Crawford         const char* filename = command.GetArgumentAtIndex(1);
322955232f09SEwan Crawford         bool success = runtime->LoadAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
323055232f09SEwan Crawford 
323155232f09SEwan Crawford         if (success)
323255232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
323355232f09SEwan Crawford         else
323455232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
323555232f09SEwan Crawford 
323655232f09SEwan Crawford         return true;
323755232f09SEwan Crawford     }
323855232f09SEwan Crawford };
323955232f09SEwan Crawford 
324055232f09SEwan Crawford 
324155232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationSave : public CommandObjectParsed
324255232f09SEwan Crawford {
324355232f09SEwan Crawford   private:
324455232f09SEwan Crawford   public:
324555232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationSave(CommandInterpreter &interpreter)
324655232f09SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation save",
324755232f09SEwan Crawford                               "Write renderscript allocation contents to a file.", "renderscript allocation save <ID> <filename>",
324855232f09SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
324955232f09SEwan Crawford     {
325055232f09SEwan Crawford     }
325155232f09SEwan Crawford 
325255232f09SEwan Crawford     ~CommandObjectRenderScriptRuntimeAllocationSave() {}
325355232f09SEwan Crawford 
325455232f09SEwan Crawford     bool
325555232f09SEwan Crawford     DoExecute(Args &command, CommandReturnObject &result)
325655232f09SEwan Crawford     {
325755232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
325855232f09SEwan Crawford         if (argc != 2)
325955232f09SEwan Crawford         {
326055232f09SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str());
326155232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
326255232f09SEwan Crawford             return false;
326355232f09SEwan Crawford         }
326455232f09SEwan Crawford 
326555232f09SEwan Crawford         RenderScriptRuntime *runtime =
326655232f09SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
326755232f09SEwan Crawford 
326855232f09SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
326955232f09SEwan Crawford         bool convert_complete = false;
327055232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
327155232f09SEwan Crawford         if (!convert_complete)
327255232f09SEwan Crawford         {
327355232f09SEwan Crawford             result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr);
327455232f09SEwan Crawford             result.SetStatus (eReturnStatusFailed);
327555232f09SEwan Crawford             return false;
327655232f09SEwan Crawford         }
327755232f09SEwan Crawford 
327855232f09SEwan Crawford         const char* filename = command.GetArgumentAtIndex(1);
327955232f09SEwan Crawford         bool success = runtime->SaveAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
328055232f09SEwan Crawford 
328155232f09SEwan Crawford         if (success)
328255232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
328355232f09SEwan Crawford         else
328455232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
328555232f09SEwan Crawford 
328655232f09SEwan Crawford         return true;
328755232f09SEwan Crawford     }
328855232f09SEwan Crawford };
328955232f09SEwan Crawford 
329015f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocation : public CommandObjectMultiword
329115f2bd95SEwan Crawford {
329215f2bd95SEwan Crawford   private:
329315f2bd95SEwan Crawford   public:
329415f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
329515f2bd95SEwan Crawford         : CommandObjectMultiword(interpreter, "renderscript allocation", "Commands that deal with renderscript allocations.",
329615f2bd95SEwan Crawford                                  NULL)
329715f2bd95SEwan Crawford     {
329815f2bd95SEwan Crawford         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
3299a0f08674SEwan Crawford         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
330055232f09SEwan Crawford         LoadSubCommand("save", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
330155232f09SEwan Crawford         LoadSubCommand("load", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
330215f2bd95SEwan Crawford     }
330315f2bd95SEwan Crawford 
330415f2bd95SEwan Crawford     ~CommandObjectRenderScriptRuntimeAllocation() {}
330515f2bd95SEwan Crawford };
330615f2bd95SEwan Crawford 
330715f2bd95SEwan Crawford 
33084640cde1SColin Riley class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed
33094640cde1SColin Riley {
33104640cde1SColin Riley   private:
33114640cde1SColin Riley   public:
33124640cde1SColin Riley     CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
33134640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript status",
33144640cde1SColin Riley                               "Displays current renderscript runtime status.", "renderscript status",
33154640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
33164640cde1SColin Riley     {
33174640cde1SColin Riley     }
33184640cde1SColin Riley 
33194640cde1SColin Riley     ~CommandObjectRenderScriptRuntimeStatus() {}
33204640cde1SColin Riley 
33214640cde1SColin Riley     bool
33224640cde1SColin Riley     DoExecute(Args &command, CommandReturnObject &result)
33234640cde1SColin Riley     {
33244640cde1SColin Riley         RenderScriptRuntime *runtime =
33254640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
33264640cde1SColin Riley         runtime->Status(result.GetOutputStream());
33274640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
33284640cde1SColin Riley         return true;
33294640cde1SColin Riley     }
33304640cde1SColin Riley };
33314640cde1SColin Riley 
33325ec532a9SColin Riley class CommandObjectRenderScriptRuntime : public CommandObjectMultiword
33335ec532a9SColin Riley {
33345ec532a9SColin Riley   public:
33355ec532a9SColin Riley     CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
33365ec532a9SColin Riley         : CommandObjectMultiword(interpreter, "renderscript", "A set of commands for operating on renderscript.",
33375ec532a9SColin Riley                                  "renderscript <subcommand> [<subcommand-options>]")
33385ec532a9SColin Riley     {
33395ec532a9SColin Riley         LoadSubCommand("module", CommandObjectSP(new CommandObjectRenderScriptRuntimeModule(interpreter)));
33404640cde1SColin Riley         LoadSubCommand("status", CommandObjectSP(new CommandObjectRenderScriptRuntimeStatus(interpreter)));
33414640cde1SColin Riley         LoadSubCommand("kernel", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernel(interpreter)));
33424640cde1SColin Riley         LoadSubCommand("context", CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(interpreter)));
334315f2bd95SEwan Crawford         LoadSubCommand("allocation", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
33445ec532a9SColin Riley     }
33455ec532a9SColin Riley 
33465ec532a9SColin Riley     ~CommandObjectRenderScriptRuntime() {}
33475ec532a9SColin Riley };
3348ef20b08fSColin Riley 
3349ef20b08fSColin Riley void
3350ef20b08fSColin Riley RenderScriptRuntime::Initiate()
33515ec532a9SColin Riley {
3352ef20b08fSColin Riley     assert(!m_initiated);
33535ec532a9SColin Riley }
3354ef20b08fSColin Riley 
3355ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
33567dc7771cSEwan Crawford     : lldb_private::CPPLanguageRuntime(process), m_initiated(false), m_debuggerPresentFlagged(false),
33577dc7771cSEwan Crawford       m_breakAllKernels(false)
3358ef20b08fSColin Riley {
33594640cde1SColin Riley     ModulesDidLoad(process->GetTarget().GetImages());
3360ef20b08fSColin Riley }
33614640cde1SColin Riley 
33624640cde1SColin Riley lldb::CommandObjectSP
33634640cde1SColin Riley RenderScriptRuntime::GetCommandObject(lldb_private::CommandInterpreter& interpreter)
33644640cde1SColin Riley {
33654640cde1SColin Riley     static CommandObjectSP command_object;
33664640cde1SColin Riley     if(!command_object)
33674640cde1SColin Riley     {
33684640cde1SColin Riley         command_object.reset(new CommandObjectRenderScriptRuntime(interpreter));
33694640cde1SColin Riley     }
33704640cde1SColin Riley     return command_object;
33714640cde1SColin Riley }
33724640cde1SColin Riley 
337378f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
3374