15ec532a9SColin Riley //===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===//
25ec532a9SColin Riley //
35ec532a9SColin Riley //                     The LLVM Compiler Infrastructure
45ec532a9SColin Riley //
55ec532a9SColin Riley // This file is distributed under the University of Illinois Open Source
65ec532a9SColin Riley // License. See LICENSE.TXT for details.
75ec532a9SColin Riley //
85ec532a9SColin Riley //===----------------------------------------------------------------------===//
95ec532a9SColin Riley 
10222b937cSEugene Zelenko // C Includes
11222b937cSEugene Zelenko // C++ Includes
12222b937cSEugene Zelenko // Other libraries and framework includes
13222b937cSEugene Zelenko // Project includes
145ec532a9SColin Riley #include "RenderScriptRuntime.h"
155ec532a9SColin Riley 
165ec532a9SColin Riley #include "lldb/Core/ConstString.h"
175ec532a9SColin Riley #include "lldb/Core/Debugger.h"
185ec532a9SColin Riley #include "lldb/Core/Error.h"
195ec532a9SColin Riley #include "lldb/Core/Log.h"
205ec532a9SColin Riley #include "lldb/Core/PluginManager.h"
21*8b244e21SEwan Crawford #include "lldb/Core/ValueObjectVariable.h"
22018f5a7eSEwan Crawford #include "lldb/Core/RegularExpression.h"
23*8b244e21SEwan Crawford #include "lldb/DataFormatters/DumpValueObjectOptions.h"
24a0f08674SEwan Crawford #include "lldb/Host/StringConvert.h"
255ec532a9SColin Riley #include "lldb/Symbol/Symbol.h"
264640cde1SColin Riley #include "lldb/Symbol/Type.h"
275ec532a9SColin Riley #include "lldb/Target/Process.h"
285ec532a9SColin Riley #include "lldb/Target/Target.h"
29018f5a7eSEwan Crawford #include "lldb/Target/Thread.h"
305ec532a9SColin Riley #include "lldb/Interpreter/Args.h"
315ec532a9SColin Riley #include "lldb/Interpreter/Options.h"
325ec532a9SColin Riley #include "lldb/Interpreter/CommandInterpreter.h"
335ec532a9SColin Riley #include "lldb/Interpreter/CommandReturnObject.h"
345ec532a9SColin Riley #include "lldb/Interpreter/CommandObjectMultiword.h"
354640cde1SColin Riley #include "lldb/Breakpoint/StoppointCallbackContext.h"
364640cde1SColin Riley #include "lldb/Target/RegisterContext.h"
3715f2bd95SEwan Crawford #include "lldb/Expression/UserExpression.h"
384640cde1SColin Riley #include "lldb/Symbol/VariableList.h"
395ec532a9SColin Riley 
405ec532a9SColin Riley using namespace lldb;
415ec532a9SColin Riley using namespace lldb_private;
4298156583SEwan Crawford using namespace lldb_renderscript;
435ec532a9SColin Riley 
4478f339d1SEwan Crawford namespace {
4578f339d1SEwan Crawford 
4678f339d1SEwan Crawford // The empirical_type adds a basic level of validation to arbitrary data
4778f339d1SEwan Crawford // allowing us to track if data has been discovered and stored or not.
4878f339d1SEwan Crawford // An empirical_type will be marked as valid only if it has been explicitly assigned to.
4978f339d1SEwan Crawford template <typename type_t>
5078f339d1SEwan Crawford class empirical_type
5178f339d1SEwan Crawford {
5278f339d1SEwan Crawford public:
5378f339d1SEwan Crawford     // Ctor. Contents is invalid when constructed.
5478f339d1SEwan Crawford     empirical_type()
5578f339d1SEwan Crawford         : valid(false)
5678f339d1SEwan Crawford     {}
5778f339d1SEwan Crawford 
5878f339d1SEwan Crawford     // Return true and copy contents to out if valid, else return false.
5978f339d1SEwan Crawford     bool get(type_t& out) const
6078f339d1SEwan Crawford     {
6178f339d1SEwan Crawford         if (valid)
6278f339d1SEwan Crawford             out = data;
6378f339d1SEwan Crawford         return valid;
6478f339d1SEwan Crawford     }
6578f339d1SEwan Crawford 
6678f339d1SEwan Crawford     // Return a pointer to the contents or nullptr if it was not valid.
6778f339d1SEwan Crawford     const type_t* get() const
6878f339d1SEwan Crawford     {
6978f339d1SEwan Crawford         return valid ? &data : nullptr;
7078f339d1SEwan Crawford     }
7178f339d1SEwan Crawford 
7278f339d1SEwan Crawford     // Assign data explicitly.
7378f339d1SEwan Crawford     void set(const type_t in)
7478f339d1SEwan Crawford     {
7578f339d1SEwan Crawford         data = in;
7678f339d1SEwan Crawford         valid = true;
7778f339d1SEwan Crawford     }
7878f339d1SEwan Crawford 
7978f339d1SEwan Crawford     // Mark contents as invalid.
8078f339d1SEwan Crawford     void invalidate()
8178f339d1SEwan Crawford     {
8278f339d1SEwan Crawford         valid = false;
8378f339d1SEwan Crawford     }
8478f339d1SEwan Crawford 
8578f339d1SEwan Crawford     // Returns true if this type contains valid data.
8678f339d1SEwan Crawford     bool isValid() const
8778f339d1SEwan Crawford     {
8878f339d1SEwan Crawford         return valid;
8978f339d1SEwan Crawford     }
9078f339d1SEwan Crawford 
9178f339d1SEwan Crawford     // Assignment operator.
9278f339d1SEwan Crawford     empirical_type<type_t>& operator = (const type_t in)
9378f339d1SEwan Crawford     {
9478f339d1SEwan Crawford         set(in);
9578f339d1SEwan Crawford         return *this;
9678f339d1SEwan Crawford     }
9778f339d1SEwan Crawford 
9878f339d1SEwan Crawford     // Dereference operator returns contents.
9978f339d1SEwan Crawford     // Warning: Will assert if not valid so use only when you know data is valid.
10078f339d1SEwan Crawford     const type_t& operator * () const
10178f339d1SEwan Crawford     {
10278f339d1SEwan Crawford         assert(valid);
10378f339d1SEwan Crawford         return data;
10478f339d1SEwan Crawford     }
10578f339d1SEwan Crawford 
10678f339d1SEwan Crawford protected:
10778f339d1SEwan Crawford     bool valid;
10878f339d1SEwan Crawford     type_t data;
10978f339d1SEwan Crawford };
11078f339d1SEwan Crawford 
111222b937cSEugene Zelenko } // anonymous namespace
11278f339d1SEwan Crawford 
11378f339d1SEwan Crawford // The ScriptDetails class collects data associated with a single script instance.
11478f339d1SEwan Crawford struct RenderScriptRuntime::ScriptDetails
11578f339d1SEwan Crawford {
116222b937cSEugene Zelenko     ~ScriptDetails() = default;
11778f339d1SEwan Crawford 
11878f339d1SEwan Crawford     enum ScriptType
11978f339d1SEwan Crawford     {
12078f339d1SEwan Crawford         eScript,
12178f339d1SEwan Crawford         eScriptC
12278f339d1SEwan Crawford     };
12378f339d1SEwan Crawford 
12478f339d1SEwan Crawford     // The derived type of the script.
12578f339d1SEwan Crawford     empirical_type<ScriptType> type;
12678f339d1SEwan Crawford     // The name of the original source file.
12778f339d1SEwan Crawford     empirical_type<std::string> resName;
12878f339d1SEwan Crawford     // Path to script .so file on the device.
12978f339d1SEwan Crawford     empirical_type<std::string> scriptDyLib;
13078f339d1SEwan Crawford     // Directory where kernel objects are cached on device.
13178f339d1SEwan Crawford     empirical_type<std::string> cacheDir;
13278f339d1SEwan Crawford     // Pointer to the context which owns this script.
13378f339d1SEwan Crawford     empirical_type<lldb::addr_t> context;
13478f339d1SEwan Crawford     // Pointer to the script object itself.
13578f339d1SEwan Crawford     empirical_type<lldb::addr_t> script;
13678f339d1SEwan Crawford };
13778f339d1SEwan Crawford 
138*8b244e21SEwan Crawford // This Element class represents the Element object in RS,
139*8b244e21SEwan Crawford // defining the type associated with an Allocation.
140*8b244e21SEwan Crawford struct RenderScriptRuntime::Element
14178f339d1SEwan Crawford {
14215f2bd95SEwan Crawford     // Taken from rsDefines.h
14315f2bd95SEwan Crawford     enum DataKind
14415f2bd95SEwan Crawford     {
14515f2bd95SEwan Crawford         RS_KIND_USER,
14615f2bd95SEwan Crawford         RS_KIND_PIXEL_L = 7,
14715f2bd95SEwan Crawford         RS_KIND_PIXEL_A,
14815f2bd95SEwan Crawford         RS_KIND_PIXEL_LA,
14915f2bd95SEwan Crawford         RS_KIND_PIXEL_RGB,
15015f2bd95SEwan Crawford         RS_KIND_PIXEL_RGBA,
15115f2bd95SEwan Crawford         RS_KIND_PIXEL_DEPTH,
15215f2bd95SEwan Crawford         RS_KIND_PIXEL_YUV,
15315f2bd95SEwan Crawford         RS_KIND_INVALID = 100
15415f2bd95SEwan Crawford     };
15578f339d1SEwan Crawford 
15615f2bd95SEwan Crawford     // Taken from rsDefines.h
15778f339d1SEwan Crawford     enum DataType
15878f339d1SEwan Crawford     {
15915f2bd95SEwan Crawford         RS_TYPE_NONE = 0,
16015f2bd95SEwan Crawford         RS_TYPE_FLOAT_16,
16115f2bd95SEwan Crawford         RS_TYPE_FLOAT_32,
16215f2bd95SEwan Crawford         RS_TYPE_FLOAT_64,
16315f2bd95SEwan Crawford         RS_TYPE_SIGNED_8,
16415f2bd95SEwan Crawford         RS_TYPE_SIGNED_16,
16515f2bd95SEwan Crawford         RS_TYPE_SIGNED_32,
16615f2bd95SEwan Crawford         RS_TYPE_SIGNED_64,
16715f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_8,
16815f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_16,
16915f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_32,
17015f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_64,
17115f2bd95SEwan Crawford         RS_TYPE_BOOLEAN
17278f339d1SEwan Crawford     };
17378f339d1SEwan Crawford 
174*8b244e21SEwan Crawford     std::vector<Element> children;                       // Child Element fields for structs
175*8b244e21SEwan Crawford     empirical_type<lldb::addr_t> element_ptr;            // Pointer to the RS Element of the Type
176*8b244e21SEwan Crawford     empirical_type<DataType> type;                       // Type of each data pointer stored by the allocation
177*8b244e21SEwan Crawford     empirical_type<DataKind> type_kind;                  // Defines pixel type if Allocation is created from an image
178*8b244e21SEwan Crawford     empirical_type<uint32_t> type_vec_size;              // Vector size of each data point, e.g '4' for uchar4
179*8b244e21SEwan Crawford     empirical_type<uint32_t> field_count;                // Number of Subelements
180*8b244e21SEwan Crawford     empirical_type<uint32_t> datum_size;                 // Size of a single Element with padding
181*8b244e21SEwan Crawford     empirical_type<uint32_t> padding;                    // Number of padding bytes
182*8b244e21SEwan Crawford     empirical_type<uint32_t> array_size;                 // Number of items in array, only needed for strucrs
183*8b244e21SEwan Crawford     ConstString type_name;                               // Name of type, only needed for structs
184*8b244e21SEwan Crawford 
185*8b244e21SEwan Crawford     static const ConstString FallbackStructName;         // Print this as the type name of a struct Element
186*8b244e21SEwan Crawford                                                          // If we can't resolve the actual struct name
187*8b244e21SEwan Crawford };
188*8b244e21SEwan Crawford 
189*8b244e21SEwan Crawford // This AllocationDetails class collects data associated with a single
190*8b244e21SEwan Crawford // allocation instance.
191*8b244e21SEwan Crawford struct RenderScriptRuntime::AllocationDetails
192*8b244e21SEwan Crawford {
19315f2bd95SEwan Crawford     struct Dimension
19478f339d1SEwan Crawford     {
19515f2bd95SEwan Crawford         uint32_t dim_1;
19615f2bd95SEwan Crawford         uint32_t dim_2;
19715f2bd95SEwan Crawford         uint32_t dim_3;
19815f2bd95SEwan Crawford         uint32_t cubeMap;
19915f2bd95SEwan Crawford 
20015f2bd95SEwan Crawford         Dimension()
20115f2bd95SEwan Crawford         {
20215f2bd95SEwan Crawford              dim_1 = 0;
20315f2bd95SEwan Crawford              dim_2 = 0;
20415f2bd95SEwan Crawford              dim_3 = 0;
20515f2bd95SEwan Crawford              cubeMap = 0;
20615f2bd95SEwan Crawford         }
20778f339d1SEwan Crawford     };
20878f339d1SEwan Crawford 
20955232f09SEwan Crawford     // Header for reading and writing allocation contents
21055232f09SEwan Crawford     // to a binary file.
21155232f09SEwan Crawford     struct FileHeader
21255232f09SEwan Crawford     {
21355232f09SEwan Crawford         uint8_t ident[4];      // ASCII 'RSAD' identifying the file
21455232f09SEwan Crawford         uint16_t hdr_size;     // Header size in bytes, for backwards compatability
21555232f09SEwan Crawford         uint16_t type;         // DataType enum
21655232f09SEwan Crawford         uint32_t kind;         // DataKind enum
21755232f09SEwan Crawford         uint32_t dims[3];      // Dimensions
21855232f09SEwan Crawford         uint32_t element_size; // Size of a single element, including padding
21955232f09SEwan Crawford     };
22055232f09SEwan Crawford 
22115f2bd95SEwan Crawford     // Monotonically increasing from 1
22215f2bd95SEwan Crawford     static unsigned int ID;
22315f2bd95SEwan Crawford 
22415f2bd95SEwan Crawford     // Maps Allocation DataType enum and vector size to printable strings
22515f2bd95SEwan Crawford     // using mapping from RenderScript numerical types summary documentation
22615f2bd95SEwan Crawford     static const char* RsDataTypeToString[][4];
22715f2bd95SEwan Crawford 
22815f2bd95SEwan Crawford     // Maps Allocation DataKind enum to printable strings
22915f2bd95SEwan Crawford     static const char* RsDataKindToString[];
23015f2bd95SEwan Crawford 
231a0f08674SEwan Crawford     // Maps allocation types to format sizes for printing.
232a0f08674SEwan Crawford     static const unsigned int RSTypeToFormat[][3];
233a0f08674SEwan Crawford 
23415f2bd95SEwan Crawford     // Give each allocation an ID as a way
23515f2bd95SEwan Crawford     // for commands to reference it.
23615f2bd95SEwan Crawford     const unsigned int id;
23715f2bd95SEwan Crawford 
238*8b244e21SEwan Crawford     RenderScriptRuntime::Element element;     // Allocation Element type
23915f2bd95SEwan Crawford     empirical_type<Dimension> dimension;      // Dimensions of the Allocation
24015f2bd95SEwan Crawford     empirical_type<lldb::addr_t> address;     // Pointer to address of the RS Allocation
24115f2bd95SEwan Crawford     empirical_type<lldb::addr_t> data_ptr;    // Pointer to the data held by the Allocation
24215f2bd95SEwan Crawford     empirical_type<lldb::addr_t> type_ptr;    // Pointer to the RS Type of the Allocation
24315f2bd95SEwan Crawford     empirical_type<lldb::addr_t> context;     // Pointer to the RS Context of the Allocation
244a0f08674SEwan Crawford     empirical_type<uint32_t> size;            // Size of the allocation
245a0f08674SEwan Crawford     empirical_type<uint32_t> stride;          // Stride between rows of the allocation
24615f2bd95SEwan Crawford 
24715f2bd95SEwan Crawford     // Give each allocation an id, so we can reference it in user commands.
24815f2bd95SEwan Crawford     AllocationDetails(): id(ID++)
24915f2bd95SEwan Crawford     {
25015f2bd95SEwan Crawford     }
25115f2bd95SEwan Crawford };
25215f2bd95SEwan Crawford 
253*8b244e21SEwan Crawford const ConstString RenderScriptRuntime::Element::FallbackStructName("struct");
254*8b244e21SEwan Crawford 
25515f2bd95SEwan Crawford unsigned int RenderScriptRuntime::AllocationDetails::ID = 1;
25615f2bd95SEwan Crawford 
25715f2bd95SEwan Crawford const char* RenderScriptRuntime::AllocationDetails::RsDataKindToString[] =
25815f2bd95SEwan Crawford {
25915f2bd95SEwan Crawford    "User",
26015f2bd95SEwan Crawford    "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7
26115f2bd95SEwan Crawford    "Undefined", "Undefined", "Undefined",
26215f2bd95SEwan Crawford    "L Pixel",
26315f2bd95SEwan Crawford    "A Pixel",
26415f2bd95SEwan Crawford    "LA Pixel",
26515f2bd95SEwan Crawford    "RGB Pixel",
26615f2bd95SEwan Crawford    "RGBA Pixel",
26715f2bd95SEwan Crawford    "Pixel Depth",
26815f2bd95SEwan Crawford    "YUV Pixel"
26915f2bd95SEwan Crawford };
27015f2bd95SEwan Crawford 
27115f2bd95SEwan Crawford const char* RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] =
27215f2bd95SEwan Crawford {
27315f2bd95SEwan Crawford     {"None", "None", "None", "None"},
27415f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
27515f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
27615f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
27715f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
27815f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
27915f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
28015f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
28115f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
28215f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
28315f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
28415f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
28515f2bd95SEwan Crawford     {"bool", "bool2", "bool3", "bool4"}
28678f339d1SEwan Crawford };
28778f339d1SEwan Crawford 
288a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
289a0f08674SEwan Crawford enum TypeToFormatIndex {
290a0f08674SEwan Crawford    eFormatSingle = 0,
291a0f08674SEwan Crawford    eFormatVector,
292a0f08674SEwan Crawford    eElementSize
293a0f08674SEwan Crawford };
294a0f08674SEwan Crawford 
295a0f08674SEwan Crawford // { format enum of single element, format enum of element vector, size of element}
296a0f08674SEwan Crawford const unsigned int RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] =
297a0f08674SEwan Crawford {
298a0f08674SEwan Crawford     {eFormatHex, eFormatHex, 1}, // RS_TYPE_NONE
299a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat16, 2}, // RS_TYPE_FLOAT_16
300a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)}, // RS_TYPE_FLOAT_32
301a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)}, // RS_TYPE_FLOAT_64
302a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)}, // RS_TYPE_SIGNED_8
303a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)}, // RS_TYPE_SIGNED_16
304a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)}, // RS_TYPE_SIGNED_32
305a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)}, // RS_TYPE_SIGNED_64
306a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)}, // RS_TYPE_UNSIGNED_8
307a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_16
308a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)}, // RS_TYPE_UNSIGNED_32
309a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)}, // RS_TYPE_UNSIGNED_64
310a0f08674SEwan Crawford     {eFormatBoolean, eFormatBoolean, sizeof(bool)} // RS_TYPE_BOOL
311a0f08674SEwan Crawford };
312a0f08674SEwan Crawford 
3135ec532a9SColin Riley //------------------------------------------------------------------
3145ec532a9SColin Riley // Static Functions
3155ec532a9SColin Riley //------------------------------------------------------------------
3165ec532a9SColin Riley LanguageRuntime *
3175ec532a9SColin Riley RenderScriptRuntime::CreateInstance(Process *process, lldb::LanguageType language)
3185ec532a9SColin Riley {
3195ec532a9SColin Riley 
3205ec532a9SColin Riley     if (language == eLanguageTypeExtRenderScript)
3215ec532a9SColin Riley         return new RenderScriptRuntime(process);
3225ec532a9SColin Riley     else
3235ec532a9SColin Riley         return NULL;
3245ec532a9SColin Riley }
3255ec532a9SColin Riley 
32698156583SEwan Crawford // Callback with a module to search for matching symbols.
32798156583SEwan Crawford // We first check that the module contains RS kernels.
32898156583SEwan Crawford // Then look for a symbol which matches our kernel name.
32998156583SEwan Crawford // The breakpoint address is finally set using the address of this symbol.
33098156583SEwan Crawford Searcher::CallbackReturn
33198156583SEwan Crawford RSBreakpointResolver::SearchCallback(SearchFilter &filter,
33298156583SEwan Crawford                                      SymbolContext &context,
33398156583SEwan Crawford                                      Address*,
33498156583SEwan Crawford                                      bool)
33598156583SEwan Crawford {
33698156583SEwan Crawford     ModuleSP module = context.module_sp;
33798156583SEwan Crawford 
33898156583SEwan Crawford     if (!module)
33998156583SEwan Crawford         return Searcher::eCallbackReturnContinue;
34098156583SEwan Crawford 
34198156583SEwan Crawford     // Is this a module containing renderscript kernels?
34298156583SEwan Crawford     if (nullptr == module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData))
34398156583SEwan Crawford         return Searcher::eCallbackReturnContinue;
34498156583SEwan Crawford 
34598156583SEwan Crawford     // Attempt to set a breakpoint on the kernel name symbol within the module library.
34698156583SEwan Crawford     // If it's not found, it's likely debug info is unavailable - try to set a
34798156583SEwan Crawford     // breakpoint on <name>.expand.
34898156583SEwan Crawford 
34998156583SEwan Crawford     const Symbol* kernel_sym = module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
35098156583SEwan Crawford     if (!kernel_sym)
35198156583SEwan Crawford     {
35298156583SEwan Crawford         std::string kernel_name_expanded(m_kernel_name.AsCString());
35398156583SEwan Crawford         kernel_name_expanded.append(".expand");
35498156583SEwan Crawford         kernel_sym = module->FindFirstSymbolWithNameAndType(ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
35598156583SEwan Crawford     }
35698156583SEwan Crawford 
35798156583SEwan Crawford     if (kernel_sym)
35898156583SEwan Crawford     {
35998156583SEwan Crawford         Address bp_addr = kernel_sym->GetAddress();
36098156583SEwan Crawford         if (filter.AddressPasses(bp_addr))
36198156583SEwan Crawford             m_breakpoint->AddLocation(bp_addr);
36298156583SEwan Crawford     }
36398156583SEwan Crawford 
36498156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
36598156583SEwan Crawford }
36698156583SEwan Crawford 
3675ec532a9SColin Riley void
3685ec532a9SColin Riley RenderScriptRuntime::Initialize()
3695ec532a9SColin Riley {
3704640cde1SColin Riley     PluginManager::RegisterPlugin(GetPluginNameStatic(), "RenderScript language support", CreateInstance, GetCommandObject);
3715ec532a9SColin Riley }
3725ec532a9SColin Riley 
3735ec532a9SColin Riley void
3745ec532a9SColin Riley RenderScriptRuntime::Terminate()
3755ec532a9SColin Riley {
3765ec532a9SColin Riley     PluginManager::UnregisterPlugin(CreateInstance);
3775ec532a9SColin Riley }
3785ec532a9SColin Riley 
3795ec532a9SColin Riley lldb_private::ConstString
3805ec532a9SColin Riley RenderScriptRuntime::GetPluginNameStatic()
3815ec532a9SColin Riley {
3825ec532a9SColin Riley     static ConstString g_name("renderscript");
3835ec532a9SColin Riley     return g_name;
3845ec532a9SColin Riley }
3855ec532a9SColin Riley 
386ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
387ef20b08fSColin Riley RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp)
388ef20b08fSColin Riley {
389ef20b08fSColin Riley     if (module_sp)
390ef20b08fSColin Riley     {
391ef20b08fSColin Riley         // Is this a module containing renderscript kernels?
392ef20b08fSColin Riley         const Symbol *info_sym = module_sp->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
393ef20b08fSColin Riley         if (info_sym)
394ef20b08fSColin Riley         {
395ef20b08fSColin Riley             return eModuleKindKernelObj;
396ef20b08fSColin Riley         }
3974640cde1SColin Riley 
3984640cde1SColin Riley         // Is this the main RS runtime library
3994640cde1SColin Riley         const ConstString rs_lib("libRS.so");
4004640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_lib)
4014640cde1SColin Riley         {
4024640cde1SColin Riley             return eModuleKindLibRS;
4034640cde1SColin Riley         }
4044640cde1SColin Riley 
4054640cde1SColin Riley         const ConstString rs_driverlib("libRSDriver.so");
4064640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_driverlib)
4074640cde1SColin Riley         {
4084640cde1SColin Riley             return eModuleKindDriver;
4094640cde1SColin Riley         }
4104640cde1SColin Riley 
41115f2bd95SEwan Crawford         const ConstString rs_cpureflib("libRSCpuRef.so");
4124640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib)
4134640cde1SColin Riley         {
4144640cde1SColin Riley             return eModuleKindImpl;
4154640cde1SColin Riley         }
4164640cde1SColin Riley 
417ef20b08fSColin Riley     }
418ef20b08fSColin Riley     return eModuleKindIgnored;
419ef20b08fSColin Riley }
420ef20b08fSColin Riley 
421ef20b08fSColin Riley bool
422ef20b08fSColin Riley RenderScriptRuntime::IsRenderScriptModule(const lldb::ModuleSP &module_sp)
423ef20b08fSColin Riley {
424ef20b08fSColin Riley     return GetModuleKind(module_sp) != eModuleKindIgnored;
425ef20b08fSColin Riley }
426ef20b08fSColin Riley 
427ef20b08fSColin Riley void
428ef20b08fSColin Riley RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list )
429ef20b08fSColin Riley {
430ef20b08fSColin Riley     Mutex::Locker locker (module_list.GetMutex ());
431ef20b08fSColin Riley 
432ef20b08fSColin Riley     size_t num_modules = module_list.GetSize();
433ef20b08fSColin Riley     for (size_t i = 0; i < num_modules; i++)
434ef20b08fSColin Riley     {
435ef20b08fSColin Riley         auto mod = module_list.GetModuleAtIndex (i);
436ef20b08fSColin Riley         if (IsRenderScriptModule (mod))
437ef20b08fSColin Riley         {
438ef20b08fSColin Riley             LoadModule(mod);
439ef20b08fSColin Riley         }
440ef20b08fSColin Riley     }
441ef20b08fSColin Riley }
442ef20b08fSColin Riley 
4435ec532a9SColin Riley //------------------------------------------------------------------
4445ec532a9SColin Riley // PluginInterface protocol
4455ec532a9SColin Riley //------------------------------------------------------------------
4465ec532a9SColin Riley lldb_private::ConstString
4475ec532a9SColin Riley RenderScriptRuntime::GetPluginName()
4485ec532a9SColin Riley {
4495ec532a9SColin Riley     return GetPluginNameStatic();
4505ec532a9SColin Riley }
4515ec532a9SColin Riley 
4525ec532a9SColin Riley uint32_t
4535ec532a9SColin Riley RenderScriptRuntime::GetPluginVersion()
4545ec532a9SColin Riley {
4555ec532a9SColin Riley     return 1;
4565ec532a9SColin Riley }
4575ec532a9SColin Riley 
4585ec532a9SColin Riley bool
4595ec532a9SColin Riley RenderScriptRuntime::IsVTableName(const char *name)
4605ec532a9SColin Riley {
4615ec532a9SColin Riley     return false;
4625ec532a9SColin Riley }
4635ec532a9SColin Riley 
4645ec532a9SColin Riley bool
4655ec532a9SColin Riley RenderScriptRuntime::GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic,
4660b6003f3SEnrico Granata                                               TypeAndOrName &class_type_or_name, Address &address,
4670b6003f3SEnrico Granata                                               Value::ValueType &value_type)
4685ec532a9SColin Riley {
4695ec532a9SColin Riley     return false;
4705ec532a9SColin Riley }
4715ec532a9SColin Riley 
472c74275bcSEnrico Granata TypeAndOrName
473c74275bcSEnrico Granata RenderScriptRuntime::FixUpDynamicType (const TypeAndOrName& type_and_or_name,
4747eed4877SEnrico Granata                                        ValueObject& static_value)
475c74275bcSEnrico Granata {
476c74275bcSEnrico Granata     return type_and_or_name;
477c74275bcSEnrico Granata }
478c74275bcSEnrico Granata 
4795ec532a9SColin Riley bool
4805ec532a9SColin Riley RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value)
4815ec532a9SColin Riley {
4825ec532a9SColin Riley     return false;
4835ec532a9SColin Riley }
4845ec532a9SColin Riley 
4855ec532a9SColin Riley lldb::BreakpointResolverSP
4865ec532a9SColin Riley RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp, bool throw_bp)
4875ec532a9SColin Riley {
4885ec532a9SColin Riley     BreakpointResolverSP resolver_sp;
4895ec532a9SColin Riley     return resolver_sp;
4905ec532a9SColin Riley }
4915ec532a9SColin Riley 
4924640cde1SColin Riley const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
4934640cde1SColin Riley {
4944640cde1SColin Riley     //rsdScript
49582780287SAidan Dodds     {
49682780287SAidan Dodds         "rsdScriptInit", //name
49782780287SAidan Dodds         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhjj", // symbol name 32 bit
49882780287SAidan Dodds         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhmj", // symbol name 64 bit
49982780287SAidan Dodds         0, // version
50082780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
50182780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureScriptInit1 // handler
50282780287SAidan Dodds     },
50382780287SAidan Dodds     {
50482780287SAidan Dodds         "rsdScriptInvokeForEach", // name
50582780287SAidan Dodds         "_Z22rsdScriptInvokeForEachPKN7android12renderscript7ContextEPNS0_6ScriptEjPKNS0_10AllocationEPS6_PKvjPK12RsScriptCall", // symbol name 32bit
50682780287SAidan Dodds         "_Z22rsdScriptInvokeForEachPKN7android12renderscript7ContextEPNS0_6ScriptEjPKNS0_10AllocationEPS6_PKvmPK12RsScriptCall", // symbol name 64bit
50782780287SAidan Dodds         0, // version
50882780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
50982780287SAidan Dodds         nullptr // handler
51082780287SAidan Dodds     },
51182780287SAidan Dodds     {
51282780287SAidan Dodds         "rsdScriptInvokeForEachMulti", // name
51382780287SAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall", // symbol name 32bit
51482780287SAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall", // symbol name 64bit
51582780287SAidan Dodds         0, // version
51682780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
51782780287SAidan Dodds         nullptr // handler
51882780287SAidan Dodds     },
51982780287SAidan Dodds     {
52082780287SAidan Dodds         "rsdScriptInvokeFunction", // name
52182780287SAidan Dodds         "_Z23rsdScriptInvokeFunctionPKN7android12renderscript7ContextEPNS0_6ScriptEjPKvj", // symbol name 32bit
52282780287SAidan Dodds         "_Z23rsdScriptInvokeFunctionPKN7android12renderscript7ContextEPNS0_6ScriptEjPKvm", // symbol name 64bit
52382780287SAidan Dodds         0, // version
52482780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
52582780287SAidan Dodds         nullptr // handler
52682780287SAidan Dodds     },
52782780287SAidan Dodds     {
52882780287SAidan Dodds         "rsdScriptSetGlobalVar", // name
52982780287SAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvj", // symbol name 32bit
53082780287SAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvm", // symbol name 64bit
53182780287SAidan Dodds         0, // version
53282780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
53382780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar1 // handler
53482780287SAidan Dodds     },
5354640cde1SColin Riley 
5364640cde1SColin Riley     //rsdAllocation
53782780287SAidan Dodds     {
53882780287SAidan Dodds         "rsdAllocationInit", // name
53982780287SAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 32bit
54082780287SAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 64bit
54182780287SAidan Dodds         0, // version
54282780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
54382780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureAllocationInit1 // handler
54482780287SAidan Dodds     },
54582780287SAidan Dodds     {
54682780287SAidan Dodds         "rsdAllocationRead2D", //name
54782780287SAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvjj", // symbol name 32bit
54882780287SAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvmm", // symbol name 64bit
54982780287SAidan Dodds         0, // version
55082780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
55182780287SAidan Dodds         nullptr // handler
55282780287SAidan Dodds     },
5534640cde1SColin Riley };
5544640cde1SColin Riley 
555222b937cSEugene Zelenko const size_t RenderScriptRuntime::s_runtimeHookCount = sizeof(s_runtimeHookDefns)/sizeof(s_runtimeHookDefns[0]);
5564640cde1SColin Riley 
5574640cde1SColin Riley bool
5584640cde1SColin Riley RenderScriptRuntime::HookCallback(void *baton, StoppointCallbackContext *ctx, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
5594640cde1SColin Riley {
5604640cde1SColin Riley     RuntimeHook* hook_info = (RuntimeHook*)baton;
5614640cde1SColin Riley     ExecutionContext context(ctx->exe_ctx_ref);
5624640cde1SColin Riley 
5634640cde1SColin Riley     RenderScriptRuntime *lang_rt = (RenderScriptRuntime *)context.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
5644640cde1SColin Riley 
5654640cde1SColin Riley     lang_rt->HookCallback(hook_info, context);
5664640cde1SColin Riley 
5674640cde1SColin Riley     return false;
5684640cde1SColin Riley }
5694640cde1SColin Riley 
5704640cde1SColin Riley void
5714640cde1SColin Riley RenderScriptRuntime::HookCallback(RuntimeHook* hook_info, ExecutionContext& context)
5724640cde1SColin Riley {
5734640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
5744640cde1SColin Riley 
5754640cde1SColin Riley     if (log)
5764640cde1SColin Riley         log->Printf ("RenderScriptRuntime::HookCallback - '%s' .", hook_info->defn->name);
5774640cde1SColin Riley 
5784640cde1SColin Riley     if (hook_info->defn->grabber)
5794640cde1SColin Riley     {
5804640cde1SColin Riley         (this->*(hook_info->defn->grabber))(hook_info, context);
5814640cde1SColin Riley     }
5824640cde1SColin Riley }
5834640cde1SColin Riley 
5844640cde1SColin Riley bool
58582780287SAidan Dodds RenderScriptRuntime::GetArgSimple(ExecutionContext &context, uint32_t arg, uint64_t *data)
5864640cde1SColin Riley {
5874640cde1SColin Riley     if (!data)
5884640cde1SColin Riley         return false;
5894640cde1SColin Riley 
59082780287SAidan Dodds     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
5914640cde1SColin Riley     Error error;
5924640cde1SColin Riley     RegisterContext* reg_ctx = context.GetRegisterContext();
5934640cde1SColin Riley     Process* process = context.GetProcessPtr();
59482780287SAidan Dodds     bool success = false; // return value
5954640cde1SColin Riley 
59682780287SAidan Dodds     if (!context.GetTargetPtr())
59782780287SAidan Dodds     {
59882780287SAidan Dodds         if (log)
59982780287SAidan Dodds             log->Printf("RenderScriptRuntime::GetArgSimple - Invalid target");
60082780287SAidan Dodds 
60182780287SAidan Dodds         return false;
60282780287SAidan Dodds     }
60382780287SAidan Dodds 
60482780287SAidan Dodds     switch (context.GetTargetPtr()->GetArchitecture().GetMachine())
60582780287SAidan Dodds     {
60682780287SAidan Dodds         case llvm::Triple::ArchType::x86:
6074640cde1SColin Riley         {
6084640cde1SColin Riley             uint64_t sp = reg_ctx->GetSP();
6094640cde1SColin Riley             uint32_t offset = (1 + arg) * sizeof(uint32_t);
61082780287SAidan Dodds             uint32_t result = 0;
61182780287SAidan Dodds             process->ReadMemory(sp + offset, &result, sizeof(uint32_t), error);
6124640cde1SColin Riley             if (error.Fail())
6134640cde1SColin Riley             {
6144640cde1SColin Riley                 if (log)
61582780287SAidan Dodds                     log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading X86 stack: %s.", error.AsCString());
6164640cde1SColin Riley             }
61782780287SAidan Dodds             else
6184640cde1SColin Riley             {
61982780287SAidan Dodds                 *data = result;
62082780287SAidan Dodds                 success = true;
62182780287SAidan Dodds             }
62282780287SAidan Dodds 
62382780287SAidan Dodds             break;
62482780287SAidan Dodds         }
62582780287SAidan Dodds         case llvm::Triple::ArchType::arm:
62682780287SAidan Dodds         {
62782780287SAidan Dodds             // arm 32 bit
6284640cde1SColin Riley             if (arg < 4)
6294640cde1SColin Riley             {
6304640cde1SColin Riley                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg);
6314640cde1SColin Riley                 RegisterValue rVal;
63202f1c5d1SEwan Crawford                 success = reg_ctx->ReadRegister(rArg, rVal);
63302f1c5d1SEwan Crawford                 if (success)
63402f1c5d1SEwan Crawford                 {
6354640cde1SColin Riley                     (*data) = rVal.GetAsUInt32();
63602f1c5d1SEwan Crawford                 }
63702f1c5d1SEwan Crawford                 else
63802f1c5d1SEwan Crawford                 {
63902f1c5d1SEwan Crawford                     if (log)
64002f1c5d1SEwan Crawford                         log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading ARM register: %d.", arg);
64102f1c5d1SEwan Crawford                 }
6424640cde1SColin Riley             }
6434640cde1SColin Riley             else
6444640cde1SColin Riley             {
6454640cde1SColin Riley                 uint64_t sp = reg_ctx->GetSP();
6464640cde1SColin Riley                 uint32_t offset = (arg-4) * sizeof(uint32_t);
6474640cde1SColin Riley                 process->ReadMemory(sp + offset, &data, sizeof(uint32_t), error);
6484640cde1SColin Riley                 if (error.Fail())
6494640cde1SColin Riley                 {
6504640cde1SColin Riley                     if (log)
65182780287SAidan Dodds                         log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading ARM stack: %s.", error.AsCString());
65282780287SAidan Dodds                 }
65382780287SAidan Dodds                 else
65482780287SAidan Dodds                 {
65582780287SAidan Dodds                     success = true;
6564640cde1SColin Riley                 }
6574640cde1SColin Riley             }
65882780287SAidan Dodds 
65982780287SAidan Dodds             break;
6604640cde1SColin Riley         }
66182780287SAidan Dodds         case llvm::Triple::ArchType::aarch64:
66282780287SAidan Dodds         {
66382780287SAidan Dodds             // arm 64 bit
66482780287SAidan Dodds             // first 8 arguments are in the registers
66582780287SAidan Dodds             if (arg < 8)
66682780287SAidan Dodds             {
66782780287SAidan Dodds                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg);
66882780287SAidan Dodds                 RegisterValue rVal;
66982780287SAidan Dodds                 success = reg_ctx->ReadRegister(rArg, rVal);
67082780287SAidan Dodds                 if (success)
67182780287SAidan Dodds                 {
67282780287SAidan Dodds                     *data = rVal.GetAsUInt64();
67382780287SAidan Dodds                 }
67482780287SAidan Dodds                 else
67582780287SAidan Dodds                 {
67682780287SAidan Dodds                     if (log)
67782780287SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple() - AARCH64 - Error while reading the argument #%d", arg);
67882780287SAidan Dodds                 }
67982780287SAidan Dodds             }
68082780287SAidan Dodds             else
68182780287SAidan Dodds             {
68282780287SAidan Dodds                 // @TODO: need to find the argument in the stack
68382780287SAidan Dodds                 if (log)
68482780287SAidan Dodds                     log->Printf("RenderScriptRuntime::GetArgSimple - AARCH64 - FOR #ARG >= 8 NOT IMPLEMENTED YET. Argument number: %d", arg);
68582780287SAidan Dodds             }
68682780287SAidan Dodds             break;
68782780287SAidan Dodds         }
68874b396d9SAidan Dodds         case llvm::Triple::ArchType::mipsel:
68974b396d9SAidan Dodds         {
69074b396d9SAidan Dodds 
69174b396d9SAidan Dodds             // read from the registers
69274b396d9SAidan Dodds             if (arg < 4){
69374b396d9SAidan Dodds                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg + 4);
69474b396d9SAidan Dodds                 RegisterValue rVal;
69574b396d9SAidan Dodds                 success = reg_ctx->ReadRegister(rArg, rVal);
69674b396d9SAidan Dodds                 if (success)
69774b396d9SAidan Dodds                 {
69874b396d9SAidan Dodds                     *data = rVal.GetAsUInt64();
69974b396d9SAidan Dodds                 }
70074b396d9SAidan Dodds                 else
70174b396d9SAidan Dodds                 {
70274b396d9SAidan Dodds                     if (log)
70374b396d9SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple() - Mips - Error while reading the argument #%d", arg);
70474b396d9SAidan Dodds                 }
70574b396d9SAidan Dodds 
70674b396d9SAidan Dodds             }
70774b396d9SAidan Dodds 
70874b396d9SAidan Dodds             // read from the stack
70974b396d9SAidan Dodds             else
71074b396d9SAidan Dodds             {
71174b396d9SAidan Dodds                 uint64_t sp = reg_ctx->GetSP();
71274b396d9SAidan Dodds                 uint32_t offset = arg * sizeof(uint32_t);
71374b396d9SAidan Dodds                 process->ReadMemory(sp + offset, &data, sizeof(uint32_t), error);
71474b396d9SAidan Dodds                 if (error.Fail())
71574b396d9SAidan Dodds                 {
71674b396d9SAidan Dodds                     if (log)
71774b396d9SAidan Dodds                         log->Printf ("RenderScriptRuntime::GetArgSimple - error reading Mips stack: %s.", error.AsCString());
71874b396d9SAidan Dodds                 }
71974b396d9SAidan Dodds                 else
72074b396d9SAidan Dodds                 {
72174b396d9SAidan Dodds                     success = true;
72274b396d9SAidan Dodds                 }
72374b396d9SAidan Dodds             }
72474b396d9SAidan Dodds 
72574b396d9SAidan Dodds             break;
72674b396d9SAidan Dodds         }
72702f1c5d1SEwan Crawford         case llvm::Triple::ArchType::mips64el:
72802f1c5d1SEwan Crawford         {
72902f1c5d1SEwan Crawford             // read from the registers
73002f1c5d1SEwan Crawford             if (arg < 8)
73102f1c5d1SEwan Crawford             {
73202f1c5d1SEwan Crawford                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg + 4);
73302f1c5d1SEwan Crawford                 RegisterValue rVal;
73402f1c5d1SEwan Crawford                 success = reg_ctx->ReadRegister(rArg, rVal);
73502f1c5d1SEwan Crawford                 if (success)
73602f1c5d1SEwan Crawford                 {
73702f1c5d1SEwan Crawford                     (*data) = rVal.GetAsUInt64();
73802f1c5d1SEwan Crawford                 }
73902f1c5d1SEwan Crawford                 else
74002f1c5d1SEwan Crawford                 {
74102f1c5d1SEwan Crawford                     if (log)
74202f1c5d1SEwan Crawford                         log->Printf("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading the argument #%d", arg);
74302f1c5d1SEwan Crawford                 }
74402f1c5d1SEwan Crawford             }
74502f1c5d1SEwan Crawford 
74602f1c5d1SEwan Crawford             // read from the stack
74702f1c5d1SEwan Crawford             else
74802f1c5d1SEwan Crawford             {
74902f1c5d1SEwan Crawford                 uint64_t sp = reg_ctx->GetSP();
75002f1c5d1SEwan Crawford                 uint32_t offset = (arg - 8) * sizeof(uint64_t);
75102f1c5d1SEwan Crawford                 process->ReadMemory(sp + offset, &data, sizeof(uint64_t), error);
75202f1c5d1SEwan Crawford                 if (error.Fail())
75302f1c5d1SEwan Crawford                 {
75402f1c5d1SEwan Crawford                     if (log)
75502f1c5d1SEwan Crawford                         log->Printf ("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading Mips64 stack: %s.", error.AsCString());
75602f1c5d1SEwan Crawford                 }
75702f1c5d1SEwan Crawford                 else
75802f1c5d1SEwan Crawford                 {
75902f1c5d1SEwan Crawford                     success = true;
76002f1c5d1SEwan Crawford                 }
76102f1c5d1SEwan Crawford             }
76202f1c5d1SEwan Crawford 
76302f1c5d1SEwan Crawford             break;
76402f1c5d1SEwan Crawford         }
76582780287SAidan Dodds         default:
76682780287SAidan Dodds         {
76782780287SAidan Dodds             // invalid architecture
76882780287SAidan Dodds             if (log)
76982780287SAidan Dodds                 log->Printf("RenderScriptRuntime::GetArgSimple - Architecture not supported");
77082780287SAidan Dodds 
77182780287SAidan Dodds         }
77282780287SAidan Dodds     }
77382780287SAidan Dodds 
77482780287SAidan Dodds     return success;
7754640cde1SColin Riley }
7764640cde1SColin Riley 
7774640cde1SColin Riley void
7784640cde1SColin Riley RenderScriptRuntime::CaptureSetGlobalVar1(RuntimeHook* hook_info, ExecutionContext& context)
7794640cde1SColin Riley {
7804640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
7814640cde1SColin Riley 
7824640cde1SColin Riley     //Context, Script, int, data, length
7834640cde1SColin Riley 
78482780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
78582780287SAidan Dodds     uint64_t rs_script_u64 = 0U;
78682780287SAidan Dodds     uint64_t rs_id_u64 = 0U;
78782780287SAidan Dodds     uint64_t rs_data_u64 = 0U;
78882780287SAidan Dodds     uint64_t rs_length_u64 = 0U;
7894640cde1SColin Riley 
79082780287SAidan Dodds     bool success =
79182780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
79282780287SAidan Dodds         GetArgSimple(context, 1, &rs_script_u64) &&
79382780287SAidan Dodds         GetArgSimple(context, 2, &rs_id_u64) &&
79482780287SAidan Dodds         GetArgSimple(context, 3, &rs_data_u64) &&
79582780287SAidan Dodds         GetArgSimple(context, 4, &rs_length_u64);
7964640cde1SColin Riley 
79782780287SAidan Dodds     if (!success)
79882780287SAidan Dodds     {
79982780287SAidan Dodds         if (log)
80082780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureSetGlobalVar1 - Error while reading the function parameters");
80182780287SAidan Dodds         return;
80282780287SAidan Dodds     }
8034640cde1SColin Riley 
8044640cde1SColin Riley     if (log)
8054640cde1SColin Riley     {
8064640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64 ":%" PRIu64 "bytes.",
80782780287SAidan Dodds                         rs_context_u64, rs_script_u64, rs_id_u64, rs_data_u64, rs_length_u64);
8084640cde1SColin Riley 
80982780287SAidan Dodds         addr_t script_addr =  (addr_t)rs_script_u64;
8104640cde1SColin Riley         if (m_scriptMappings.find( script_addr ) != m_scriptMappings.end())
8114640cde1SColin Riley         {
8124640cde1SColin Riley             auto rsm = m_scriptMappings[script_addr];
81382780287SAidan Dodds             if (rs_id_u64 < rsm->m_globals.size())
8144640cde1SColin Riley             {
81582780287SAidan Dodds                 auto rsg = rsm->m_globals[rs_id_u64];
8164640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - Setting of '%s' within '%s' inferred", rsg.m_name.AsCString(),
8174640cde1SColin Riley                                 rsm->m_module->GetFileSpec().GetFilename().AsCString());
8184640cde1SColin Riley             }
8194640cde1SColin Riley         }
8204640cde1SColin Riley     }
8214640cde1SColin Riley }
8224640cde1SColin Riley 
8234640cde1SColin Riley void
8244640cde1SColin Riley RenderScriptRuntime::CaptureAllocationInit1(RuntimeHook* hook_info, ExecutionContext& context)
8254640cde1SColin Riley {
8264640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
8274640cde1SColin Riley 
8284640cde1SColin Riley     //Context, Alloc, bool
8294640cde1SColin Riley 
83082780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
83182780287SAidan Dodds     uint64_t rs_alloc_u64 = 0U;
83282780287SAidan Dodds     uint64_t rs_forceZero_u64 = 0U;
8334640cde1SColin Riley 
83482780287SAidan Dodds     bool success =
83582780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
83682780287SAidan Dodds         GetArgSimple(context, 1, &rs_alloc_u64) &&
83782780287SAidan Dodds         GetArgSimple(context, 2, &rs_forceZero_u64);
83882780287SAidan Dodds     if (!success) // error case
83982780287SAidan Dodds     {
84082780287SAidan Dodds         if (log)
84182780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureAllocationInit1 - Error while reading the function parameters");
84282780287SAidan Dodds         return; // abort
84382780287SAidan Dodds     }
8444640cde1SColin Riley 
8454640cde1SColin Riley     if (log)
8464640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureAllocationInit1 - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
84782780287SAidan Dodds                         rs_context_u64, rs_alloc_u64, rs_forceZero_u64);
84878f339d1SEwan Crawford 
84978f339d1SEwan Crawford     AllocationDetails* alloc = LookUpAllocation(rs_alloc_u64, true);
85078f339d1SEwan Crawford     if (alloc)
85178f339d1SEwan Crawford         alloc->context = rs_context_u64;
8524640cde1SColin Riley }
8534640cde1SColin Riley 
8544640cde1SColin Riley void
8554640cde1SColin Riley RenderScriptRuntime::CaptureScriptInit1(RuntimeHook* hook_info, ExecutionContext& context)
8564640cde1SColin Riley {
8574640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
8584640cde1SColin Riley 
8594640cde1SColin Riley     //Context, Script, resname Str, cachedir Str
8604640cde1SColin Riley     Error error;
8614640cde1SColin Riley     Process* process = context.GetProcessPtr();
8624640cde1SColin Riley 
86382780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
86482780287SAidan Dodds     uint64_t rs_script_u64 = 0U;
86582780287SAidan Dodds     uint64_t rs_resnameptr_u64 = 0U;
86682780287SAidan Dodds     uint64_t rs_cachedirptr_u64 = 0U;
8674640cde1SColin Riley 
8684640cde1SColin Riley     std::string resname;
8694640cde1SColin Riley     std::string cachedir;
8704640cde1SColin Riley 
87182780287SAidan Dodds     // read the function parameters
87282780287SAidan Dodds     bool success =
87382780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
87482780287SAidan Dodds         GetArgSimple(context, 1, &rs_script_u64) &&
87582780287SAidan Dodds         GetArgSimple(context, 2, &rs_resnameptr_u64) &&
87682780287SAidan Dodds         GetArgSimple(context, 3, &rs_cachedirptr_u64);
8774640cde1SColin Riley 
87882780287SAidan Dodds     if (!success)
87982780287SAidan Dodds     {
88082780287SAidan Dodds         if (log)
88182780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureScriptInit1 - Error while reading the function parameters");
88282780287SAidan Dodds         return;
88382780287SAidan Dodds     }
88482780287SAidan Dodds 
88582780287SAidan Dodds     process->ReadCStringFromMemory((lldb::addr_t)rs_resnameptr_u64, resname, error);
8864640cde1SColin Riley     if (error.Fail())
8874640cde1SColin Riley     {
8884640cde1SColin Riley         if (log)
8894640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading resname: %s.", error.AsCString());
8904640cde1SColin Riley 
8914640cde1SColin Riley     }
8924640cde1SColin Riley 
89382780287SAidan Dodds     process->ReadCStringFromMemory((lldb::addr_t)rs_cachedirptr_u64, cachedir, error);
8944640cde1SColin Riley     if (error.Fail())
8954640cde1SColin Riley     {
8964640cde1SColin Riley         if (log)
8974640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading cachedir: %s.", error.AsCString());
8984640cde1SColin Riley     }
8994640cde1SColin Riley 
9004640cde1SColin Riley     if (log)
9014640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
90282780287SAidan Dodds                      rs_context_u64, rs_script_u64, resname.c_str(), cachedir.c_str());
9034640cde1SColin Riley 
9044640cde1SColin Riley     if (resname.size() > 0)
9054640cde1SColin Riley     {
9064640cde1SColin Riley         StreamString strm;
9074640cde1SColin Riley         strm.Printf("librs.%s.so", resname.c_str());
9084640cde1SColin Riley 
90978f339d1SEwan Crawford         ScriptDetails* script = LookUpScript(rs_script_u64, true);
91078f339d1SEwan Crawford         if (script)
91178f339d1SEwan Crawford         {
91278f339d1SEwan Crawford             script->type = ScriptDetails::eScriptC;
91378f339d1SEwan Crawford             script->cacheDir = cachedir;
91478f339d1SEwan Crawford             script->resName = resname;
91578f339d1SEwan Crawford             script->scriptDyLib = strm.GetData();
91678f339d1SEwan Crawford             script->context = addr_t(rs_context_u64);
91778f339d1SEwan Crawford         }
9184640cde1SColin Riley 
9194640cde1SColin Riley         if (log)
9204640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - '%s' tagged with context 0x%" PRIx64 " and script 0x%" PRIx64 ".",
92182780287SAidan Dodds                          strm.GetData(), rs_context_u64, rs_script_u64);
9224640cde1SColin Riley     }
9234640cde1SColin Riley     else if (log)
9244640cde1SColin Riley     {
9254640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - resource name invalid, Script not tagged");
9264640cde1SColin Riley     }
9274640cde1SColin Riley }
9284640cde1SColin Riley 
9294640cde1SColin Riley void
9304640cde1SColin Riley RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind)
9314640cde1SColin Riley {
9324640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
9334640cde1SColin Riley 
9344640cde1SColin Riley     if (!module)
9354640cde1SColin Riley     {
9364640cde1SColin Riley         return;
9374640cde1SColin Riley     }
9384640cde1SColin Riley 
93982780287SAidan Dodds     Target &target = GetProcess()->GetTarget();
94082780287SAidan Dodds     llvm::Triple::ArchType targetArchType = target.GetArchitecture().GetMachine();
94182780287SAidan Dodds 
94282780287SAidan Dodds     if (targetArchType != llvm::Triple::ArchType::x86
94382780287SAidan Dodds         && targetArchType != llvm::Triple::ArchType::arm
94402f1c5d1SEwan Crawford         && targetArchType != llvm::Triple::ArchType::aarch64
94574b396d9SAidan Dodds         && targetArchType != llvm::Triple::ArchType::mipsel
94602f1c5d1SEwan Crawford         && targetArchType != llvm::Triple::ArchType::mips64el
94702f1c5d1SEwan Crawford     )
9484640cde1SColin Riley     {
9494640cde1SColin Riley         if (log)
95074b396d9SAidan Dodds             log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to hook runtime. Only X86, ARM, Mips supported currently.");
9514640cde1SColin Riley 
9524640cde1SColin Riley         return;
9534640cde1SColin Riley     }
9544640cde1SColin Riley 
95582780287SAidan Dodds     uint32_t archByteSize = target.GetArchitecture().GetAddressByteSize();
9564640cde1SColin Riley 
9574640cde1SColin Riley     for (size_t idx = 0; idx < s_runtimeHookCount; idx++)
9584640cde1SColin Riley     {
9594640cde1SColin Riley         const HookDefn* hook_defn = &s_runtimeHookDefns[idx];
9604640cde1SColin Riley         if (hook_defn->kind != kind) {
9614640cde1SColin Riley             continue;
9624640cde1SColin Riley         }
9634640cde1SColin Riley 
96482780287SAidan Dodds         const char* symbol_name = (archByteSize == 4) ? hook_defn->symbol_name_m32 : hook_defn->symbol_name_m64;
96582780287SAidan Dodds 
96682780287SAidan Dodds         const Symbol *sym = module->FindFirstSymbolWithNameAndType(ConstString(symbol_name), eSymbolTypeCode);
96782780287SAidan Dodds         if (!sym){
96882780287SAidan Dodds             if (log){
96982780287SAidan Dodds                 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - ERROR: Symbol '%s' related to the function %s not found", symbol_name, hook_defn->name);
97082780287SAidan Dodds             }
97182780287SAidan Dodds             continue;
97282780287SAidan Dodds         }
9734640cde1SColin Riley 
974358cf1eaSGreg Clayton         addr_t addr = sym->GetLoadAddress(&target);
9754640cde1SColin Riley         if (addr == LLDB_INVALID_ADDRESS)
9764640cde1SColin Riley         {
9774640cde1SColin Riley             if (log)
9784640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to resolve the address of hook function '%s' with symbol '%s'.",
97982780287SAidan Dodds                              hook_defn->name, symbol_name);
9804640cde1SColin Riley             continue;
9814640cde1SColin Riley         }
98282780287SAidan Dodds         else
98382780287SAidan Dodds         {
98482780287SAidan Dodds             if (log)
98582780287SAidan Dodds                 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - Function %s, address resolved at 0x%" PRIx64, hook_defn->name, addr);
98682780287SAidan Dodds         }
9874640cde1SColin Riley 
9884640cde1SColin Riley         RuntimeHookSP hook(new RuntimeHook());
9894640cde1SColin Riley         hook->address = addr;
9904640cde1SColin Riley         hook->defn = hook_defn;
9914640cde1SColin Riley         hook->bp_sp = target.CreateBreakpoint(addr, true, false);
9924640cde1SColin Riley         hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
9934640cde1SColin Riley         m_runtimeHooks[addr] = hook;
9944640cde1SColin Riley         if (log)
9954640cde1SColin Riley         {
9964640cde1SColin Riley             log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Successfully hooked '%s' in '%s' version %" PRIu64 " at 0x%" PRIx64 ".",
9974640cde1SColin Riley                 hook_defn->name, module->GetFileSpec().GetFilename().AsCString(), (uint64_t)hook_defn->version, (uint64_t)addr);
9984640cde1SColin Riley         }
9994640cde1SColin Riley     }
10004640cde1SColin Riley }
10014640cde1SColin Riley 
10024640cde1SColin Riley void
10034640cde1SColin Riley RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp)
10044640cde1SColin Riley {
10054640cde1SColin Riley     if (!rsmodule_sp)
10064640cde1SColin Riley         return;
10074640cde1SColin Riley 
10084640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
10094640cde1SColin Riley 
10104640cde1SColin Riley     const ModuleSP module = rsmodule_sp->m_module;
10114640cde1SColin Riley     const FileSpec& file = module->GetPlatformFileSpec();
10124640cde1SColin Riley 
101378f339d1SEwan Crawford     // Iterate over all of the scripts that we currently know of.
101478f339d1SEwan Crawford     // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
10154640cde1SColin Riley     for (const auto & rs_script : m_scripts)
10164640cde1SColin Riley     {
101778f339d1SEwan Crawford         // Extract the expected .so file path for this script.
101878f339d1SEwan Crawford         std::string dylib;
101978f339d1SEwan Crawford         if (!rs_script->scriptDyLib.get(dylib))
102078f339d1SEwan Crawford             continue;
102178f339d1SEwan Crawford 
102278f339d1SEwan Crawford         // Only proceed if the module that has loaded corresponds to this script.
102378f339d1SEwan Crawford         if (file.GetFilename() != ConstString(dylib.c_str()))
102478f339d1SEwan Crawford             continue;
102578f339d1SEwan Crawford 
102678f339d1SEwan Crawford         // Obtain the script address which we use as a key.
102778f339d1SEwan Crawford         lldb::addr_t script;
102878f339d1SEwan Crawford         if (!rs_script->script.get(script))
102978f339d1SEwan Crawford             continue;
103078f339d1SEwan Crawford 
103178f339d1SEwan Crawford         // If we have a script mapping for the current script.
103278f339d1SEwan Crawford         if (m_scriptMappings.find(script) != m_scriptMappings.end())
10334640cde1SColin Riley         {
103478f339d1SEwan Crawford             // if the module we have stored is different to the one we just received.
103578f339d1SEwan Crawford             if (m_scriptMappings[script] != rsmodule_sp)
10364640cde1SColin Riley             {
10374640cde1SColin Riley                 if (log)
10384640cde1SColin Riley                     log->Printf ("RenderScriptRuntime::FixupScriptDetails - Error: script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
103978f339d1SEwan Crawford                                     (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
10404640cde1SColin Riley             }
10414640cde1SColin Riley         }
104278f339d1SEwan Crawford         // We don't have a script mapping for the current script.
10434640cde1SColin Riley         else
10444640cde1SColin Riley         {
104578f339d1SEwan Crawford             // Obtain the script resource name.
104678f339d1SEwan Crawford             std::string resName;
104778f339d1SEwan Crawford             if (rs_script->resName.get(resName))
104878f339d1SEwan Crawford                 // Set the modules resource name.
104978f339d1SEwan Crawford                 rsmodule_sp->m_resname = resName;
105078f339d1SEwan Crawford             // Add Script/Module pair to map.
105178f339d1SEwan Crawford             m_scriptMappings[script] = rsmodule_sp;
10524640cde1SColin Riley             if (log)
10534640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::FixupScriptDetails - script %" PRIx64 " associated with rsmodule '%s'.",
105478f339d1SEwan Crawford                                 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
10554640cde1SColin Riley         }
10564640cde1SColin Riley     }
10574640cde1SColin Riley }
10584640cde1SColin Riley 
105915f2bd95SEwan Crawford // Uses the Target API to evaluate the expression passed as a parameter to the function
106015f2bd95SEwan Crawford // The result of that expression is returned an unsigned 64 bit int, via the result* paramter.
106115f2bd95SEwan Crawford // Function returns true on success, and false on failure
106215f2bd95SEwan Crawford bool
106315f2bd95SEwan Crawford RenderScriptRuntime::EvalRSExpression(const char* expression, StackFrame* frame_ptr, uint64_t* result)
106415f2bd95SEwan Crawford {
106515f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
106615f2bd95SEwan Crawford     if (log)
106715f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::EvalRSExpression(%s)", expression);
106815f2bd95SEwan Crawford 
106915f2bd95SEwan Crawford     ValueObjectSP expr_result;
107015f2bd95SEwan Crawford     // Perform the actual expression evaluation
107115f2bd95SEwan Crawford     GetProcess()->GetTarget().EvaluateExpression(expression, frame_ptr, expr_result);
107215f2bd95SEwan Crawford 
107315f2bd95SEwan Crawford     if (!expr_result)
107415f2bd95SEwan Crawford     {
107515f2bd95SEwan Crawford        if (log)
107615f2bd95SEwan Crawford            log->Printf("RenderScriptRuntime::EvalRSExpression -  Error: Couldn't evaluate expression");
107715f2bd95SEwan Crawford        return false;
107815f2bd95SEwan Crawford     }
107915f2bd95SEwan Crawford 
108015f2bd95SEwan Crawford     // The result of the expression is invalid
108115f2bd95SEwan Crawford     if (!expr_result->GetError().Success())
108215f2bd95SEwan Crawford     {
108315f2bd95SEwan Crawford         Error err = expr_result->GetError();
108415f2bd95SEwan Crawford         if (err.GetError() == UserExpression::kNoResult) // Expression returned void, so this is actually a success
108515f2bd95SEwan Crawford         {
108615f2bd95SEwan Crawford             if (log)
108715f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::EvalRSExpression - Expression returned void");
108815f2bd95SEwan Crawford 
108915f2bd95SEwan Crawford             result = nullptr;
109015f2bd95SEwan Crawford             return true;
109115f2bd95SEwan Crawford         }
109215f2bd95SEwan Crawford 
109315f2bd95SEwan Crawford         if (log)
109415f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::EvalRSExpression - Error evaluating expression result: %s", err.AsCString());
109515f2bd95SEwan Crawford         return false;
109615f2bd95SEwan Crawford     }
109715f2bd95SEwan Crawford 
109815f2bd95SEwan Crawford     bool success = false;
109915f2bd95SEwan Crawford     *result = expr_result->GetValueAsUnsigned(0, &success); // We only read the result as an unsigned int.
110015f2bd95SEwan Crawford 
110115f2bd95SEwan Crawford     if (!success)
110215f2bd95SEwan Crawford     {
110315f2bd95SEwan Crawford        if (log)
110415f2bd95SEwan Crawford            log->Printf("RenderScriptRuntime::EvalRSExpression -  Error: Couldn't convert expression result to unsigned int");
110515f2bd95SEwan Crawford        return false;
110615f2bd95SEwan Crawford     }
110715f2bd95SEwan Crawford 
110815f2bd95SEwan Crawford     return true;
110915f2bd95SEwan Crawford }
111015f2bd95SEwan Crawford 
111115f2bd95SEwan Crawford // Used to index expression format strings
111215f2bd95SEwan Crawford enum ExpressionStrings
111315f2bd95SEwan Crawford {
111415f2bd95SEwan Crawford    eExprGetOffsetPtr = 0,
111515f2bd95SEwan Crawford    eExprAllocGetType,
111615f2bd95SEwan Crawford    eExprTypeDimX,
111715f2bd95SEwan Crawford    eExprTypeDimY,
111815f2bd95SEwan Crawford    eExprTypeDimZ,
111915f2bd95SEwan Crawford    eExprTypeElemPtr,
112015f2bd95SEwan Crawford    eExprElementType,
112115f2bd95SEwan Crawford    eExprElementKind,
1122*8b244e21SEwan Crawford    eExprElementVec,
1123*8b244e21SEwan Crawford    eExprElementFieldCount,
1124*8b244e21SEwan Crawford    eExprSubelementsId,
1125*8b244e21SEwan Crawford    eExprSubelementsName,
1126*8b244e21SEwan Crawford    eExprSubelementsArrSize
112715f2bd95SEwan Crawford };
112815f2bd95SEwan Crawford 
112915f2bd95SEwan Crawford // Format strings containing the expressions we may need to evaluate.
113015f2bd95SEwan Crawford const char runtimeExpressions[][256] =
113115f2bd95SEwan Crawford {
113215f2bd95SEwan Crawford  // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
113315f2bd95SEwan Crawford  "(int*)_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace(0x%lx, %u, %u, %u, 0, 0)",
113415f2bd95SEwan Crawford 
113515f2bd95SEwan Crawford  // Type* rsaAllocationGetType(Context*, Allocation*)
113615f2bd95SEwan Crawford  "(void*)rsaAllocationGetType(0x%lx, 0x%lx)",
113715f2bd95SEwan Crawford 
113815f2bd95SEwan Crawford  // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
113915f2bd95SEwan Crawford  // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ;
114015f2bd95SEwan Crawford  // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
114115f2bd95SEwan Crawford  // Need to specify 32 or 64 bit for uint_t since this differs between devices
114215f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[0]", // X dim
114315f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[1]", // Y dim
114415f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[2]", // Z dim
114515f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[5]", // Element ptr
114615f2bd95SEwan Crawford 
114715f2bd95SEwan Crawford  // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
114815f2bd95SEwan Crawford  // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData
1149*8b244e21SEwan Crawford  "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[0]", // Type
1150*8b244e21SEwan Crawford  "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[1]", // Kind
1151*8b244e21SEwan Crawford  "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[3]", // Vector Size
1152*8b244e21SEwan Crawford  "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[4]", // Field Count
1153*8b244e21SEwan Crawford 
1154*8b244e21SEwan Crawford   // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t *ids, const char **names,
1155*8b244e21SEwan Crawford   // size_t *arraySizes, uint32_t dataSize)
1156*8b244e21SEwan Crawford   // Needed for Allocations of structs to gather details about fields/Subelements
1157*8b244e21SEwan Crawford  "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
1158*8b244e21SEwan Crawford  "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); ids[%u]",     // Element* of field
1159*8b244e21SEwan Crawford 
1160*8b244e21SEwan Crawford  "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
1161*8b244e21SEwan Crawford  "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); names[%u]",   // Name of field
1162*8b244e21SEwan Crawford 
1163*8b244e21SEwan Crawford  "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
1164*8b244e21SEwan Crawford  "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); arr_size[%u]" // Array size of field
116515f2bd95SEwan Crawford };
116615f2bd95SEwan Crawford 
116715f2bd95SEwan Crawford // JITs the RS runtime for the internal data pointer of an allocation.
116815f2bd95SEwan Crawford // Is passed x,y,z coordinates for the pointer to a specific element.
116915f2bd95SEwan Crawford // Then sets the data_ptr member in Allocation with the result.
117015f2bd95SEwan Crawford // Returns true on success, false otherwise
117115f2bd95SEwan Crawford bool
117215f2bd95SEwan Crawford RenderScriptRuntime::JITDataPointer(AllocationDetails* allocation, StackFrame* frame_ptr,
117315f2bd95SEwan Crawford                                     unsigned int x, unsigned int y, unsigned int z)
117415f2bd95SEwan Crawford {
117515f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
117615f2bd95SEwan Crawford 
117715f2bd95SEwan Crawford     if (!allocation->address.isValid())
117815f2bd95SEwan Crawford     {
117915f2bd95SEwan Crawford         if (log)
118015f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Failed to find allocation details");
118115f2bd95SEwan Crawford         return false;
118215f2bd95SEwan Crawford     }
118315f2bd95SEwan Crawford 
118415f2bd95SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprGetOffsetPtr];
118515f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
118615f2bd95SEwan Crawford     char buffer[max_expr_size];
118715f2bd95SEwan Crawford 
118815f2bd95SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->address.get(), x, y, z);
118915f2bd95SEwan Crawford     if (chars_written < 0)
119015f2bd95SEwan Crawford     {
119115f2bd95SEwan Crawford         if (log)
119215f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
119315f2bd95SEwan Crawford         return false;
119415f2bd95SEwan Crawford     }
119515f2bd95SEwan Crawford     else if (chars_written >= max_expr_size)
119615f2bd95SEwan Crawford     {
119715f2bd95SEwan Crawford         if (log)
119815f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Expression too long");
119915f2bd95SEwan Crawford         return false;
120015f2bd95SEwan Crawford     }
120115f2bd95SEwan Crawford 
120215f2bd95SEwan Crawford     uint64_t result = 0;
120315f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
120415f2bd95SEwan Crawford         return false;
120515f2bd95SEwan Crawford 
120615f2bd95SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
120715f2bd95SEwan Crawford     allocation->data_ptr = mem_ptr;
120815f2bd95SEwan Crawford 
120915f2bd95SEwan Crawford     return true;
121015f2bd95SEwan Crawford }
121115f2bd95SEwan Crawford 
121215f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
121315f2bd95SEwan Crawford // Then sets the type_ptr member in Allocation with the result.
121415f2bd95SEwan Crawford // Returns true on success, false otherwise
121515f2bd95SEwan Crawford bool
121615f2bd95SEwan Crawford RenderScriptRuntime::JITTypePointer(AllocationDetails* allocation, StackFrame* frame_ptr)
121715f2bd95SEwan Crawford {
121815f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
121915f2bd95SEwan Crawford 
122015f2bd95SEwan Crawford     if (!allocation->address.isValid() || !allocation->context.isValid())
122115f2bd95SEwan Crawford     {
122215f2bd95SEwan Crawford         if (log)
122315f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePointer - Failed to find allocation details");
122415f2bd95SEwan Crawford         return false;
122515f2bd95SEwan Crawford     }
122615f2bd95SEwan Crawford 
122715f2bd95SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprAllocGetType];
122815f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
122915f2bd95SEwan Crawford     char buffer[max_expr_size];
123015f2bd95SEwan Crawford 
123115f2bd95SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->context.get(), *allocation->address.get());
123215f2bd95SEwan Crawford     if (chars_written < 0)
123315f2bd95SEwan Crawford     {
123415f2bd95SEwan Crawford         if (log)
123515f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
123615f2bd95SEwan Crawford         return false;
123715f2bd95SEwan Crawford     }
123815f2bd95SEwan Crawford     else if (chars_written >= max_expr_size)
123915f2bd95SEwan Crawford     {
124015f2bd95SEwan Crawford         if (log)
124115f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePointer - Expression too long");
124215f2bd95SEwan Crawford         return false;
124315f2bd95SEwan Crawford     }
124415f2bd95SEwan Crawford 
124515f2bd95SEwan Crawford     uint64_t result = 0;
124615f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
124715f2bd95SEwan Crawford         return false;
124815f2bd95SEwan Crawford 
124915f2bd95SEwan Crawford     addr_t type_ptr = static_cast<lldb::addr_t>(result);
125015f2bd95SEwan Crawford     allocation->type_ptr = type_ptr;
125115f2bd95SEwan Crawford 
125215f2bd95SEwan Crawford     return true;
125315f2bd95SEwan Crawford }
125415f2bd95SEwan Crawford 
125515f2bd95SEwan Crawford // JITs the RS runtime for information about the dimensions and type of an allocation
125615f2bd95SEwan Crawford // Then sets dimension and element_ptr members in Allocation with the result.
125715f2bd95SEwan Crawford // Returns true on success, false otherwise
125815f2bd95SEwan Crawford bool
125915f2bd95SEwan Crawford RenderScriptRuntime::JITTypePacked(AllocationDetails* allocation, StackFrame* frame_ptr)
126015f2bd95SEwan Crawford {
126115f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
126215f2bd95SEwan Crawford 
126315f2bd95SEwan Crawford     if (!allocation->type_ptr.isValid() || !allocation->context.isValid())
126415f2bd95SEwan Crawford     {
126515f2bd95SEwan Crawford         if (log)
126615f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePacked - Failed to find allocation details");
126715f2bd95SEwan Crawford         return false;
126815f2bd95SEwan Crawford     }
126915f2bd95SEwan Crawford 
127015f2bd95SEwan Crawford     // Expression is different depending on if device is 32 or 64 bit
127115f2bd95SEwan Crawford     uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
127215f2bd95SEwan Crawford     const unsigned int bits = archByteSize == 4 ? 32 : 64;
127315f2bd95SEwan Crawford 
127415f2bd95SEwan Crawford     // We want 4 elements from packed data
127515f2bd95SEwan Crawford     const unsigned int num_exprs = 4;
127615f2bd95SEwan Crawford     assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) && "Invalid number of expressions");
127715f2bd95SEwan Crawford 
127815f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
127915f2bd95SEwan Crawford     char buffer[num_exprs][max_expr_size];
128015f2bd95SEwan Crawford     uint64_t results[num_exprs];
128115f2bd95SEwan Crawford 
128215f2bd95SEwan Crawford     for (unsigned int i = 0; i < num_exprs; ++i)
128315f2bd95SEwan Crawford     {
128415f2bd95SEwan Crawford         int chars_written = snprintf(buffer[i], max_expr_size, runtimeExpressions[eExprTypeDimX + i], bits,
128515f2bd95SEwan Crawford                                      *allocation->context.get(), *allocation->type_ptr.get());
128615f2bd95SEwan Crawford         if (chars_written < 0)
128715f2bd95SEwan Crawford         {
128815f2bd95SEwan Crawford             if (log)
128915f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
129015f2bd95SEwan Crawford             return false;
129115f2bd95SEwan Crawford         }
129215f2bd95SEwan Crawford         else if (chars_written >= max_expr_size)
129315f2bd95SEwan Crawford         {
129415f2bd95SEwan Crawford             if (log)
129515f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITTypePacked - Expression too long");
129615f2bd95SEwan Crawford             return false;
129715f2bd95SEwan Crawford         }
129815f2bd95SEwan Crawford 
129915f2bd95SEwan Crawford         // Perform expression evaluation
130015f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
130115f2bd95SEwan Crawford             return false;
130215f2bd95SEwan Crawford     }
130315f2bd95SEwan Crawford 
130415f2bd95SEwan Crawford     // Assign results to allocation members
130515f2bd95SEwan Crawford     AllocationDetails::Dimension dims;
130615f2bd95SEwan Crawford     dims.dim_1 = static_cast<uint32_t>(results[0]);
130715f2bd95SEwan Crawford     dims.dim_2 = static_cast<uint32_t>(results[1]);
130815f2bd95SEwan Crawford     dims.dim_3 = static_cast<uint32_t>(results[2]);
130915f2bd95SEwan Crawford     allocation->dimension = dims;
131015f2bd95SEwan Crawford 
131115f2bd95SEwan Crawford     addr_t elem_ptr = static_cast<lldb::addr_t>(results[3]);
1312*8b244e21SEwan Crawford     allocation->element.element_ptr = elem_ptr;
131315f2bd95SEwan Crawford 
131415f2bd95SEwan Crawford     if (log)
131515f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::JITTypePacked - dims (%u, %u, %u) Element*: 0x%" PRIx64,
131615f2bd95SEwan Crawford                     dims.dim_1, dims.dim_2, dims.dim_3, elem_ptr);
131715f2bd95SEwan Crawford 
131815f2bd95SEwan Crawford     return true;
131915f2bd95SEwan Crawford }
132015f2bd95SEwan Crawford 
132115f2bd95SEwan Crawford // JITs the RS runtime for information about the Element of an allocation
1322*8b244e21SEwan Crawford // Then sets type, type_vec_size, field_count and type_kind members in Element with the result.
132315f2bd95SEwan Crawford // Returns true on success, false otherwise
132415f2bd95SEwan Crawford bool
1325*8b244e21SEwan Crawford RenderScriptRuntime::JITElementPacked(Element& elem, const lldb::addr_t context, StackFrame* frame_ptr)
132615f2bd95SEwan Crawford {
132715f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
132815f2bd95SEwan Crawford 
1329*8b244e21SEwan Crawford     if (!elem.element_ptr.isValid())
133015f2bd95SEwan Crawford     {
133115f2bd95SEwan Crawford         if (log)
133215f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITElementPacked - Failed to find allocation details");
133315f2bd95SEwan Crawford         return false;
133415f2bd95SEwan Crawford     }
133515f2bd95SEwan Crawford 
1336*8b244e21SEwan Crawford     // We want 4 elements from packed data
1337*8b244e21SEwan Crawford     const unsigned int num_exprs = 4;
1338*8b244e21SEwan Crawford     assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) && "Invalid number of expressions");
133915f2bd95SEwan Crawford 
134015f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
134115f2bd95SEwan Crawford     char buffer[num_exprs][max_expr_size];
134215f2bd95SEwan Crawford     uint64_t results[num_exprs];
134315f2bd95SEwan Crawford 
134415f2bd95SEwan Crawford     for (unsigned int i = 0; i < num_exprs; i++)
134515f2bd95SEwan Crawford     {
1346*8b244e21SEwan Crawford         int chars_written = snprintf(buffer[i], max_expr_size, runtimeExpressions[eExprElementType + i], context, *elem.element_ptr.get());
134715f2bd95SEwan Crawford         if (chars_written < 0)
134815f2bd95SEwan Crawford         {
134915f2bd95SEwan Crawford             if (log)
1350*8b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::JITElementPacked - Encoding error in snprintf()");
135115f2bd95SEwan Crawford             return false;
135215f2bd95SEwan Crawford         }
135315f2bd95SEwan Crawford         else if (chars_written >= max_expr_size)
135415f2bd95SEwan Crawford         {
135515f2bd95SEwan Crawford             if (log)
135615f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITElementPacked - Expression too long");
135715f2bd95SEwan Crawford             return false;
135815f2bd95SEwan Crawford         }
135915f2bd95SEwan Crawford 
136015f2bd95SEwan Crawford         // Perform expression evaluation
136115f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
136215f2bd95SEwan Crawford             return false;
136315f2bd95SEwan Crawford     }
136415f2bd95SEwan Crawford 
136515f2bd95SEwan Crawford     // Assign results to allocation members
1366*8b244e21SEwan Crawford     elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
1367*8b244e21SEwan Crawford     elem.type_kind = static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
1368*8b244e21SEwan Crawford     elem.type_vec_size = static_cast<uint32_t>(results[2]);
1369*8b244e21SEwan Crawford     elem.field_count = static_cast<uint32_t>(results[3]);
137015f2bd95SEwan Crawford 
137115f2bd95SEwan Crawford     if (log)
1372*8b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::JITElementPacked - data type %u, pixel type %u, vector size %u, field count %u",
1373*8b244e21SEwan Crawford                     *elem.type.get(), *elem.type_kind.get(), *elem.type_vec_size.get(), *elem.field_count.get());
1374*8b244e21SEwan Crawford 
1375*8b244e21SEwan Crawford     // If this Element has subelements then JIT rsaElementGetSubElements() for details about its fields
1376*8b244e21SEwan Crawford     if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
1377*8b244e21SEwan Crawford         return false;
1378*8b244e21SEwan Crawford 
1379*8b244e21SEwan Crawford     return true;
1380*8b244e21SEwan Crawford }
1381*8b244e21SEwan Crawford 
1382*8b244e21SEwan Crawford // JITs the RS runtime for information about the subelements/fields of a struct allocation
1383*8b244e21SEwan Crawford // This is necessary for infering the struct type so we can pretty print the allocation's contents.
1384*8b244e21SEwan Crawford // Returns true on success, false otherwise
1385*8b244e21SEwan Crawford bool
1386*8b244e21SEwan Crawford RenderScriptRuntime::JITSubelements(Element& elem, const lldb::addr_t context, StackFrame* frame_ptr)
1387*8b244e21SEwan Crawford {
1388*8b244e21SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1389*8b244e21SEwan Crawford 
1390*8b244e21SEwan Crawford     if (!elem.element_ptr.isValid() || !elem.field_count.isValid())
1391*8b244e21SEwan Crawford     {
1392*8b244e21SEwan Crawford         if (log)
1393*8b244e21SEwan Crawford             log->Printf("RenderScriptRuntime::JITSubelements - Failed to find allocation details");
1394*8b244e21SEwan Crawford         return false;
1395*8b244e21SEwan Crawford     }
1396*8b244e21SEwan Crawford 
1397*8b244e21SEwan Crawford     const short num_exprs = 3;
1398*8b244e21SEwan Crawford     assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) && "Invalid number of expressions");
1399*8b244e21SEwan Crawford 
1400*8b244e21SEwan Crawford     const int max_expr_size = 512; // Max expression size
1401*8b244e21SEwan Crawford     char expr_buffer[max_expr_size];
1402*8b244e21SEwan Crawford     uint64_t results;
1403*8b244e21SEwan Crawford 
1404*8b244e21SEwan Crawford     // Iterate over struct fields.
1405*8b244e21SEwan Crawford     const uint32_t field_count = *elem.field_count.get();
1406*8b244e21SEwan Crawford     for (unsigned int field_index = 0; field_index < field_count; ++field_index)
1407*8b244e21SEwan Crawford     {
1408*8b244e21SEwan Crawford         Element child;
1409*8b244e21SEwan Crawford         for (unsigned int expr_index = 0; expr_index < num_exprs; ++expr_index)
1410*8b244e21SEwan Crawford         {
1411*8b244e21SEwan Crawford             int chars_written = snprintf(expr_buffer, max_expr_size, runtimeExpressions[eExprSubelementsId + expr_index],
1412*8b244e21SEwan Crawford                                          field_count, field_count, field_count,
1413*8b244e21SEwan Crawford                                          context, *elem.element_ptr.get(), field_count, field_index);
1414*8b244e21SEwan Crawford             if (chars_written < 0)
1415*8b244e21SEwan Crawford             {
1416*8b244e21SEwan Crawford                 if (log)
1417*8b244e21SEwan Crawford                     log->Printf("RenderScriptRuntime::JITSubelements - Encoding error in snprintf()");
1418*8b244e21SEwan Crawford                 return false;
1419*8b244e21SEwan Crawford             }
1420*8b244e21SEwan Crawford             else if (chars_written >= max_expr_size)
1421*8b244e21SEwan Crawford             {
1422*8b244e21SEwan Crawford                 if (log)
1423*8b244e21SEwan Crawford                     log->Printf("RenderScriptRuntime::JITSubelements - Expression too long");
1424*8b244e21SEwan Crawford                 return false;
1425*8b244e21SEwan Crawford             }
1426*8b244e21SEwan Crawford 
1427*8b244e21SEwan Crawford             // Perform expression evaluation
1428*8b244e21SEwan Crawford             if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
1429*8b244e21SEwan Crawford                 return false;
1430*8b244e21SEwan Crawford 
1431*8b244e21SEwan Crawford             if (log)
1432*8b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::JITSubelements - Expr result 0x%" PRIx64, results);
1433*8b244e21SEwan Crawford 
1434*8b244e21SEwan Crawford             switch(expr_index)
1435*8b244e21SEwan Crawford             {
1436*8b244e21SEwan Crawford                 case 0: // Element* of child
1437*8b244e21SEwan Crawford                     child.element_ptr = static_cast<addr_t>(results);
1438*8b244e21SEwan Crawford                     break;
1439*8b244e21SEwan Crawford                 case 1: // Name of child
1440*8b244e21SEwan Crawford                 {
1441*8b244e21SEwan Crawford                     lldb::addr_t address = static_cast<addr_t>(results);
1442*8b244e21SEwan Crawford                     Error err;
1443*8b244e21SEwan Crawford                     std::string name;
1444*8b244e21SEwan Crawford                     GetProcess()->ReadCStringFromMemory(address, name, err);
1445*8b244e21SEwan Crawford                     if (!err.Fail())
1446*8b244e21SEwan Crawford                         child.type_name = ConstString(name);
1447*8b244e21SEwan Crawford                     else
1448*8b244e21SEwan Crawford                     {
1449*8b244e21SEwan Crawford                         if (log)
1450*8b244e21SEwan Crawford                             log->Printf("RenderScriptRuntime::JITSubelements - Warning: Couldn't read field name");
1451*8b244e21SEwan Crawford                     }
1452*8b244e21SEwan Crawford                     break;
1453*8b244e21SEwan Crawford                 }
1454*8b244e21SEwan Crawford                 case 2: // Array size of child
1455*8b244e21SEwan Crawford                     child.array_size = static_cast<uint32_t>(results);
1456*8b244e21SEwan Crawford                     break;
1457*8b244e21SEwan Crawford             }
1458*8b244e21SEwan Crawford         }
1459*8b244e21SEwan Crawford 
1460*8b244e21SEwan Crawford         // We need to recursively JIT each Element field of the struct since
1461*8b244e21SEwan Crawford         // structs can be nested inside structs.
1462*8b244e21SEwan Crawford         if (!JITElementPacked(child, context, frame_ptr))
1463*8b244e21SEwan Crawford             return false;
1464*8b244e21SEwan Crawford         elem.children.push_back(child);
1465*8b244e21SEwan Crawford     }
1466*8b244e21SEwan Crawford 
1467*8b244e21SEwan Crawford     // Try to infer the name of the struct type so we can pretty print the allocation contents.
1468*8b244e21SEwan Crawford     FindStructTypeName(elem, frame_ptr);
146915f2bd95SEwan Crawford 
147015f2bd95SEwan Crawford     return true;
147115f2bd95SEwan Crawford }
147215f2bd95SEwan Crawford 
1473a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
1474a0f08674SEwan Crawford // The `elem_size` paramter represents the size of a single element, including padding.
1475a0f08674SEwan Crawford // Which is needed as an offset from the last element pointer.
1476a0f08674SEwan Crawford // Using this offset minus the starting address we can calculate the size of the allocation.
1477a0f08674SEwan Crawford // Returns true on success, false otherwise
1478a0f08674SEwan Crawford bool
1479*8b244e21SEwan Crawford RenderScriptRuntime::JITAllocationSize(AllocationDetails* allocation, StackFrame* frame_ptr)
1480a0f08674SEwan Crawford {
1481a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1482a0f08674SEwan Crawford 
1483a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->dimension.isValid()
1484*8b244e21SEwan Crawford         || !allocation->data_ptr.isValid() || !allocation->element.datum_size.isValid())
1485a0f08674SEwan Crawford     {
1486a0f08674SEwan Crawford         if (log)
1487a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Failed to find allocation details");
1488a0f08674SEwan Crawford         return false;
1489a0f08674SEwan Crawford     }
1490a0f08674SEwan Crawford 
1491a0f08674SEwan Crawford     // Find dimensions
1492a0f08674SEwan Crawford     unsigned int dim_x = allocation->dimension.get()->dim_1;
1493a0f08674SEwan Crawford     unsigned int dim_y = allocation->dimension.get()->dim_2;
1494a0f08674SEwan Crawford     unsigned int dim_z = allocation->dimension.get()->dim_3;
1495a0f08674SEwan Crawford 
1496*8b244e21SEwan Crawford     // Our plan of jitting the last element address doesn't seem to work for struct Allocations
1497*8b244e21SEwan Crawford     // Instead try to infer the size ourselves without any inter element padding.
1498*8b244e21SEwan Crawford     if (allocation->element.children.size() > 0)
1499*8b244e21SEwan Crawford     {
1500*8b244e21SEwan Crawford         if (dim_x == 0) dim_x = 1;
1501*8b244e21SEwan Crawford         if (dim_y == 0) dim_y = 1;
1502*8b244e21SEwan Crawford         if (dim_z == 0) dim_z = 1;
1503*8b244e21SEwan Crawford 
1504*8b244e21SEwan Crawford         allocation->size = dim_x * dim_y * dim_z * *allocation->element.datum_size.get();
1505*8b244e21SEwan Crawford 
1506*8b244e21SEwan Crawford         if (log)
1507*8b244e21SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Infered size of struct allocation %u", *allocation->size.get());
1508*8b244e21SEwan Crawford 
1509*8b244e21SEwan Crawford         return true;
1510*8b244e21SEwan Crawford     }
1511*8b244e21SEwan Crawford 
1512*8b244e21SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprGetOffsetPtr];
1513*8b244e21SEwan Crawford     const int max_expr_size = 512;
1514*8b244e21SEwan Crawford     char buffer[max_expr_size];
1515*8b244e21SEwan Crawford 
1516a0f08674SEwan Crawford     // Calculate last element
1517a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 0 : dim_x - 1;
1518a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 0 : dim_y - 1;
1519a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 0 : dim_z - 1;
1520a0f08674SEwan Crawford 
1521a0f08674SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->address.get(),
1522a0f08674SEwan Crawford                                  dim_x, dim_y, dim_z);
1523a0f08674SEwan Crawford     if (chars_written < 0)
1524a0f08674SEwan Crawford     {
1525a0f08674SEwan Crawford         if (log)
1526a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Encoding error in snprintf()");
1527a0f08674SEwan Crawford         return false;
1528a0f08674SEwan Crawford     }
1529a0f08674SEwan Crawford     else if (chars_written >= max_expr_size)
1530a0f08674SEwan Crawford     {
1531a0f08674SEwan Crawford         if (log)
1532a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Expression too long");
1533a0f08674SEwan Crawford         return false;
1534a0f08674SEwan Crawford     }
1535a0f08674SEwan Crawford 
1536a0f08674SEwan Crawford     uint64_t result = 0;
1537a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1538a0f08674SEwan Crawford         return false;
1539a0f08674SEwan Crawford 
1540a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1541a0f08674SEwan Crawford     // Find pointer to last element and add on size of an element
1542*8b244e21SEwan Crawford     allocation->size = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()) + *allocation->element.datum_size.get();
1543a0f08674SEwan Crawford 
1544a0f08674SEwan Crawford     return true;
1545a0f08674SEwan Crawford }
1546a0f08674SEwan Crawford 
1547a0f08674SEwan Crawford // JITs the RS runtime for information about the stride between rows in the allocation.
1548a0f08674SEwan Crawford // This is done to detect padding, since allocated memory is 16-byte aligned.
1549a0f08674SEwan Crawford // Returns true on success, false otherwise
1550a0f08674SEwan Crawford bool
1551a0f08674SEwan Crawford RenderScriptRuntime::JITAllocationStride(AllocationDetails* allocation, StackFrame* frame_ptr)
1552a0f08674SEwan Crawford {
1553a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1554a0f08674SEwan Crawford 
1555a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->data_ptr.isValid())
1556a0f08674SEwan Crawford     {
1557a0f08674SEwan Crawford         if (log)
1558a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Failed to find allocation details");
1559a0f08674SEwan Crawford         return false;
1560a0f08674SEwan Crawford     }
1561a0f08674SEwan Crawford 
1562a0f08674SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprGetOffsetPtr];
1563a0f08674SEwan Crawford     const int max_expr_size = 512; // Max expression size
1564a0f08674SEwan Crawford     char buffer[max_expr_size];
1565a0f08674SEwan Crawford 
1566a0f08674SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->address.get(),
1567a0f08674SEwan Crawford                                  0, 1, 0);
1568a0f08674SEwan Crawford     if (chars_written < 0)
1569a0f08674SEwan Crawford     {
1570a0f08674SEwan Crawford         if (log)
1571a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Encoding error in snprintf()");
1572a0f08674SEwan Crawford         return false;
1573a0f08674SEwan Crawford     }
1574a0f08674SEwan Crawford     else if (chars_written >= max_expr_size)
1575a0f08674SEwan Crawford     {
1576a0f08674SEwan Crawford         if (log)
1577a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Expression too long");
1578a0f08674SEwan Crawford         return false;
1579a0f08674SEwan Crawford     }
1580a0f08674SEwan Crawford 
1581a0f08674SEwan Crawford     uint64_t result = 0;
1582a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1583a0f08674SEwan Crawford         return false;
1584a0f08674SEwan Crawford 
1585a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1586a0f08674SEwan Crawford     allocation->stride = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get());
1587a0f08674SEwan Crawford 
1588a0f08674SEwan Crawford     return true;
1589a0f08674SEwan Crawford }
1590a0f08674SEwan Crawford 
159115f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
159215f2bd95SEwan Crawford bool
159315f2bd95SEwan Crawford RenderScriptRuntime::RefreshAllocation(AllocationDetails* allocation, StackFrame* frame_ptr)
159415f2bd95SEwan Crawford {
159515f2bd95SEwan Crawford     // GetOffsetPointer()
159615f2bd95SEwan Crawford     if (!JITDataPointer(allocation, frame_ptr))
159715f2bd95SEwan Crawford         return false;
159815f2bd95SEwan Crawford 
159915f2bd95SEwan Crawford     // rsaAllocationGetType()
160015f2bd95SEwan Crawford     if (!JITTypePointer(allocation, frame_ptr))
160115f2bd95SEwan Crawford         return false;
160215f2bd95SEwan Crawford 
160315f2bd95SEwan Crawford     // rsaTypeGetNativeData()
160415f2bd95SEwan Crawford     if (!JITTypePacked(allocation, frame_ptr))
160515f2bd95SEwan Crawford         return false;
160615f2bd95SEwan Crawford 
160715f2bd95SEwan Crawford     // rsaElementGetNativeData()
1608*8b244e21SEwan Crawford     if (!JITElementPacked(allocation->element, *allocation->context.get(), frame_ptr))
160915f2bd95SEwan Crawford         return false;
161015f2bd95SEwan Crawford 
1611*8b244e21SEwan Crawford     // Sets the datum_size member in Element
1612*8b244e21SEwan Crawford     SetElementSize(allocation->element);
1613*8b244e21SEwan Crawford 
161455232f09SEwan Crawford     // Use GetOffsetPointer() to infer size of the allocation
1615*8b244e21SEwan Crawford     if (!JITAllocationSize(allocation, frame_ptr))
161655232f09SEwan Crawford         return false;
161755232f09SEwan Crawford 
161855232f09SEwan Crawford     return true;
161955232f09SEwan Crawford }
162055232f09SEwan Crawford 
1621*8b244e21SEwan Crawford // Function attempts to set the type_name member of the paramaterised Element object.
1622*8b244e21SEwan Crawford // This string should be the name of the struct type the Element represents.
1623*8b244e21SEwan Crawford // We need this string for pretty printing the Element to users.
1624*8b244e21SEwan Crawford void
1625*8b244e21SEwan Crawford RenderScriptRuntime::FindStructTypeName(Element& elem, StackFrame* frame_ptr)
162655232f09SEwan Crawford {
1627*8b244e21SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1628*8b244e21SEwan Crawford 
1629*8b244e21SEwan Crawford     if (!elem.type_name.IsEmpty()) // Name already set
1630*8b244e21SEwan Crawford         return;
1631*8b244e21SEwan Crawford     else
1632*8b244e21SEwan Crawford         elem.type_name = Element::FallbackStructName; // Default type name if we don't succeed
1633*8b244e21SEwan Crawford 
1634*8b244e21SEwan Crawford     // Find all the global variables from the script rs modules
1635*8b244e21SEwan Crawford     VariableList variable_list;
1636*8b244e21SEwan Crawford     for (auto module_sp : m_rsmodules)
1637*8b244e21SEwan Crawford         module_sp->m_module->FindGlobalVariables(RegularExpression("."), true, UINT32_MAX, variable_list);
1638*8b244e21SEwan Crawford 
1639*8b244e21SEwan Crawford     // Iterate over all the global variables looking for one with a matching type to the Element.
1640*8b244e21SEwan Crawford     // We make the assumption a match exists since there needs to be a global variable to reflect the
1641*8b244e21SEwan Crawford     // struct type back into java host code.
1642*8b244e21SEwan Crawford     for (uint32_t var_index = 0; var_index < variable_list.GetSize(); ++var_index)
1643*8b244e21SEwan Crawford     {
1644*8b244e21SEwan Crawford         const VariableSP var_sp(variable_list.GetVariableAtIndex(var_index));
1645*8b244e21SEwan Crawford         if (!var_sp)
1646*8b244e21SEwan Crawford            continue;
1647*8b244e21SEwan Crawford 
1648*8b244e21SEwan Crawford         ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
1649*8b244e21SEwan Crawford         if (!valobj_sp)
1650*8b244e21SEwan Crawford             continue;
1651*8b244e21SEwan Crawford 
1652*8b244e21SEwan Crawford         // Find the number of variable fields.
1653*8b244e21SEwan Crawford         // If it has no fields, or more fields than our Element, then it can't be the struct we're looking for.
1654*8b244e21SEwan Crawford         // Don't check for equality since RS can add extra struct members for padding.
1655*8b244e21SEwan Crawford         size_t num_children = valobj_sp->GetNumChildren();
1656*8b244e21SEwan Crawford         if (num_children > elem.children.size() || num_children == 0)
1657*8b244e21SEwan Crawford             continue;
1658*8b244e21SEwan Crawford 
1659*8b244e21SEwan Crawford         // Iterate over children looking for members with matching field names.
1660*8b244e21SEwan Crawford         // If all the field names match, this is likely the struct we want.
1661*8b244e21SEwan Crawford         //
1662*8b244e21SEwan Crawford         //   TODO: This could be made more robust by also checking children data sizes, or array size
1663*8b244e21SEwan Crawford         bool found = true;
1664*8b244e21SEwan Crawford         for (size_t child_index = 0; child_index < num_children; ++child_index)
1665*8b244e21SEwan Crawford         {
1666*8b244e21SEwan Crawford             ValueObjectSP child = valobj_sp->GetChildAtIndex(child_index, true);
1667*8b244e21SEwan Crawford             if (!child || (child->GetName() != elem.children[child_index].type_name))
1668*8b244e21SEwan Crawford             {
1669*8b244e21SEwan Crawford                 found = false;
1670*8b244e21SEwan Crawford                 break;
1671*8b244e21SEwan Crawford             }
1672*8b244e21SEwan Crawford         }
1673*8b244e21SEwan Crawford 
1674*8b244e21SEwan Crawford         // RS can add extra struct members for padding in the format '#rs_padding_[0-9]+'
1675*8b244e21SEwan Crawford         if (found && num_children < elem.children.size())
1676*8b244e21SEwan Crawford         {
1677*8b244e21SEwan Crawford             const unsigned int size_diff = elem.children.size() - num_children;
1678*8b244e21SEwan Crawford             if (log)
1679*8b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::FindStructTypeName - %u padding struct entries", size_diff);
1680*8b244e21SEwan Crawford 
1681*8b244e21SEwan Crawford             for (unsigned int padding_index = 0; padding_index < size_diff; ++padding_index)
1682*8b244e21SEwan Crawford             {
1683*8b244e21SEwan Crawford                 const ConstString& name = elem.children[num_children + padding_index].type_name;
1684*8b244e21SEwan Crawford                 if (strcmp(name.AsCString(), "#rs_padding") < 0)
1685*8b244e21SEwan Crawford                     found = false;
1686*8b244e21SEwan Crawford             }
1687*8b244e21SEwan Crawford         }
1688*8b244e21SEwan Crawford 
1689*8b244e21SEwan Crawford         // We've found a global var with matching type
1690*8b244e21SEwan Crawford         if (found)
1691*8b244e21SEwan Crawford         {
1692*8b244e21SEwan Crawford             // Dereference since our Element type isn't a pointer.
1693*8b244e21SEwan Crawford             if (valobj_sp->IsPointerType())
1694*8b244e21SEwan Crawford             {
1695*8b244e21SEwan Crawford                 Error err;
1696*8b244e21SEwan Crawford                 ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
1697*8b244e21SEwan Crawford                 if (!err.Fail())
1698*8b244e21SEwan Crawford                     valobj_sp = deref_valobj;
1699*8b244e21SEwan Crawford             }
1700*8b244e21SEwan Crawford 
1701*8b244e21SEwan Crawford             // Save name of variable in Element.
1702*8b244e21SEwan Crawford             elem.type_name = valobj_sp->GetTypeName();
1703*8b244e21SEwan Crawford             if (log)
1704*8b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::FindStructTypeName - Element name set to %s", elem.type_name.AsCString());
1705*8b244e21SEwan Crawford 
1706*8b244e21SEwan Crawford             return;
1707*8b244e21SEwan Crawford         }
1708*8b244e21SEwan Crawford     }
1709*8b244e21SEwan Crawford }
1710*8b244e21SEwan Crawford 
1711*8b244e21SEwan Crawford // Function sets the datum_size member of Element. Representing the size of a single instance including padding.
1712*8b244e21SEwan Crawford // Assumes the relevant allocation information has already been jitted.
1713*8b244e21SEwan Crawford void
1714*8b244e21SEwan Crawford RenderScriptRuntime::SetElementSize(Element& elem)
1715*8b244e21SEwan Crawford {
1716*8b244e21SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1717*8b244e21SEwan Crawford     const Element::DataType type = *elem.type.get();
1718*8b244e21SEwan Crawford     assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_BOOLEAN
171955232f09SEwan Crawford                                                    && "Invalid allocation type");
172055232f09SEwan Crawford 
1721*8b244e21SEwan Crawford     const unsigned int vec_size = *elem.type_vec_size.get();
1722*8b244e21SEwan Crawford     unsigned int data_size = 0;
172355232f09SEwan Crawford     const unsigned int padding = vec_size == 3 ? AllocationDetails::RSTypeToFormat[type][eElementSize] : 0;
172455232f09SEwan Crawford 
1725*8b244e21SEwan Crawford     // Element is of a struct type, calculate size recursively.
1726*8b244e21SEwan Crawford     if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0))
1727*8b244e21SEwan Crawford     {
1728*8b244e21SEwan Crawford         for (Element& child : elem.children)
1729*8b244e21SEwan Crawford         {
1730*8b244e21SEwan Crawford             SetElementSize(child);
1731*8b244e21SEwan Crawford             const unsigned int array_size = child.array_size.isValid() ? *child.array_size.get() : 1;
1732*8b244e21SEwan Crawford             data_size += *child.datum_size.get() * array_size;
1733*8b244e21SEwan Crawford         }
1734*8b244e21SEwan Crawford     }
1735*8b244e21SEwan Crawford     else
1736*8b244e21SEwan Crawford         data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
1737*8b244e21SEwan Crawford 
1738*8b244e21SEwan Crawford     elem.padding = padding;
1739*8b244e21SEwan Crawford     elem.datum_size = data_size + padding;
1740*8b244e21SEwan Crawford     if (log)
1741*8b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::SetElementSize - element size set to %u", data_size + padding);
174255232f09SEwan Crawford }
174355232f09SEwan Crawford 
174455232f09SEwan Crawford // Given an allocation, this function copies the allocation contents from device into a buffer on the heap.
174555232f09SEwan Crawford // Returning a shared pointer to the buffer containing the data.
174655232f09SEwan Crawford std::shared_ptr<uint8_t>
174755232f09SEwan Crawford RenderScriptRuntime::GetAllocationData(AllocationDetails* allocation, StackFrame* frame_ptr)
174855232f09SEwan Crawford {
174955232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
175055232f09SEwan Crawford 
175155232f09SEwan Crawford     // JIT all the allocation details
1752*8b244e21SEwan Crawford     if (!allocation->data_ptr.isValid() || !allocation->element.type.isValid()
1753*8b244e21SEwan Crawford         || !allocation->element.type_vec_size.isValid() || !allocation->size.isValid())
175455232f09SEwan Crawford     {
175555232f09SEwan Crawford         if (log)
175655232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - Allocation details not calculated yet, jitting info");
175755232f09SEwan Crawford 
175855232f09SEwan Crawford         if (!RefreshAllocation(allocation, frame_ptr))
175955232f09SEwan Crawford         {
176055232f09SEwan Crawford             if (log)
176155232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't JIT allocation details");
176255232f09SEwan Crawford             return nullptr;
176355232f09SEwan Crawford         }
176455232f09SEwan Crawford     }
176555232f09SEwan Crawford 
1766*8b244e21SEwan Crawford     assert(allocation->data_ptr.isValid() && allocation->element.type.isValid() && allocation->element.type_vec_size.isValid()
176755232f09SEwan Crawford            && allocation->size.isValid() && "Allocation information not available");
176855232f09SEwan Crawford 
176955232f09SEwan Crawford     // Allocate a buffer to copy data into
177055232f09SEwan Crawford     const unsigned int size = *allocation->size.get();
177155232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
177255232f09SEwan Crawford     if (!buffer)
177355232f09SEwan Crawford     {
177455232f09SEwan Crawford         if (log)
177555232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't allocate a %u byte buffer", size);
177655232f09SEwan Crawford         return nullptr;
177755232f09SEwan Crawford     }
177855232f09SEwan Crawford 
177955232f09SEwan Crawford     // Read the inferior memory
178055232f09SEwan Crawford     Error error;
178155232f09SEwan Crawford     lldb::addr_t data_ptr = *allocation->data_ptr.get();
178255232f09SEwan Crawford     GetProcess()->ReadMemory(data_ptr, buffer.get(), size, error);
178355232f09SEwan Crawford     if (error.Fail())
178455232f09SEwan Crawford     {
178555232f09SEwan Crawford         if (log)
178655232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - '%s' Couldn't read %u bytes of allocation data from 0x%" PRIx64,
178755232f09SEwan Crawford                         error.AsCString(), size, data_ptr);
178855232f09SEwan Crawford         return nullptr;
178955232f09SEwan Crawford     }
179055232f09SEwan Crawford 
179155232f09SEwan Crawford     return buffer;
179255232f09SEwan Crawford }
179355232f09SEwan Crawford 
179455232f09SEwan Crawford // Function copies data from a binary file into an allocation.
179555232f09SEwan Crawford // There is a header at the start of the file, FileHeader, before the data content itself.
179655232f09SEwan Crawford // Information from this header is used to display warnings to the user about incompatabilities
179755232f09SEwan Crawford bool
179855232f09SEwan Crawford RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr)
179955232f09SEwan Crawford {
180055232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
180155232f09SEwan Crawford 
180255232f09SEwan Crawford     // Find allocation with the given id
180355232f09SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, alloc_id);
180455232f09SEwan Crawford     if (!alloc)
180555232f09SEwan Crawford         return false;
180655232f09SEwan Crawford 
180755232f09SEwan Crawford     if (log)
180855232f09SEwan Crawford         log->Printf("RenderScriptRuntime::LoadAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
180955232f09SEwan Crawford 
181055232f09SEwan Crawford     // JIT all the allocation details
1811*8b244e21SEwan Crawford     if (!alloc->data_ptr.isValid() || !alloc->element.type.isValid() || !alloc->element.datum_size.isValid()
1812*8b244e21SEwan Crawford         || !alloc->element.type_vec_size.isValid() || !alloc->size.isValid())
181355232f09SEwan Crawford     {
181455232f09SEwan Crawford         if (log)
181555232f09SEwan Crawford             log->Printf("RenderScriptRuntime::LoadAllocation - Allocation details not calculated yet, jitting info");
181655232f09SEwan Crawford 
181755232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
181855232f09SEwan Crawford         {
181955232f09SEwan Crawford             if (log)
182055232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::LoadAllocation - Couldn't JIT allocation details");
18214cfc9198SSylvestre Ledru             return false;
182255232f09SEwan Crawford         }
182355232f09SEwan Crawford     }
182455232f09SEwan Crawford 
1825*8b244e21SEwan Crawford     assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid()
1826*8b244e21SEwan Crawford            && alloc->size.isValid() && alloc->element.datum_size.isValid() && "Allocation information not available");
182755232f09SEwan Crawford 
182855232f09SEwan Crawford     // Check we can read from file
182955232f09SEwan Crawford     FileSpec file(filename, true);
183055232f09SEwan Crawford     if (!file.Exists())
183155232f09SEwan Crawford     {
183255232f09SEwan Crawford         strm.Printf("Error: File %s does not exist", filename);
183355232f09SEwan Crawford         strm.EOL();
183455232f09SEwan Crawford         return false;
183555232f09SEwan Crawford     }
183655232f09SEwan Crawford 
183755232f09SEwan Crawford     if (!file.Readable())
183855232f09SEwan Crawford     {
183955232f09SEwan Crawford         strm.Printf("Error: File %s does not have readable permissions", filename);
184055232f09SEwan Crawford         strm.EOL();
184155232f09SEwan Crawford         return false;
184255232f09SEwan Crawford     }
184355232f09SEwan Crawford 
184455232f09SEwan Crawford     // Read file into data buffer
184555232f09SEwan Crawford     DataBufferSP data_sp(file.ReadFileContents());
184655232f09SEwan Crawford 
184755232f09SEwan Crawford     // Cast start of buffer to FileHeader and use pointer to read metadata
184855232f09SEwan Crawford     void* file_buffer = data_sp->GetBytes();
184955232f09SEwan Crawford     const AllocationDetails::FileHeader* head = static_cast<AllocationDetails::FileHeader*>(file_buffer);
185055232f09SEwan Crawford 
185155232f09SEwan Crawford     // Advance buffer past header
185255232f09SEwan Crawford     file_buffer = static_cast<uint8_t*>(file_buffer) + head->hdr_size;
185355232f09SEwan Crawford 
185455232f09SEwan Crawford     if (log)
185555232f09SEwan Crawford         log->Printf("RenderScriptRuntime::LoadAllocation - header type %u, element size %u",
185655232f09SEwan Crawford                     head->type, head->element_size);
185755232f09SEwan Crawford 
185855232f09SEwan Crawford     // Check if the target allocation and file both have the same number of bytes for an Element
1859*8b244e21SEwan Crawford     if (*alloc->element.datum_size.get() != head->element_size)
186055232f09SEwan Crawford     {
186155232f09SEwan Crawford         strm.Printf("Warning: Mismatched Element sizes - file %u bytes, allocation %u bytes",
1862*8b244e21SEwan Crawford                     head->element_size, *alloc->element.datum_size.get());
186355232f09SEwan Crawford         strm.EOL();
186455232f09SEwan Crawford     }
186555232f09SEwan Crawford 
186655232f09SEwan Crawford     // Check if the target allocation and file both have the same integral type
1867*8b244e21SEwan Crawford     const unsigned int type = static_cast<unsigned int>(*alloc->element.type.get());
186855232f09SEwan Crawford     if (type != head->type)
186955232f09SEwan Crawford     {
187055232f09SEwan Crawford         const char* file_type_cstr = AllocationDetails::RsDataTypeToString[head->type][0];
187155232f09SEwan Crawford         const char* alloc_type_cstr = AllocationDetails::RsDataTypeToString[type][0];
187255232f09SEwan Crawford 
187355232f09SEwan Crawford         strm.Printf("Warning: Mismatched Types - file '%s' type, allocation '%s' type",
187455232f09SEwan Crawford                     file_type_cstr, alloc_type_cstr);
187555232f09SEwan Crawford         strm.EOL();
187655232f09SEwan Crawford     }
187755232f09SEwan Crawford 
187855232f09SEwan Crawford     // Calculate size of allocation data in file
187955232f09SEwan Crawford     size_t length = data_sp->GetByteSize() - head->hdr_size;
188055232f09SEwan Crawford 
188155232f09SEwan Crawford     // Check if the target allocation and file both have the same total data size.
188255232f09SEwan Crawford     const unsigned int alloc_size = *alloc->size.get();
188355232f09SEwan Crawford     if (alloc_size != length)
188455232f09SEwan Crawford     {
188555232f09SEwan Crawford         strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64 " bytes, allocation 0x%x bytes",
1886eba832beSJason Molenda                     (uint64_t) length, alloc_size);
188755232f09SEwan Crawford         strm.EOL();
188855232f09SEwan Crawford         length = alloc_size < length ? alloc_size : length; // Set length to copy to minimum
188955232f09SEwan Crawford     }
189055232f09SEwan Crawford 
189155232f09SEwan Crawford     // Copy file data from our buffer into the target allocation.
189255232f09SEwan Crawford     lldb::addr_t alloc_data = *alloc->data_ptr.get();
189355232f09SEwan Crawford     Error error;
189455232f09SEwan Crawford     size_t bytes_written = GetProcess()->WriteMemory(alloc_data, file_buffer, length, error);
189555232f09SEwan Crawford     if (!error.Success() || bytes_written != length)
189655232f09SEwan Crawford     {
189755232f09SEwan Crawford         strm.Printf("Error: Couldn't write data to allocation %s", error.AsCString());
189855232f09SEwan Crawford         strm.EOL();
189955232f09SEwan Crawford         return false;
190055232f09SEwan Crawford     }
190155232f09SEwan Crawford 
190255232f09SEwan Crawford     strm.Printf("Contents of file '%s' read into allocation %u", filename, alloc->id);
190355232f09SEwan Crawford     strm.EOL();
190455232f09SEwan Crawford 
190555232f09SEwan Crawford     return true;
190655232f09SEwan Crawford }
190755232f09SEwan Crawford 
190855232f09SEwan Crawford // Function copies allocation contents into a binary file.
190955232f09SEwan Crawford // This file can then be loaded later into a different allocation.
191055232f09SEwan Crawford // There is a header, FileHeader, before the allocation data containing meta-data.
191155232f09SEwan Crawford bool
191255232f09SEwan Crawford RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr)
191355232f09SEwan Crawford {
191455232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
191555232f09SEwan Crawford 
191655232f09SEwan Crawford     // Find allocation with the given id
191755232f09SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, alloc_id);
191855232f09SEwan Crawford     if (!alloc)
191955232f09SEwan Crawford         return false;
192055232f09SEwan Crawford 
192155232f09SEwan Crawford     if (log)
192255232f09SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
192355232f09SEwan Crawford 
192455232f09SEwan Crawford      // JIT all the allocation details
1925*8b244e21SEwan Crawford     if (!alloc->data_ptr.isValid() || !alloc->element.type.isValid() || !alloc->element.type_vec_size.isValid()
1926*8b244e21SEwan Crawford         || !alloc->element.type_kind.isValid() || !alloc->dimension.isValid())
192755232f09SEwan Crawford     {
192855232f09SEwan Crawford         if (log)
192955232f09SEwan Crawford             log->Printf("RenderScriptRuntime::SaveAllocation - Allocation details not calculated yet, jitting info");
193055232f09SEwan Crawford 
193155232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
193255232f09SEwan Crawford         {
193355232f09SEwan Crawford             if (log)
193455232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::SaveAllocation - Couldn't JIT allocation details");
19354cfc9198SSylvestre Ledru             return false;
193655232f09SEwan Crawford         }
193755232f09SEwan Crawford     }
193855232f09SEwan Crawford 
1939*8b244e21SEwan Crawford     assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid() && alloc->element.datum_size.get()
1940*8b244e21SEwan Crawford            && alloc->element.type_kind.isValid() && alloc->dimension.isValid() && "Allocation information not available");
194155232f09SEwan Crawford 
194255232f09SEwan Crawford     // Check we can create writable file
194355232f09SEwan Crawford     FileSpec file_spec(filename, true);
194455232f09SEwan Crawford     File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionTruncate);
194555232f09SEwan Crawford     if (!file)
194655232f09SEwan Crawford     {
194755232f09SEwan Crawford         strm.Printf("Error: Failed to open '%s' for writing", filename);
194855232f09SEwan Crawford         strm.EOL();
194955232f09SEwan Crawford         return false;
195055232f09SEwan Crawford     }
195155232f09SEwan Crawford 
195255232f09SEwan Crawford     // Read allocation into buffer of heap memory
195355232f09SEwan Crawford     const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
195455232f09SEwan Crawford     if (!buffer)
195555232f09SEwan Crawford     {
195655232f09SEwan Crawford         strm.Printf("Error: Couldn't read allocation data into buffer");
195755232f09SEwan Crawford         strm.EOL();
195855232f09SEwan Crawford         return false;
195955232f09SEwan Crawford     }
196055232f09SEwan Crawford 
196155232f09SEwan Crawford     // Create the file header
196255232f09SEwan Crawford     AllocationDetails::FileHeader head;
196355232f09SEwan Crawford     head.ident[0] = 'R'; head.ident[1] = 'S'; head.ident[2] = 'A'; head.ident[3] = 'D';
196455232f09SEwan Crawford     head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader));
1965*8b244e21SEwan Crawford     head.type = static_cast<uint16_t>(*alloc->element.type.get());
1966*8b244e21SEwan Crawford     head.kind = static_cast<uint32_t>(*alloc->element.type_kind.get());
19672d62328aSEwan Crawford     head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
19682d62328aSEwan Crawford     head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
19692d62328aSEwan Crawford     head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
1970*8b244e21SEwan Crawford     head.element_size = static_cast<uint32_t>(*alloc->element.datum_size.get());
197155232f09SEwan Crawford 
197255232f09SEwan Crawford     // Write the file header
197355232f09SEwan Crawford     size_t num_bytes = sizeof(AllocationDetails::FileHeader);
197455232f09SEwan Crawford     Error err = file.Write(static_cast<const void*>(&head), num_bytes);
197555232f09SEwan Crawford     if (!err.Success())
197655232f09SEwan Crawford     {
197755232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
197855232f09SEwan Crawford         strm.EOL();
197955232f09SEwan Crawford         return false;
198055232f09SEwan Crawford     }
198155232f09SEwan Crawford 
198255232f09SEwan Crawford     // Write allocation data to file
198355232f09SEwan Crawford     num_bytes = static_cast<size_t>(*alloc->size.get());
198455232f09SEwan Crawford     if (log)
1985eba832beSJason Molenda         log->Printf("RenderScriptRuntime::SaveAllocation - Writing 0x%" PRIx64 " bytes from %p", (uint64_t) num_bytes, buffer.get());
198655232f09SEwan Crawford 
198755232f09SEwan Crawford     err = file.Write(buffer.get(), num_bytes);
198855232f09SEwan Crawford     if (!err.Success())
198955232f09SEwan Crawford     {
199055232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
199155232f09SEwan Crawford         strm.EOL();
199255232f09SEwan Crawford         return false;
199355232f09SEwan Crawford     }
199455232f09SEwan Crawford 
199555232f09SEwan Crawford     strm.Printf("Allocation written to file '%s'", filename);
199655232f09SEwan Crawford     strm.EOL();
199715f2bd95SEwan Crawford     return true;
199815f2bd95SEwan Crawford }
199915f2bd95SEwan Crawford 
20005ec532a9SColin Riley bool
20015ec532a9SColin Riley RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp)
20025ec532a9SColin Riley {
20034640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
20044640cde1SColin Riley 
20055ec532a9SColin Riley     if (module_sp)
20065ec532a9SColin Riley     {
20075ec532a9SColin Riley         for (const auto &rs_module : m_rsmodules)
20085ec532a9SColin Riley         {
20094640cde1SColin Riley             if (rs_module->m_module == module_sp)
20107dc7771cSEwan Crawford             {
20117dc7771cSEwan Crawford                 // Check if the user has enabled automatically breaking on
20127dc7771cSEwan Crawford                 // all RS kernels.
20137dc7771cSEwan Crawford                 if (m_breakAllKernels)
20147dc7771cSEwan Crawford                     BreakOnModuleKernels(rs_module);
20157dc7771cSEwan Crawford 
20165ec532a9SColin Riley                 return false;
20175ec532a9SColin Riley             }
20187dc7771cSEwan Crawford         }
2019ef20b08fSColin Riley         bool module_loaded = false;
2020ef20b08fSColin Riley         switch (GetModuleKind(module_sp))
2021ef20b08fSColin Riley         {
2022ef20b08fSColin Riley             case eModuleKindKernelObj:
2023ef20b08fSColin Riley             {
20244640cde1SColin Riley                 RSModuleDescriptorSP module_desc;
20254640cde1SColin Riley                 module_desc.reset(new RSModuleDescriptor(module_sp));
20264640cde1SColin Riley                 if (module_desc->ParseRSInfo())
20275ec532a9SColin Riley                 {
20285ec532a9SColin Riley                     m_rsmodules.push_back(module_desc);
2029ef20b08fSColin Riley                     module_loaded = true;
20305ec532a9SColin Riley                 }
20314640cde1SColin Riley                 if (module_loaded)
20324640cde1SColin Riley                 {
20334640cde1SColin Riley                     FixupScriptDetails(module_desc);
20344640cde1SColin Riley                 }
2035ef20b08fSColin Riley                 break;
2036ef20b08fSColin Riley             }
2037ef20b08fSColin Riley             case eModuleKindDriver:
20384640cde1SColin Riley             {
20394640cde1SColin Riley                 if (!m_libRSDriver)
20404640cde1SColin Riley                 {
20414640cde1SColin Riley                     m_libRSDriver = module_sp;
20424640cde1SColin Riley                     LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
20434640cde1SColin Riley                 }
20444640cde1SColin Riley                 break;
20454640cde1SColin Riley             }
2046ef20b08fSColin Riley             case eModuleKindImpl:
20474640cde1SColin Riley             {
20484640cde1SColin Riley                 m_libRSCpuRef = module_sp;
20494640cde1SColin Riley                 break;
20504640cde1SColin Riley             }
2051ef20b08fSColin Riley             case eModuleKindLibRS:
20524640cde1SColin Riley             {
20534640cde1SColin Riley                 if (!m_libRS)
20544640cde1SColin Riley                 {
20554640cde1SColin Riley                     m_libRS = module_sp;
20564640cde1SColin Riley                     static ConstString gDbgPresentStr("gDebuggerPresent");
20574640cde1SColin Riley                     const Symbol* debug_present = m_libRS->FindFirstSymbolWithNameAndType(gDbgPresentStr, eSymbolTypeData);
20584640cde1SColin Riley                     if (debug_present)
20594640cde1SColin Riley                     {
20604640cde1SColin Riley                         Error error;
20614640cde1SColin Riley                         uint32_t flag = 0x00000001U;
20624640cde1SColin Riley                         Target &target = GetProcess()->GetTarget();
2063358cf1eaSGreg Clayton                         addr_t addr = debug_present->GetLoadAddress(&target);
20644640cde1SColin Riley                         GetProcess()->WriteMemory(addr, &flag, sizeof(flag), error);
20654640cde1SColin Riley                         if(error.Success())
20664640cde1SColin Riley                         {
20674640cde1SColin Riley                             if (log)
20684640cde1SColin Riley                                 log->Printf ("RenderScriptRuntime::LoadModule - Debugger present flag set on debugee");
20694640cde1SColin Riley 
20704640cde1SColin Riley                             m_debuggerPresentFlagged = true;
20714640cde1SColin Riley                         }
20724640cde1SColin Riley                         else if (log)
20734640cde1SColin Riley                         {
20744640cde1SColin Riley                             log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags '%s' ", error.AsCString());
20754640cde1SColin Riley                         }
20764640cde1SColin Riley                     }
20774640cde1SColin Riley                     else if (log)
20784640cde1SColin Riley                     {
20794640cde1SColin Riley                         log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags - symbol not found");
20804640cde1SColin Riley                     }
20814640cde1SColin Riley                 }
20824640cde1SColin Riley                 break;
20834640cde1SColin Riley             }
2084ef20b08fSColin Riley             default:
2085ef20b08fSColin Riley                 break;
2086ef20b08fSColin Riley         }
2087ef20b08fSColin Riley         if (module_loaded)
2088ef20b08fSColin Riley             Update();
2089ef20b08fSColin Riley         return module_loaded;
20905ec532a9SColin Riley     }
20915ec532a9SColin Riley     return false;
20925ec532a9SColin Riley }
20935ec532a9SColin Riley 
2094ef20b08fSColin Riley void
2095ef20b08fSColin Riley RenderScriptRuntime::Update()
2096ef20b08fSColin Riley {
2097ef20b08fSColin Riley     if (m_rsmodules.size() > 0)
2098ef20b08fSColin Riley     {
2099ef20b08fSColin Riley         if (!m_initiated)
2100ef20b08fSColin Riley         {
2101ef20b08fSColin Riley             Initiate();
2102ef20b08fSColin Riley         }
2103ef20b08fSColin Riley     }
2104ef20b08fSColin Riley }
2105ef20b08fSColin Riley 
21065ec532a9SColin Riley // The maximum line length of an .rs.info packet
21075ec532a9SColin Riley #define MAXLINE 500
21085ec532a9SColin Riley 
21095ec532a9SColin Riley // The .rs.info symbol in renderscript modules contains a string which needs to be parsed.
21105ec532a9SColin Riley // The string is basic and is parsed on a line by line basis.
21115ec532a9SColin Riley bool
21125ec532a9SColin Riley RSModuleDescriptor::ParseRSInfo()
21135ec532a9SColin Riley {
21145ec532a9SColin Riley     const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
21155ec532a9SColin Riley     if (info_sym)
21165ec532a9SColin Riley     {
2117358cf1eaSGreg Clayton         const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
21185ec532a9SColin Riley         const addr_t size = info_sym->GetByteSize();
21195ec532a9SColin Riley         const FileSpec fs = m_module->GetFileSpec();
21205ec532a9SColin Riley 
21215ec532a9SColin Riley         DataBufferSP buffer = fs.ReadFileContents(addr, size);
21225ec532a9SColin Riley 
21235ec532a9SColin Riley         if (!buffer)
21245ec532a9SColin Riley             return false;
21255ec532a9SColin Riley 
21265ec532a9SColin Riley         std::string info((const char *)buffer->GetBytes());
21275ec532a9SColin Riley 
21285ec532a9SColin Riley         std::vector<std::string> info_lines;
2129e8433cc1SBruce Mitchener         size_t lpos = info.find('\n');
21305ec532a9SColin Riley         while (lpos != std::string::npos)
21315ec532a9SColin Riley         {
21325ec532a9SColin Riley             info_lines.push_back(info.substr(0, lpos));
21335ec532a9SColin Riley             info = info.substr(lpos + 1);
2134e8433cc1SBruce Mitchener             lpos = info.find('\n');
21355ec532a9SColin Riley         }
21365ec532a9SColin Riley         size_t offset = 0;
21375ec532a9SColin Riley         while (offset < info_lines.size())
21385ec532a9SColin Riley         {
21395ec532a9SColin Riley             std::string line = info_lines[offset];
21405ec532a9SColin Riley             // Parse directives
21415ec532a9SColin Riley             uint32_t numDefns = 0;
21425ec532a9SColin Riley             if (sscanf(line.c_str(), "exportVarCount: %u", &numDefns) == 1)
21435ec532a9SColin Riley             {
21445ec532a9SColin Riley                 while (numDefns--)
21454640cde1SColin Riley                     m_globals.push_back(RSGlobalDescriptor(this, info_lines[++offset].c_str()));
21465ec532a9SColin Riley             }
21475ec532a9SColin Riley             else if (sscanf(line.c_str(), "exportFuncCount: %u", &numDefns) == 1)
21485ec532a9SColin Riley             {
21495ec532a9SColin Riley             }
21505ec532a9SColin Riley             else if (sscanf(line.c_str(), "exportForEachCount: %u", &numDefns) == 1)
21515ec532a9SColin Riley             {
21525ec532a9SColin Riley                 char name[MAXLINE];
21535ec532a9SColin Riley                 while (numDefns--)
21545ec532a9SColin Riley                 {
21555ec532a9SColin Riley                     uint32_t slot = 0;
21565ec532a9SColin Riley                     name[0] = '\0';
21575ec532a9SColin Riley                     if (sscanf(info_lines[++offset].c_str(), "%u - %s", &slot, &name[0]) == 2)
21585ec532a9SColin Riley                     {
21594640cde1SColin Riley                         m_kernels.push_back(RSKernelDescriptor(this, name, slot));
21604640cde1SColin Riley                     }
21614640cde1SColin Riley                 }
21624640cde1SColin Riley             }
21634640cde1SColin Riley             else if (sscanf(line.c_str(), "pragmaCount: %u", &numDefns) == 1)
21644640cde1SColin Riley             {
21654640cde1SColin Riley                 char name[MAXLINE];
21664640cde1SColin Riley                 char value[MAXLINE];
21674640cde1SColin Riley                 while (numDefns--)
21684640cde1SColin Riley                 {
21694640cde1SColin Riley                     name[0] = '\0';
21704640cde1SColin Riley                     value[0] = '\0';
21714640cde1SColin Riley                     if (sscanf(info_lines[++offset].c_str(), "%s - %s", &name[0], &value[0]) != 0
21724640cde1SColin Riley                         && (name[0] != '\0'))
21734640cde1SColin Riley                     {
21744640cde1SColin Riley                         m_pragmas[std::string(name)] = value;
21755ec532a9SColin Riley                     }
21765ec532a9SColin Riley                 }
21775ec532a9SColin Riley             }
21785ec532a9SColin Riley             else if (sscanf(line.c_str(), "objectSlotCount: %u", &numDefns) == 1)
21795ec532a9SColin Riley             {
21805ec532a9SColin Riley             }
21815ec532a9SColin Riley 
21825ec532a9SColin Riley             offset++;
21835ec532a9SColin Riley         }
21845ec532a9SColin Riley         return m_kernels.size() > 0;
21855ec532a9SColin Riley     }
21865ec532a9SColin Riley     return false;
21875ec532a9SColin Riley }
21885ec532a9SColin Riley 
21895ec532a9SColin Riley bool
21905ec532a9SColin Riley RenderScriptRuntime::ProbeModules(const ModuleList module_list)
21915ec532a9SColin Riley {
21925ec532a9SColin Riley     bool rs_found = false;
21935ec532a9SColin Riley     size_t num_modules = module_list.GetSize();
21945ec532a9SColin Riley     for (size_t i = 0; i < num_modules; i++)
21955ec532a9SColin Riley     {
21965ec532a9SColin Riley         auto module = module_list.GetModuleAtIndex(i);
21975ec532a9SColin Riley         rs_found |= LoadModule(module);
21985ec532a9SColin Riley     }
21995ec532a9SColin Riley     return rs_found;
22005ec532a9SColin Riley }
22015ec532a9SColin Riley 
22025ec532a9SColin Riley void
22034640cde1SColin Riley RenderScriptRuntime::Status(Stream &strm) const
22044640cde1SColin Riley {
22054640cde1SColin Riley     if (m_libRS)
22064640cde1SColin Riley     {
22074640cde1SColin Riley         strm.Printf("Runtime Library discovered.");
22084640cde1SColin Riley         strm.EOL();
22094640cde1SColin Riley     }
22104640cde1SColin Riley     if (m_libRSDriver)
22114640cde1SColin Riley     {
22124640cde1SColin Riley         strm.Printf("Runtime Driver discovered.");
22134640cde1SColin Riley         strm.EOL();
22144640cde1SColin Riley     }
22154640cde1SColin Riley     if (m_libRSCpuRef)
22164640cde1SColin Riley     {
22174640cde1SColin Riley         strm.Printf("CPU Reference Implementation discovered.");
22184640cde1SColin Riley         strm.EOL();
22194640cde1SColin Riley     }
22204640cde1SColin Riley 
22214640cde1SColin Riley     if (m_runtimeHooks.size())
22224640cde1SColin Riley     {
22234640cde1SColin Riley         strm.Printf("Runtime functions hooked:");
22244640cde1SColin Riley         strm.EOL();
22254640cde1SColin Riley         for (auto b : m_runtimeHooks)
22264640cde1SColin Riley         {
22274640cde1SColin Riley             strm.Indent(b.second->defn->name);
22284640cde1SColin Riley             strm.EOL();
22294640cde1SColin Riley         }
22304640cde1SColin Riley         strm.EOL();
22314640cde1SColin Riley     }
22324640cde1SColin Riley     else
22334640cde1SColin Riley     {
22344640cde1SColin Riley         strm.Printf("Runtime is not hooked.");
22354640cde1SColin Riley         strm.EOL();
22364640cde1SColin Riley     }
22374640cde1SColin Riley }
22384640cde1SColin Riley 
22394640cde1SColin Riley void
22404640cde1SColin Riley RenderScriptRuntime::DumpContexts(Stream &strm) const
22414640cde1SColin Riley {
22424640cde1SColin Riley     strm.Printf("Inferred RenderScript Contexts:");
22434640cde1SColin Riley     strm.EOL();
22444640cde1SColin Riley     strm.IndentMore();
22454640cde1SColin Riley 
22464640cde1SColin Riley     std::map<addr_t, uint64_t> contextReferences;
22474640cde1SColin Riley 
224878f339d1SEwan Crawford     // Iterate over all of the currently discovered scripts.
224978f339d1SEwan Crawford     // Note: We cant push or pop from m_scripts inside this loop or it may invalidate script.
22504640cde1SColin Riley     for (const auto & script : m_scripts)
22514640cde1SColin Riley     {
225278f339d1SEwan Crawford         if (!script->context.isValid())
225378f339d1SEwan Crawford             continue;
225478f339d1SEwan Crawford         lldb::addr_t context = *script->context;
225578f339d1SEwan Crawford 
225678f339d1SEwan Crawford         if (contextReferences.find(context) != contextReferences.end())
22574640cde1SColin Riley         {
225878f339d1SEwan Crawford             contextReferences[context]++;
22594640cde1SColin Riley         }
22604640cde1SColin Riley         else
22614640cde1SColin Riley         {
226278f339d1SEwan Crawford             contextReferences[context] = 1;
22634640cde1SColin Riley         }
22644640cde1SColin Riley     }
22654640cde1SColin Riley 
22664640cde1SColin Riley     for (const auto& cRef : contextReferences)
22674640cde1SColin Riley     {
22684640cde1SColin Riley         strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances", cRef.first, cRef.second);
22694640cde1SColin Riley         strm.EOL();
22704640cde1SColin Riley     }
22714640cde1SColin Riley     strm.IndentLess();
22724640cde1SColin Riley }
22734640cde1SColin Riley 
22744640cde1SColin Riley void
22754640cde1SColin Riley RenderScriptRuntime::DumpKernels(Stream &strm) const
22764640cde1SColin Riley {
22774640cde1SColin Riley     strm.Printf("RenderScript Kernels:");
22784640cde1SColin Riley     strm.EOL();
22794640cde1SColin Riley     strm.IndentMore();
22804640cde1SColin Riley     for (const auto &module : m_rsmodules)
22814640cde1SColin Riley     {
22824640cde1SColin Riley         strm.Printf("Resource '%s':",module->m_resname.c_str());
22834640cde1SColin Riley         strm.EOL();
22844640cde1SColin Riley         for (const auto &kernel : module->m_kernels)
22854640cde1SColin Riley         {
22864640cde1SColin Riley             strm.Indent(kernel.m_name.AsCString());
22874640cde1SColin Riley             strm.EOL();
22884640cde1SColin Riley         }
22894640cde1SColin Riley     }
22904640cde1SColin Riley     strm.IndentLess();
22914640cde1SColin Riley }
22924640cde1SColin Riley 
2293a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails*
2294a0f08674SEwan Crawford RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id)
2295a0f08674SEwan Crawford {
2296a0f08674SEwan Crawford     AllocationDetails* alloc = nullptr;
2297a0f08674SEwan Crawford 
2298a0f08674SEwan Crawford     // See if we can find allocation using id as an index;
2299a0f08674SEwan Crawford     if (alloc_id <= m_allocations.size() && alloc_id != 0
2300a0f08674SEwan Crawford         && m_allocations[alloc_id-1]->id == alloc_id)
2301a0f08674SEwan Crawford     {
2302a0f08674SEwan Crawford         alloc = m_allocations[alloc_id-1].get();
2303a0f08674SEwan Crawford         return alloc;
2304a0f08674SEwan Crawford     }
2305a0f08674SEwan Crawford 
2306a0f08674SEwan Crawford     // Fallback to searching
2307a0f08674SEwan Crawford     for (const auto & a : m_allocations)
2308a0f08674SEwan Crawford     {
2309a0f08674SEwan Crawford        if (a->id == alloc_id)
2310a0f08674SEwan Crawford        {
2311a0f08674SEwan Crawford            alloc = a.get();
2312a0f08674SEwan Crawford            break;
2313a0f08674SEwan Crawford        }
2314a0f08674SEwan Crawford     }
2315a0f08674SEwan Crawford 
2316a0f08674SEwan Crawford     if (alloc == nullptr)
2317a0f08674SEwan Crawford     {
2318a0f08674SEwan Crawford         strm.Printf("Error: Couldn't find allocation with id matching %u", alloc_id);
2319a0f08674SEwan Crawford         strm.EOL();
2320a0f08674SEwan Crawford     }
2321a0f08674SEwan Crawford 
2322a0f08674SEwan Crawford     return alloc;
2323a0f08674SEwan Crawford }
2324a0f08674SEwan Crawford 
2325a0f08674SEwan Crawford // Prints the contents of an allocation to the output stream, which may be a file
2326a0f08674SEwan Crawford bool
2327a0f08674SEwan Crawford RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame* frame_ptr, const uint32_t id)
2328a0f08674SEwan Crawford {
2329a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2330a0f08674SEwan Crawford 
2331a0f08674SEwan Crawford     // Check we can find the desired allocation
2332a0f08674SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, id);
2333a0f08674SEwan Crawford     if (!alloc)
2334a0f08674SEwan Crawford         return false; // FindAllocByID() will print error message for us here
2335a0f08674SEwan Crawford 
2336a0f08674SEwan Crawford     if (log)
2337a0f08674SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
2338a0f08674SEwan Crawford 
2339a0f08674SEwan Crawford     // Check we have information about the allocation, if not calculate it
2340*8b244e21SEwan Crawford     if (!alloc->data_ptr.isValid() || !alloc->element.type.isValid() ||
2341*8b244e21SEwan Crawford         !alloc->element.type_vec_size.isValid() || !alloc->dimension.isValid() || !alloc->element.datum_size.isValid())
2342a0f08674SEwan Crawford     {
2343a0f08674SEwan Crawford         if (log)
2344a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::DumpAllocation - Allocation details not calculated yet, jitting info");
2345a0f08674SEwan Crawford 
2346a0f08674SEwan Crawford         // JIT all the allocation information
2347a0f08674SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
2348a0f08674SEwan Crawford         {
2349a0f08674SEwan Crawford             strm.Printf("Error: Couldn't JIT allocation details");
2350a0f08674SEwan Crawford             strm.EOL();
2351a0f08674SEwan Crawford             return false;
2352a0f08674SEwan Crawford         }
2353a0f08674SEwan Crawford     }
2354a0f08674SEwan Crawford 
2355a0f08674SEwan Crawford     // Establish format and size of each data element
2356*8b244e21SEwan Crawford     const unsigned int vec_size = *alloc->element.type_vec_size.get();
2357*8b244e21SEwan Crawford     const Element::DataType type = *alloc->element.type.get();
2358a0f08674SEwan Crawford 
2359*8b244e21SEwan Crawford     assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_BOOLEAN
2360a0f08674SEwan Crawford                                                    && "Invalid allocation type");
2361a0f08674SEwan Crawford 
2362a0f08674SEwan Crawford     lldb::Format format = vec_size == 1 ? static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatSingle])
2363a0f08674SEwan Crawford                                         : static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatVector]);
2364a0f08674SEwan Crawford 
2365*8b244e21SEwan Crawford     const unsigned int data_size = *alloc->element.datum_size.get();
2366a0f08674SEwan Crawford 
2367a0f08674SEwan Crawford     if (log)
2368*8b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - Element size %u bytes, including padding", data_size);
2369a0f08674SEwan Crawford 
237055232f09SEwan Crawford     // Allocate a buffer to copy data into
237155232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
237255232f09SEwan Crawford     if (!buffer)
237355232f09SEwan Crawford     {
237455232f09SEwan Crawford         strm.Printf("Error: Couldn't allocate a read allocation data into memory");
237555232f09SEwan Crawford         strm.EOL();
237655232f09SEwan Crawford         return false;
237755232f09SEwan Crawford     }
237855232f09SEwan Crawford 
2379a0f08674SEwan Crawford     // Calculate stride between rows as there may be padding at end of rows since
2380a0f08674SEwan Crawford     // allocated memory is 16-byte aligned
2381a0f08674SEwan Crawford     if (!alloc->stride.isValid())
2382a0f08674SEwan Crawford     {
2383a0f08674SEwan Crawford         if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
2384a0f08674SEwan Crawford             alloc->stride = 0;
2385a0f08674SEwan Crawford         else if (!JITAllocationStride(alloc, frame_ptr))
2386a0f08674SEwan Crawford         {
2387a0f08674SEwan Crawford             strm.Printf("Error: Couldn't calculate allocation row stride");
2388a0f08674SEwan Crawford             strm.EOL();
2389a0f08674SEwan Crawford             return false;
2390a0f08674SEwan Crawford         }
2391a0f08674SEwan Crawford     }
2392a0f08674SEwan Crawford     const unsigned int stride = *alloc->stride.get();
2393*8b244e21SEwan Crawford     const unsigned int size = *alloc->size.get(); // Size of whole allocation
2394*8b244e21SEwan Crawford     const unsigned int padding = alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
2395a0f08674SEwan Crawford     if (log)
2396*8b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - stride %u bytes, size %u bytes, padding %u", stride, size, padding);
2397a0f08674SEwan Crawford 
2398a0f08674SEwan Crawford     // Find dimensions used to index loops, so need to be non-zero
2399a0f08674SEwan Crawford     unsigned int dim_x = alloc->dimension.get()->dim_1;
2400a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 1 : dim_x;
2401a0f08674SEwan Crawford 
2402a0f08674SEwan Crawford     unsigned int dim_y = alloc->dimension.get()->dim_2;
2403a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 1 : dim_y;
2404a0f08674SEwan Crawford 
2405a0f08674SEwan Crawford     unsigned int dim_z = alloc->dimension.get()->dim_3;
2406a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 1 : dim_z;
2407a0f08674SEwan Crawford 
240855232f09SEwan Crawford     // Use data extractor to format output
240955232f09SEwan Crawford     const uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
241055232f09SEwan Crawford     DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(), archByteSize);
241155232f09SEwan Crawford 
2412a0f08674SEwan Crawford     unsigned int offset = 0;   // Offset in buffer to next element to be printed
2413a0f08674SEwan Crawford     unsigned int prev_row = 0; // Offset to the start of the previous row
2414a0f08674SEwan Crawford 
2415a0f08674SEwan Crawford     // Iterate over allocation dimensions, printing results to user
2416a0f08674SEwan Crawford     strm.Printf("Data (X, Y, Z):");
2417a0f08674SEwan Crawford     for (unsigned int z = 0; z < dim_z; ++z)
2418a0f08674SEwan Crawford     {
2419a0f08674SEwan Crawford         for (unsigned int y = 0; y < dim_y; ++y)
2420a0f08674SEwan Crawford         {
2421a0f08674SEwan Crawford             // Use stride to index start of next row.
2422a0f08674SEwan Crawford             if (!(y==0 && z==0))
2423a0f08674SEwan Crawford                 offset = prev_row + stride;
2424a0f08674SEwan Crawford             prev_row = offset;
2425a0f08674SEwan Crawford 
2426a0f08674SEwan Crawford             // Print each element in the row individually
2427a0f08674SEwan Crawford             for (unsigned int x = 0; x < dim_x; ++x)
2428a0f08674SEwan Crawford             {
2429a0f08674SEwan Crawford                 strm.Printf("\n(%u, %u, %u) = ", x, y, z);
2430*8b244e21SEwan Crawford                 if ((type == Element::RS_TYPE_NONE) && (alloc->element.children.size() > 0) &&
2431*8b244e21SEwan Crawford                     (alloc->element.type_name != Element::FallbackStructName))
2432*8b244e21SEwan Crawford                 {
2433*8b244e21SEwan Crawford                     // Here we are dumping an Element of struct type.
2434*8b244e21SEwan Crawford                     // This is done using expression evaluation with the name of the struct type and pointer to element.
2435*8b244e21SEwan Crawford 
2436*8b244e21SEwan Crawford                     // Don't print the name of the resulting expression, since this will be '$[0-9]+'
2437*8b244e21SEwan Crawford                     DumpValueObjectOptions expr_options;
2438*8b244e21SEwan Crawford                     expr_options.SetHideName(true);
2439*8b244e21SEwan Crawford 
2440*8b244e21SEwan Crawford                     // Setup expression as derefrencing a pointer cast to element address.
2441*8b244e21SEwan Crawford                     const int max_expr_size = 512;
2442*8b244e21SEwan Crawford                     char expr_char_buffer[max_expr_size];
2443*8b244e21SEwan Crawford                     int chars_written = snprintf(expr_char_buffer, max_expr_size, "*(%s*) 0x%" PRIx64,
2444*8b244e21SEwan Crawford                                         alloc->element.type_name.AsCString(), *alloc->data_ptr.get() + offset);
2445*8b244e21SEwan Crawford 
2446*8b244e21SEwan Crawford                     if (chars_written < 0 || chars_written >= max_expr_size)
2447*8b244e21SEwan Crawford                     {
2448*8b244e21SEwan Crawford                         if (log)
2449*8b244e21SEwan Crawford                             log->Printf("RenderScriptRuntime::DumpAllocation- Error in snprintf()");
2450*8b244e21SEwan Crawford                         continue;
2451*8b244e21SEwan Crawford                     }
2452*8b244e21SEwan Crawford 
2453*8b244e21SEwan Crawford                     // Evaluate expression
2454*8b244e21SEwan Crawford                     ValueObjectSP expr_result;
2455*8b244e21SEwan Crawford                     GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer, frame_ptr, expr_result);
2456*8b244e21SEwan Crawford 
2457*8b244e21SEwan Crawford                     // Print the results to our stream.
2458*8b244e21SEwan Crawford                     expr_result->Dump(strm, expr_options);
2459*8b244e21SEwan Crawford                 }
2460*8b244e21SEwan Crawford                 else
2461*8b244e21SEwan Crawford                 {
2462*8b244e21SEwan Crawford                     alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0, 0);
2463*8b244e21SEwan Crawford                 }
2464*8b244e21SEwan Crawford                 offset += data_size;
2465a0f08674SEwan Crawford             }
2466a0f08674SEwan Crawford         }
2467a0f08674SEwan Crawford     }
2468a0f08674SEwan Crawford     strm.EOL();
2469a0f08674SEwan Crawford 
2470a0f08674SEwan Crawford     return true;
2471a0f08674SEwan Crawford }
2472a0f08674SEwan Crawford 
247315f2bd95SEwan Crawford // Prints infomation regarding all the currently loaded allocations.
247415f2bd95SEwan Crawford // These details are gathered by jitting the runtime, which has as latency.
247515f2bd95SEwan Crawford void
247615f2bd95SEwan Crawford RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame* frame_ptr, bool recompute)
247715f2bd95SEwan Crawford {
247815f2bd95SEwan Crawford     strm.Printf("RenderScript Allocations:");
247915f2bd95SEwan Crawford     strm.EOL();
248015f2bd95SEwan Crawford     strm.IndentMore();
248115f2bd95SEwan Crawford 
248215f2bd95SEwan Crawford     for (auto &alloc : m_allocations)
248315f2bd95SEwan Crawford     {
248415f2bd95SEwan Crawford         // JIT the allocation info if we haven't done it, or the user forces us to.
248515f2bd95SEwan Crawford         bool do_refresh = !alloc->data_ptr.isValid() || recompute;
248615f2bd95SEwan Crawford 
248715f2bd95SEwan Crawford         // JIT current allocation information
248815f2bd95SEwan Crawford         if (do_refresh && !RefreshAllocation(alloc.get(), frame_ptr))
248915f2bd95SEwan Crawford         {
249015f2bd95SEwan Crawford             strm.Printf("Error: Couldn't evaluate details for allocation %u\n", alloc->id);
249115f2bd95SEwan Crawford             continue;
249215f2bd95SEwan Crawford         }
249315f2bd95SEwan Crawford 
249415f2bd95SEwan Crawford         strm.Printf("%u:\n",alloc->id);
249515f2bd95SEwan Crawford         strm.IndentMore();
249615f2bd95SEwan Crawford 
249715f2bd95SEwan Crawford         strm.Indent("Context: ");
249815f2bd95SEwan Crawford         if (!alloc->context.isValid())
249915f2bd95SEwan Crawford             strm.Printf("unknown\n");
250015f2bd95SEwan Crawford         else
250115f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
250215f2bd95SEwan Crawford 
250315f2bd95SEwan Crawford         strm.Indent("Address: ");
250415f2bd95SEwan Crawford         if (!alloc->address.isValid())
250515f2bd95SEwan Crawford             strm.Printf("unknown\n");
250615f2bd95SEwan Crawford         else
250715f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
250815f2bd95SEwan Crawford 
250915f2bd95SEwan Crawford         strm.Indent("Data pointer: ");
251015f2bd95SEwan Crawford         if (!alloc->data_ptr.isValid())
251115f2bd95SEwan Crawford             strm.Printf("unknown\n");
251215f2bd95SEwan Crawford         else
251315f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
251415f2bd95SEwan Crawford 
251515f2bd95SEwan Crawford         strm.Indent("Dimensions: ");
251615f2bd95SEwan Crawford         if (!alloc->dimension.isValid())
251715f2bd95SEwan Crawford             strm.Printf("unknown\n");
251815f2bd95SEwan Crawford         else
251915f2bd95SEwan Crawford             strm.Printf("(%d, %d, %d)\n", alloc->dimension.get()->dim_1,
252015f2bd95SEwan Crawford                                           alloc->dimension.get()->dim_2,
252115f2bd95SEwan Crawford                                           alloc->dimension.get()->dim_3);
252215f2bd95SEwan Crawford 
252315f2bd95SEwan Crawford         strm.Indent("Data Type: ");
2524*8b244e21SEwan Crawford         if (!alloc->element.type.isValid() || !alloc->element.type_vec_size.isValid())
252515f2bd95SEwan Crawford             strm.Printf("unknown\n");
252615f2bd95SEwan Crawford         else
252715f2bd95SEwan Crawford         {
2528*8b244e21SEwan Crawford             const int vector_size = *alloc->element.type_vec_size.get();
2529*8b244e21SEwan Crawford             const Element::DataType type = *alloc->element.type.get();
253015f2bd95SEwan Crawford 
2531*8b244e21SEwan Crawford             if (!alloc->element.type_name.IsEmpty())
2532*8b244e21SEwan Crawford                 strm.Printf("%s\n", alloc->element.type_name.AsCString());
2533*8b244e21SEwan Crawford             else if (vector_size > 4 || vector_size < 1 ||
2534*8b244e21SEwan Crawford                 type < Element::RS_TYPE_NONE || type > Element::RS_TYPE_BOOLEAN)
253515f2bd95SEwan Crawford                 strm.Printf("invalid type\n");
253615f2bd95SEwan Crawford             else
253715f2bd95SEwan Crawford                 strm.Printf("%s\n", AllocationDetails::RsDataTypeToString[static_cast<unsigned int>(type)][vector_size-1]);
253815f2bd95SEwan Crawford         }
253915f2bd95SEwan Crawford 
254015f2bd95SEwan Crawford         strm.Indent("Data Kind: ");
2541*8b244e21SEwan Crawford         if (!alloc->element.type_kind.isValid())
254215f2bd95SEwan Crawford             strm.Printf("unknown\n");
254315f2bd95SEwan Crawford         else
254415f2bd95SEwan Crawford         {
2545*8b244e21SEwan Crawford             const Element::DataKind kind = *alloc->element.type_kind.get();
2546*8b244e21SEwan Crawford             if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
254715f2bd95SEwan Crawford                 strm.Printf("invalid kind\n");
254815f2bd95SEwan Crawford             else
254915f2bd95SEwan Crawford                 strm.Printf("%s\n", AllocationDetails::RsDataKindToString[static_cast<unsigned int>(kind)]);
255015f2bd95SEwan Crawford         }
255115f2bd95SEwan Crawford 
255215f2bd95SEwan Crawford         strm.EOL();
255315f2bd95SEwan Crawford         strm.IndentLess();
255415f2bd95SEwan Crawford     }
255515f2bd95SEwan Crawford     strm.IndentLess();
255615f2bd95SEwan Crawford }
255715f2bd95SEwan Crawford 
25587dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
25597dc7771cSEwan Crawford void
25607dc7771cSEwan Crawford RenderScriptRuntime::BreakOnModuleKernels(const RSModuleDescriptorSP rsmodule_sp)
25617dc7771cSEwan Crawford {
25627dc7771cSEwan Crawford     for (const auto &kernel : rsmodule_sp->m_kernels)
25637dc7771cSEwan Crawford     {
25647dc7771cSEwan Crawford         // Don't set breakpoint on 'root' kernel
25657dc7771cSEwan Crawford         if (strcmp(kernel.m_name.AsCString(), "root") == 0)
25667dc7771cSEwan Crawford             continue;
25677dc7771cSEwan Crawford 
25687dc7771cSEwan Crawford         CreateKernelBreakpoint(kernel.m_name);
25697dc7771cSEwan Crawford     }
25707dc7771cSEwan Crawford }
25717dc7771cSEwan Crawford 
25727dc7771cSEwan Crawford // Method is internally called by the 'kernel breakpoint all' command to
25737dc7771cSEwan Crawford // enable or disable breaking on all kernels.
25747dc7771cSEwan Crawford //
25757dc7771cSEwan Crawford // When do_break is true we want to enable this functionality.
25767dc7771cSEwan Crawford // When do_break is false we want to disable it.
25777dc7771cSEwan Crawford void
25787dc7771cSEwan Crawford RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target)
25797dc7771cSEwan Crawford {
258054782db7SEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
25817dc7771cSEwan Crawford 
25827dc7771cSEwan Crawford     InitSearchFilter(target);
25837dc7771cSEwan Crawford 
25847dc7771cSEwan Crawford     // Set breakpoints on all the kernels
25857dc7771cSEwan Crawford     if (do_break && !m_breakAllKernels)
25867dc7771cSEwan Crawford     {
25877dc7771cSEwan Crawford         m_breakAllKernels = true;
25887dc7771cSEwan Crawford 
25897dc7771cSEwan Crawford         for (const auto &module : m_rsmodules)
25907dc7771cSEwan Crawford             BreakOnModuleKernels(module);
25917dc7771cSEwan Crawford 
25927dc7771cSEwan Crawford         if (log)
25937dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::SetBreakAllKernels(True)"
25947dc7771cSEwan Crawford                         "- breakpoints set on all currently loaded kernels");
25957dc7771cSEwan Crawford     }
25967dc7771cSEwan Crawford     else if (!do_break && m_breakAllKernels) // Breakpoints won't be set on any new kernels.
25977dc7771cSEwan Crawford     {
25987dc7771cSEwan Crawford         m_breakAllKernels = false;
25997dc7771cSEwan Crawford 
26007dc7771cSEwan Crawford         if (log)
26017dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::SetBreakAllKernels(False) - breakpoints no longer automatically set");
26027dc7771cSEwan Crawford     }
26037dc7771cSEwan Crawford }
26047dc7771cSEwan Crawford 
26057dc7771cSEwan Crawford // Given the name of a kernel this function creates a breakpoint using our
26067dc7771cSEwan Crawford // own breakpoint resolver, and returns the Breakpoint shared pointer.
26077dc7771cSEwan Crawford BreakpointSP
26087dc7771cSEwan Crawford RenderScriptRuntime::CreateKernelBreakpoint(const ConstString& name)
26097dc7771cSEwan Crawford {
261054782db7SEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
26117dc7771cSEwan Crawford 
26127dc7771cSEwan Crawford     if (!m_filtersp)
26137dc7771cSEwan Crawford     {
26147dc7771cSEwan Crawford         if (log)
26157dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::CreateKernelBreakpoint - Error: No breakpoint search filter set");
26167dc7771cSEwan Crawford         return nullptr;
26177dc7771cSEwan Crawford     }
26187dc7771cSEwan Crawford 
26197dc7771cSEwan Crawford     BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
26207dc7771cSEwan Crawford     BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(m_filtersp, resolver_sp, false, false, false);
26217dc7771cSEwan Crawford 
262254782db7SEwan Crawford     // Give RS breakpoints a specific name, so the user can manipulate them as a group.
262354782db7SEwan Crawford     Error err;
262454782db7SEwan Crawford     if (!bp->AddName("RenderScriptKernel", err) && log)
262554782db7SEwan Crawford         log->Printf("RenderScriptRuntime::CreateKernelBreakpoint: Error setting break name, %s", err.AsCString());
262654782db7SEwan Crawford 
26277dc7771cSEwan Crawford     return bp;
26287dc7771cSEwan Crawford }
26297dc7771cSEwan Crawford 
2630018f5a7eSEwan Crawford // Given an expression for a variable this function tries to calculate the variable's value.
2631018f5a7eSEwan Crawford // If this is possible it returns true and sets the uint64_t parameter to the variables unsigned value.
2632018f5a7eSEwan Crawford // Otherwise function returns false.
2633018f5a7eSEwan Crawford bool
2634018f5a7eSEwan Crawford RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp, const char* var_name, uint64_t& val)
2635018f5a7eSEwan Crawford {
2636018f5a7eSEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2637018f5a7eSEwan Crawford     Error error;
2638018f5a7eSEwan Crawford     VariableSP var_sp;
2639018f5a7eSEwan Crawford 
2640018f5a7eSEwan Crawford     // Find variable in stack frame
2641018f5a7eSEwan Crawford     ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(var_name,
2642018f5a7eSEwan Crawford                                                                        eNoDynamicValues,
2643018f5a7eSEwan Crawford                                                                        StackFrame::eExpressionPathOptionCheckPtrVsMember |
2644018f5a7eSEwan Crawford                                                                        StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
2645018f5a7eSEwan Crawford                                                                        var_sp,
2646018f5a7eSEwan Crawford                                                                        error));
2647018f5a7eSEwan Crawford     if (!error.Success())
2648018f5a7eSEwan Crawford     {
2649018f5a7eSEwan Crawford         if (log)
2650018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't find '%s' in frame", var_name);
2651018f5a7eSEwan Crawford 
2652018f5a7eSEwan Crawford         return false;
2653018f5a7eSEwan Crawford     }
2654018f5a7eSEwan Crawford 
2655018f5a7eSEwan Crawford     // Find the unsigned int value for the variable
2656018f5a7eSEwan Crawford     bool success = false;
2657018f5a7eSEwan Crawford     val = value_sp->GetValueAsUnsigned(0, &success);
2658018f5a7eSEwan Crawford     if (!success)
2659018f5a7eSEwan Crawford     {
2660018f5a7eSEwan Crawford         if (log)
2661018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't parse '%s' as an unsigned int", var_name);
2662018f5a7eSEwan Crawford 
2663018f5a7eSEwan Crawford         return false;
2664018f5a7eSEwan Crawford     }
2665018f5a7eSEwan Crawford 
2666018f5a7eSEwan Crawford     return true;
2667018f5a7eSEwan Crawford }
2668018f5a7eSEwan Crawford 
2669018f5a7eSEwan Crawford // Callback when a kernel breakpoint hits and we're looking for a specific coordinate.
2670018f5a7eSEwan Crawford // Baton parameter contains a pointer to the target coordinate we want to break on.
2671018f5a7eSEwan Crawford // Function then checks the .expand frame for the current coordinate and breaks to user if it matches.
2672018f5a7eSEwan Crawford // Parameter 'break_id' is the id of the Breakpoint which made the callback.
2673018f5a7eSEwan Crawford // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
2674018f5a7eSEwan Crawford // a single logical breakpoint can have multiple addresses.
2675018f5a7eSEwan Crawford bool
2676018f5a7eSEwan Crawford RenderScriptRuntime::KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx,
2677018f5a7eSEwan Crawford                                          user_id_t break_id, user_id_t break_loc_id)
2678018f5a7eSEwan Crawford {
2679018f5a7eSEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
2680018f5a7eSEwan Crawford 
2681018f5a7eSEwan Crawford     assert(baton && "Error: null baton in conditional kernel breakpoint callback");
2682018f5a7eSEwan Crawford 
2683018f5a7eSEwan Crawford     // Coordinate we want to stop on
2684018f5a7eSEwan Crawford     const int* target_coord = static_cast<const int*>(baton);
2685018f5a7eSEwan Crawford 
2686018f5a7eSEwan Crawford     if (log)
2687018f5a7eSEwan Crawford         log->Printf("RenderScriptRuntime::KernelBreakpointHit - Break ID %" PRIu64 ", target coord (%d, %d, %d)",
2688018f5a7eSEwan Crawford                     break_id, target_coord[0], target_coord[1], target_coord[2]);
2689018f5a7eSEwan Crawford 
2690018f5a7eSEwan Crawford     // Go up one stack frame to .expand kernel
2691018f5a7eSEwan Crawford     ExecutionContext context(ctx->exe_ctx_ref);
2692018f5a7eSEwan Crawford     ThreadSP thread_sp = context.GetThreadSP();
2693018f5a7eSEwan Crawford     if (!thread_sp->SetSelectedFrameByIndex(1))
2694018f5a7eSEwan Crawford     {
2695018f5a7eSEwan Crawford         if (log)
2696018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't go up stack frame");
2697018f5a7eSEwan Crawford 
2698018f5a7eSEwan Crawford        return false;
2699018f5a7eSEwan Crawford     }
2700018f5a7eSEwan Crawford 
2701018f5a7eSEwan Crawford     StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
2702018f5a7eSEwan Crawford     if (!frame_sp)
2703018f5a7eSEwan Crawford     {
2704018f5a7eSEwan Crawford         if (log)
2705018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't select .expand stack frame");
2706018f5a7eSEwan Crawford 
2707018f5a7eSEwan Crawford         return false;
2708018f5a7eSEwan Crawford     }
2709018f5a7eSEwan Crawford 
2710018f5a7eSEwan Crawford     // Get values for variables in .expand frame that tell us the current kernel invocation
2711018f5a7eSEwan Crawford     const char* coord_expressions[] = {"rsIndex", "p->current.y", "p->current.z"};
2712018f5a7eSEwan Crawford     uint64_t current_coord[3] = {0, 0, 0};
2713018f5a7eSEwan Crawford 
2714018f5a7eSEwan Crawford     for(int i = 0; i < 3; ++i)
2715018f5a7eSEwan Crawford     {
2716018f5a7eSEwan Crawford         if (!GetFrameVarAsUnsigned(frame_sp, coord_expressions[i], current_coord[i]))
2717018f5a7eSEwan Crawford             return false;
2718018f5a7eSEwan Crawford 
2719018f5a7eSEwan Crawford         if (log)
2720018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit, %s = %" PRIu64, coord_expressions[i], current_coord[i]);
2721018f5a7eSEwan Crawford     }
2722018f5a7eSEwan Crawford 
2723018f5a7eSEwan Crawford     // Check if the current kernel invocation coordinate matches our target coordinate
2724018f5a7eSEwan Crawford     if (current_coord[0] == static_cast<uint64_t>(target_coord[0]) &&
2725018f5a7eSEwan Crawford         current_coord[1] == static_cast<uint64_t>(target_coord[1]) &&
2726018f5a7eSEwan Crawford         current_coord[2] == static_cast<uint64_t>(target_coord[2]))
2727018f5a7eSEwan Crawford     {
2728018f5a7eSEwan Crawford         if (log)
2729018f5a7eSEwan Crawford              log->Printf("RenderScriptRuntime::KernelBreakpointHit, BREAKING %" PRIu64 ", %" PRIu64 ", %" PRIu64,
2730018f5a7eSEwan Crawford                          current_coord[0], current_coord[1], current_coord[2]);
2731018f5a7eSEwan Crawford 
2732018f5a7eSEwan Crawford         BreakpointSP breakpoint_sp = context.GetTargetPtr()->GetBreakpointByID(break_id);
2733018f5a7eSEwan Crawford         assert(breakpoint_sp != nullptr && "Error: Couldn't find breakpoint matching break id for callback");
2734018f5a7eSEwan Crawford         breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint should only be hit once.
2735018f5a7eSEwan Crawford         return true;
2736018f5a7eSEwan Crawford     }
2737018f5a7eSEwan Crawford 
2738018f5a7eSEwan Crawford     // No match on coordinate
2739018f5a7eSEwan Crawford     return false;
2740018f5a7eSEwan Crawford }
2741018f5a7eSEwan Crawford 
2742018f5a7eSEwan Crawford // Tries to set a breakpoint on the start of a kernel, resolved using the kernel name.
2743018f5a7eSEwan Crawford // Argument 'coords', represents a three dimensional coordinate which can be used to specify
2744018f5a7eSEwan Crawford // a single kernel instance to break on. If this is set then we add a callback to the breakpoint.
27454640cde1SColin Riley void
2746018f5a7eSEwan Crawford RenderScriptRuntime::PlaceBreakpointOnKernel(Stream &strm, const char* name, const std::array<int,3> coords,
2747018f5a7eSEwan Crawford                                              Error& error, TargetSP target)
27484640cde1SColin Riley {
27494640cde1SColin Riley     if (!name)
27504640cde1SColin Riley     {
27514640cde1SColin Riley         error.SetErrorString("invalid kernel name");
27524640cde1SColin Riley         return;
27534640cde1SColin Riley     }
27544640cde1SColin Riley 
27557dc7771cSEwan Crawford     InitSearchFilter(target);
275698156583SEwan Crawford 
27574640cde1SColin Riley     ConstString kernel_name(name);
27587dc7771cSEwan Crawford     BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
2759018f5a7eSEwan Crawford 
2760018f5a7eSEwan Crawford     // We have a conditional breakpoint on a specific coordinate
2761018f5a7eSEwan Crawford     if (coords[0] != -1)
2762018f5a7eSEwan Crawford     {
2763018f5a7eSEwan Crawford         strm.Printf("Conditional kernel breakpoint on coordinate %d, %d, %d", coords[0], coords[1], coords[2]);
2764018f5a7eSEwan Crawford         strm.EOL();
2765018f5a7eSEwan Crawford 
2766018f5a7eSEwan Crawford         // Allocate memory for the baton, and copy over coordinate
2767018f5a7eSEwan Crawford         int* baton = new int[3];
2768018f5a7eSEwan Crawford         baton[0] = coords[0]; baton[1] = coords[1]; baton[2] = coords[2];
2769018f5a7eSEwan Crawford 
2770018f5a7eSEwan Crawford         // Create a callback that will be invoked everytime the breakpoint is hit.
2771018f5a7eSEwan Crawford         // The baton object passed to the handler is the target coordinate we want to break on.
2772018f5a7eSEwan Crawford         bp->SetCallback(KernelBreakpointHit, baton, true);
2773018f5a7eSEwan Crawford 
2774018f5a7eSEwan Crawford         // Store a shared pointer to the baton, so the memory will eventually be cleaned up after destruction
2775018f5a7eSEwan Crawford         m_conditional_breaks[bp->GetID()] = std::shared_ptr<int>(baton);
2776018f5a7eSEwan Crawford     }
2777018f5a7eSEwan Crawford 
277898156583SEwan Crawford     if (bp)
277998156583SEwan Crawford         bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
27804640cde1SColin Riley }
27814640cde1SColin Riley 
27824640cde1SColin Riley void
27835ec532a9SColin Riley RenderScriptRuntime::DumpModules(Stream &strm) const
27845ec532a9SColin Riley {
27855ec532a9SColin Riley     strm.Printf("RenderScript Modules:");
27865ec532a9SColin Riley     strm.EOL();
27875ec532a9SColin Riley     strm.IndentMore();
27885ec532a9SColin Riley     for (const auto &module : m_rsmodules)
27895ec532a9SColin Riley     {
27904640cde1SColin Riley         module->Dump(strm);
27915ec532a9SColin Riley     }
27925ec532a9SColin Riley     strm.IndentLess();
27935ec532a9SColin Riley }
27945ec532a9SColin Riley 
279578f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails*
279678f339d1SEwan Crawford RenderScriptRuntime::LookUpScript(addr_t address, bool create)
279778f339d1SEwan Crawford {
279878f339d1SEwan Crawford     for (const auto & s : m_scripts)
279978f339d1SEwan Crawford     {
280078f339d1SEwan Crawford         if (s->script.isValid())
280178f339d1SEwan Crawford             if (*s->script == address)
280278f339d1SEwan Crawford                 return s.get();
280378f339d1SEwan Crawford     }
280478f339d1SEwan Crawford     if (create)
280578f339d1SEwan Crawford     {
280678f339d1SEwan Crawford         std::unique_ptr<ScriptDetails> s(new ScriptDetails);
280778f339d1SEwan Crawford         s->script = address;
280878f339d1SEwan Crawford         m_scripts.push_back(std::move(s));
2809d10ca9deSEwan Crawford         return m_scripts.back().get();
281078f339d1SEwan Crawford     }
281178f339d1SEwan Crawford     return nullptr;
281278f339d1SEwan Crawford }
281378f339d1SEwan Crawford 
281478f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails*
281578f339d1SEwan Crawford RenderScriptRuntime::LookUpAllocation(addr_t address, bool create)
281678f339d1SEwan Crawford {
281778f339d1SEwan Crawford     for (const auto & a : m_allocations)
281878f339d1SEwan Crawford     {
281978f339d1SEwan Crawford         if (a->address.isValid())
282078f339d1SEwan Crawford             if (*a->address == address)
282178f339d1SEwan Crawford                 return a.get();
282278f339d1SEwan Crawford     }
282378f339d1SEwan Crawford     if (create)
282478f339d1SEwan Crawford     {
282578f339d1SEwan Crawford         std::unique_ptr<AllocationDetails> a(new AllocationDetails);
282678f339d1SEwan Crawford         a->address = address;
282778f339d1SEwan Crawford         m_allocations.push_back(std::move(a));
2828d10ca9deSEwan Crawford         return m_allocations.back().get();
282978f339d1SEwan Crawford     }
283078f339d1SEwan Crawford     return nullptr;
283178f339d1SEwan Crawford }
283278f339d1SEwan Crawford 
28335ec532a9SColin Riley void
28345ec532a9SColin Riley RSModuleDescriptor::Dump(Stream &strm) const
28355ec532a9SColin Riley {
28365ec532a9SColin Riley     strm.Indent();
28375ec532a9SColin Riley     m_module->GetFileSpec().Dump(&strm);
28384640cde1SColin Riley     if(m_module->GetNumCompileUnits())
28394640cde1SColin Riley     {
28404640cde1SColin Riley         strm.Indent("Debug info loaded.");
28414640cde1SColin Riley     }
28424640cde1SColin Riley     else
28434640cde1SColin Riley     {
28444640cde1SColin Riley         strm.Indent("Debug info does not exist.");
28454640cde1SColin Riley     }
28465ec532a9SColin Riley     strm.EOL();
28475ec532a9SColin Riley     strm.IndentMore();
28485ec532a9SColin Riley     strm.Indent();
2849189598edSColin Riley     strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
28505ec532a9SColin Riley     strm.EOL();
28515ec532a9SColin Riley     strm.IndentMore();
28525ec532a9SColin Riley     for (const auto &global : m_globals)
28535ec532a9SColin Riley     {
28545ec532a9SColin Riley         global.Dump(strm);
28555ec532a9SColin Riley     }
28565ec532a9SColin Riley     strm.IndentLess();
28575ec532a9SColin Riley     strm.Indent();
2858189598edSColin Riley     strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
28595ec532a9SColin Riley     strm.EOL();
28605ec532a9SColin Riley     strm.IndentMore();
28615ec532a9SColin Riley     for (const auto &kernel : m_kernels)
28625ec532a9SColin Riley     {
28635ec532a9SColin Riley         kernel.Dump(strm);
28645ec532a9SColin Riley     }
28654640cde1SColin Riley     strm.Printf("Pragmas: %"  PRIu64 , static_cast<uint64_t>(m_pragmas.size()));
28664640cde1SColin Riley     strm.EOL();
28674640cde1SColin Riley     strm.IndentMore();
28684640cde1SColin Riley     for (const auto &key_val : m_pragmas)
28694640cde1SColin Riley     {
28704640cde1SColin Riley         strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
28714640cde1SColin Riley         strm.EOL();
28724640cde1SColin Riley     }
28735ec532a9SColin Riley     strm.IndentLess(4);
28745ec532a9SColin Riley }
28755ec532a9SColin Riley 
28765ec532a9SColin Riley void
28775ec532a9SColin Riley RSGlobalDescriptor::Dump(Stream &strm) const
28785ec532a9SColin Riley {
28795ec532a9SColin Riley     strm.Indent(m_name.AsCString());
28804640cde1SColin Riley     VariableList var_list;
28814640cde1SColin Riley     m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
28824640cde1SColin Riley     if (var_list.GetSize() == 1)
28834640cde1SColin Riley     {
28844640cde1SColin Riley         auto var = var_list.GetVariableAtIndex(0);
28854640cde1SColin Riley         auto type = var->GetType();
28864640cde1SColin Riley         if(type)
28874640cde1SColin Riley         {
28884640cde1SColin Riley             strm.Printf(" - ");
28894640cde1SColin Riley             type->DumpTypeName(&strm);
28904640cde1SColin Riley         }
28914640cde1SColin Riley         else
28924640cde1SColin Riley         {
28934640cde1SColin Riley             strm.Printf(" - Unknown Type");
28944640cde1SColin Riley         }
28954640cde1SColin Riley     }
28964640cde1SColin Riley     else
28974640cde1SColin Riley     {
28984640cde1SColin Riley         strm.Printf(" - variable identified, but not found in binary");
28994640cde1SColin Riley         const Symbol* s = m_module->m_module->FindFirstSymbolWithNameAndType(m_name, eSymbolTypeData);
29004640cde1SColin Riley         if (s)
29014640cde1SColin Riley         {
29024640cde1SColin Riley             strm.Printf(" (symbol exists) ");
29034640cde1SColin Riley         }
29044640cde1SColin Riley     }
29054640cde1SColin Riley 
29065ec532a9SColin Riley     strm.EOL();
29075ec532a9SColin Riley }
29085ec532a9SColin Riley 
29095ec532a9SColin Riley void
29105ec532a9SColin Riley RSKernelDescriptor::Dump(Stream &strm) const
29115ec532a9SColin Riley {
29125ec532a9SColin Riley     strm.Indent(m_name.AsCString());
29135ec532a9SColin Riley     strm.EOL();
29145ec532a9SColin Riley }
29155ec532a9SColin Riley 
29165ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleProbe : public CommandObjectParsed
29175ec532a9SColin Riley {
29185ec532a9SColin Riley public:
29195ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleProbe(CommandInterpreter &interpreter)
29205ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module probe",
29215ec532a9SColin Riley                               "Initiates a Probe of all loaded modules for kernels and other renderscript objects.",
29225ec532a9SColin Riley                               "renderscript module probe",
2923e87764f2SEnrico Granata                               eCommandRequiresTarget | eCommandRequiresProcess | eCommandProcessMustBeLaunched)
29245ec532a9SColin Riley     {
29255ec532a9SColin Riley     }
29265ec532a9SColin Riley 
2927222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModuleProbe() override = default;
29285ec532a9SColin Riley 
29295ec532a9SColin Riley     bool
2930222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
29315ec532a9SColin Riley     {
29325ec532a9SColin Riley         const size_t argc = command.GetArgumentCount();
29335ec532a9SColin Riley         if (argc == 0)
29345ec532a9SColin Riley         {
29355ec532a9SColin Riley             Target *target = m_exe_ctx.GetTargetPtr();
29365ec532a9SColin Riley             RenderScriptRuntime *runtime =
29375ec532a9SColin Riley                 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
29385ec532a9SColin Riley             auto module_list = target->GetImages();
29395ec532a9SColin Riley             bool new_rs_details = runtime->ProbeModules(module_list);
29405ec532a9SColin Riley             if (new_rs_details)
29415ec532a9SColin Riley             {
29425ec532a9SColin Riley                 result.AppendMessage("New renderscript modules added to runtime model.");
29435ec532a9SColin Riley             }
29445ec532a9SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
29455ec532a9SColin Riley             return true;
29465ec532a9SColin Riley         }
29475ec532a9SColin Riley 
29485ec532a9SColin Riley         result.AppendErrorWithFormat("'%s' takes no arguments", m_cmd_name.c_str());
29495ec532a9SColin Riley         result.SetStatus(eReturnStatusFailed);
29505ec532a9SColin Riley         return false;
29515ec532a9SColin Riley     }
29525ec532a9SColin Riley };
29535ec532a9SColin Riley 
29545ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed
29555ec532a9SColin Riley {
29565ec532a9SColin Riley public:
29575ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
29585ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module dump",
29595ec532a9SColin Riley                               "Dumps renderscript specific information for all modules.", "renderscript module dump",
2960e87764f2SEnrico Granata                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
29615ec532a9SColin Riley     {
29625ec532a9SColin Riley     }
29635ec532a9SColin Riley 
2964222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
29655ec532a9SColin Riley 
29665ec532a9SColin Riley     bool
2967222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
29685ec532a9SColin Riley     {
29695ec532a9SColin Riley         RenderScriptRuntime *runtime =
29705ec532a9SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
29715ec532a9SColin Riley         runtime->DumpModules(result.GetOutputStream());
29725ec532a9SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
29735ec532a9SColin Riley         return true;
29745ec532a9SColin Riley     }
29755ec532a9SColin Riley };
29765ec532a9SColin Riley 
29775ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword
29785ec532a9SColin Riley {
29795ec532a9SColin Riley public:
29805ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
29815ec532a9SColin Riley         : CommandObjectMultiword(interpreter, "renderscript module", "Commands that deal with renderscript modules.",
29825ec532a9SColin Riley                                  NULL)
29835ec532a9SColin Riley     {
29845ec532a9SColin Riley         LoadSubCommand("probe", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleProbe(interpreter)));
29855ec532a9SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(interpreter)));
29865ec532a9SColin Riley     }
29875ec532a9SColin Riley 
2988222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModule() override = default;
29895ec532a9SColin Riley };
29905ec532a9SColin Riley 
29914640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed
29924640cde1SColin Riley {
29934640cde1SColin Riley public:
29944640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
29954640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript kernel list",
29964640cde1SColin Riley                               "Lists renderscript kernel names and associated script resources.", "renderscript kernel list",
29974640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
29984640cde1SColin Riley     {
29994640cde1SColin Riley     }
30004640cde1SColin Riley 
3001222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelList() override = default;
30024640cde1SColin Riley 
30034640cde1SColin Riley     bool
3004222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
30054640cde1SColin Riley     {
30064640cde1SColin Riley         RenderScriptRuntime *runtime =
30074640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
30084640cde1SColin Riley         runtime->DumpKernels(result.GetOutputStream());
30094640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
30104640cde1SColin Riley         return true;
30114640cde1SColin Riley     }
30124640cde1SColin Riley };
30134640cde1SColin Riley 
30147dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointSet : public CommandObjectParsed
30154640cde1SColin Riley {
30164640cde1SColin Riley public:
30177dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointSet(CommandInterpreter &interpreter)
30187dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint set",
3019018f5a7eSEwan Crawford                               "Sets a breakpoint on a renderscript kernel.", "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
3020018f5a7eSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), m_options(interpreter)
30214640cde1SColin Riley     {
30224640cde1SColin Riley     }
30234640cde1SColin Riley 
3024222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
3025222b937cSEugene Zelenko 
3026222b937cSEugene Zelenko     Options*
3027222b937cSEugene Zelenko     GetOptions() override
3028018f5a7eSEwan Crawford     {
3029018f5a7eSEwan Crawford         return &m_options;
3030018f5a7eSEwan Crawford     }
3031018f5a7eSEwan Crawford 
3032018f5a7eSEwan Crawford     class CommandOptions : public Options
3033018f5a7eSEwan Crawford     {
3034018f5a7eSEwan Crawford     public:
3035018f5a7eSEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter)
3036018f5a7eSEwan Crawford         {
3037018f5a7eSEwan Crawford         }
3038018f5a7eSEwan Crawford 
3039222b937cSEugene Zelenko         ~CommandOptions() override = default;
3040018f5a7eSEwan Crawford 
3041222b937cSEugene Zelenko         Error
3042222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
3043018f5a7eSEwan Crawford         {
3044018f5a7eSEwan Crawford             Error error;
3045018f5a7eSEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
3046018f5a7eSEwan Crawford 
3047018f5a7eSEwan Crawford             switch (short_option)
3048018f5a7eSEwan Crawford             {
3049018f5a7eSEwan Crawford                 case 'c':
3050018f5a7eSEwan Crawford                     if (!ParseCoordinate(option_arg))
3051018f5a7eSEwan Crawford                         error.SetErrorStringWithFormat("Couldn't parse coordinate '%s', should be in format 'x,y,z'.", option_arg);
3052018f5a7eSEwan Crawford                     break;
3053018f5a7eSEwan Crawford                 default:
3054018f5a7eSEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3055018f5a7eSEwan Crawford                     break;
3056018f5a7eSEwan Crawford             }
3057018f5a7eSEwan Crawford             return error;
3058018f5a7eSEwan Crawford         }
3059018f5a7eSEwan Crawford 
3060018f5a7eSEwan Crawford         // -c takes an argument of the form 'num[,num][,num]'.
3061018f5a7eSEwan Crawford         // Where 'id_cstr' is this argument with the whitespace trimmed.
3062018f5a7eSEwan Crawford         // Missing coordinates are defaulted to zero.
3063018f5a7eSEwan Crawford         bool
3064018f5a7eSEwan Crawford         ParseCoordinate(const char* id_cstr)
3065018f5a7eSEwan Crawford         {
3066018f5a7eSEwan Crawford             RegularExpression regex;
3067018f5a7eSEwan Crawford             RegularExpression::Match regex_match(3);
3068018f5a7eSEwan Crawford 
3069018f5a7eSEwan Crawford             bool matched = false;
3070018f5a7eSEwan Crawford             if(regex.Compile("^([0-9]+),([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3071018f5a7eSEwan Crawford                 matched = true;
3072018f5a7eSEwan Crawford             else if(regex.Compile("^([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3073018f5a7eSEwan Crawford                 matched = true;
3074018f5a7eSEwan Crawford             else if(regex.Compile("^([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3075018f5a7eSEwan Crawford                 matched = true;
3076018f5a7eSEwan Crawford             for(uint32_t i = 0; i < 3; i++)
3077018f5a7eSEwan Crawford             {
3078018f5a7eSEwan Crawford                 std::string group;
3079018f5a7eSEwan Crawford                 if(regex_match.GetMatchAtIndex(id_cstr, i + 1, group))
3080018f5a7eSEwan Crawford                     m_coord[i] = (uint32_t)strtoul(group.c_str(), NULL, 0);
3081018f5a7eSEwan Crawford                 else
3082018f5a7eSEwan Crawford                     m_coord[i] = 0;
3083018f5a7eSEwan Crawford             }
3084018f5a7eSEwan Crawford             return matched;
3085018f5a7eSEwan Crawford         }
3086018f5a7eSEwan Crawford 
3087018f5a7eSEwan Crawford         void
3088222b937cSEugene Zelenko         OptionParsingStarting() override
3089018f5a7eSEwan Crawford         {
3090018f5a7eSEwan Crawford             // -1 means the -c option hasn't been set
3091018f5a7eSEwan Crawford             m_coord[0] = -1;
3092018f5a7eSEwan Crawford             m_coord[1] = -1;
3093018f5a7eSEwan Crawford             m_coord[2] = -1;
3094018f5a7eSEwan Crawford         }
3095018f5a7eSEwan Crawford 
3096018f5a7eSEwan Crawford         const OptionDefinition*
3097222b937cSEugene Zelenko         GetDefinitions() override
3098018f5a7eSEwan Crawford         {
3099018f5a7eSEwan Crawford             return g_option_table;
3100018f5a7eSEwan Crawford         }
3101018f5a7eSEwan Crawford 
3102018f5a7eSEwan Crawford         static OptionDefinition g_option_table[];
3103018f5a7eSEwan Crawford         std::array<int,3> m_coord;
3104018f5a7eSEwan Crawford     };
3105018f5a7eSEwan Crawford 
31064640cde1SColin Riley     bool
3107222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
31084640cde1SColin Riley     {
31094640cde1SColin Riley         const size_t argc = command.GetArgumentCount();
3110018f5a7eSEwan Crawford         if (argc < 1)
31114640cde1SColin Riley         {
3112018f5a7eSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of kernel name, and an optional coordinate.", m_cmd_name.c_str());
3113018f5a7eSEwan Crawford             result.SetStatus(eReturnStatusFailed);
3114018f5a7eSEwan Crawford             return false;
3115018f5a7eSEwan Crawford         }
3116018f5a7eSEwan Crawford 
31174640cde1SColin Riley         RenderScriptRuntime *runtime =
31184640cde1SColin Riley                 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
31194640cde1SColin Riley 
31204640cde1SColin Riley         Error error;
3121018f5a7eSEwan Crawford         runtime->PlaceBreakpointOnKernel(result.GetOutputStream(), command.GetArgumentAtIndex(0), m_options.m_coord,
312298156583SEwan Crawford                                          error, m_exe_ctx.GetTargetSP());
31234640cde1SColin Riley 
31244640cde1SColin Riley         if (error.Success())
31254640cde1SColin Riley         {
31264640cde1SColin Riley             result.AppendMessage("Breakpoint(s) created");
31274640cde1SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
31284640cde1SColin Riley             return true;
31294640cde1SColin Riley         }
31304640cde1SColin Riley         result.SetStatus(eReturnStatusFailed);
31314640cde1SColin Riley         result.AppendErrorWithFormat("Error: %s", error.AsCString());
31324640cde1SColin Riley         return false;
31334640cde1SColin Riley     }
31344640cde1SColin Riley 
3135018f5a7eSEwan Crawford private:
3136018f5a7eSEwan Crawford     CommandOptions m_options;
31374640cde1SColin Riley };
31384640cde1SColin Riley 
3139018f5a7eSEwan Crawford OptionDefinition
3140018f5a7eSEwan Crawford CommandObjectRenderScriptRuntimeKernelBreakpointSet::CommandOptions::g_option_table[] =
3141018f5a7eSEwan Crawford {
3142018f5a7eSEwan Crawford     { LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeValue,
3143018f5a7eSEwan Crawford       "Set a breakpoint on a single invocation of the kernel with specified coordinate.\n"
3144018f5a7eSEwan Crawford       "Coordinate takes the form 'x[,y][,z] where x,y,z are positive integers representing kernel dimensions. "
3145018f5a7eSEwan Crawford       "Any unset dimensions will be defaulted to zero."},
3146018f5a7eSEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
3147018f5a7eSEwan Crawford };
3148018f5a7eSEwan Crawford 
31497dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointAll : public CommandObjectParsed
31507dc7771cSEwan Crawford {
31517dc7771cSEwan Crawford public:
31527dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointAll(CommandInterpreter &interpreter)
31537dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint all",
31547dc7771cSEwan Crawford                               "Automatically sets a breakpoint on all renderscript kernels that are or will be loaded.\n"
31557dc7771cSEwan Crawford                               "Disabling option means breakpoints will no longer be set on any kernels loaded in the future, "
31567dc7771cSEwan Crawford                               "but does not remove currently set breakpoints.",
31577dc7771cSEwan Crawford                               "renderscript kernel breakpoint all <enable/disable>",
31587dc7771cSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
31597dc7771cSEwan Crawford     {
31607dc7771cSEwan Crawford     }
31617dc7771cSEwan Crawford 
3162222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
31637dc7771cSEwan Crawford 
31647dc7771cSEwan Crawford     bool
3165222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
31667dc7771cSEwan Crawford     {
31677dc7771cSEwan Crawford         const size_t argc = command.GetArgumentCount();
31687dc7771cSEwan Crawford         if (argc != 1)
31697dc7771cSEwan Crawford         {
31707dc7771cSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
31717dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
31727dc7771cSEwan Crawford             return false;
31737dc7771cSEwan Crawford         }
31747dc7771cSEwan Crawford 
31757dc7771cSEwan Crawford         RenderScriptRuntime *runtime =
31767dc7771cSEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
31777dc7771cSEwan Crawford 
31787dc7771cSEwan Crawford         bool do_break = false;
31797dc7771cSEwan Crawford         const char* argument = command.GetArgumentAtIndex(0);
31807dc7771cSEwan Crawford         if (strcmp(argument, "enable") == 0)
31817dc7771cSEwan Crawford         {
31827dc7771cSEwan Crawford             do_break = true;
31837dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will be set on all kernels.");
31847dc7771cSEwan Crawford         }
31857dc7771cSEwan Crawford         else if (strcmp(argument, "disable") == 0)
31867dc7771cSEwan Crawford         {
31877dc7771cSEwan Crawford             do_break = false;
31887dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will not be set on any new kernels.");
31897dc7771cSEwan Crawford         }
31907dc7771cSEwan Crawford         else
31917dc7771cSEwan Crawford         {
31927dc7771cSEwan Crawford             result.AppendErrorWithFormat("Argument must be either 'enable' or 'disable'");
31937dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
31947dc7771cSEwan Crawford             return false;
31957dc7771cSEwan Crawford         }
31967dc7771cSEwan Crawford 
31977dc7771cSEwan Crawford         runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
31987dc7771cSEwan Crawford 
31997dc7771cSEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
32007dc7771cSEwan Crawford         return true;
32017dc7771cSEwan Crawford     }
32027dc7771cSEwan Crawford };
32037dc7771cSEwan Crawford 
32047dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpoint : public CommandObjectMultiword
32057dc7771cSEwan Crawford {
32067dc7771cSEwan Crawford public:
32077dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpoint(CommandInterpreter &interpreter)
32087dc7771cSEwan Crawford         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that generate breakpoints on renderscript kernels.",
32097dc7771cSEwan Crawford                                  nullptr)
32107dc7771cSEwan Crawford     {
32117dc7771cSEwan Crawford         LoadSubCommand("set", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(interpreter)));
32127dc7771cSEwan Crawford         LoadSubCommand("all", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(interpreter)));
32137dc7771cSEwan Crawford     }
32147dc7771cSEwan Crawford 
3215222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
32167dc7771cSEwan Crawford };
32177dc7771cSEwan Crawford 
32184640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword
32194640cde1SColin Riley {
32204640cde1SColin Riley public:
32214640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
32224640cde1SColin Riley         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that deal with renderscript kernels.",
32234640cde1SColin Riley                                  NULL)
32244640cde1SColin Riley     {
32254640cde1SColin Riley         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(interpreter)));
32264640cde1SColin Riley         LoadSubCommand("breakpoint", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
32274640cde1SColin Riley     }
32284640cde1SColin Riley 
3229222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernel() override = default;
32304640cde1SColin Riley };
32314640cde1SColin Riley 
32324640cde1SColin Riley class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed
32334640cde1SColin Riley {
32344640cde1SColin Riley public:
32354640cde1SColin Riley     CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
32364640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript context dump",
32374640cde1SColin Riley                               "Dumps renderscript context information.", "renderscript context dump",
32384640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
32394640cde1SColin Riley     {
32404640cde1SColin Riley     }
32414640cde1SColin Riley 
3242222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeContextDump() override = default;
32434640cde1SColin Riley 
32444640cde1SColin Riley     bool
3245222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
32464640cde1SColin Riley     {
32474640cde1SColin Riley         RenderScriptRuntime *runtime =
32484640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
32494640cde1SColin Riley         runtime->DumpContexts(result.GetOutputStream());
32504640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
32514640cde1SColin Riley         return true;
32524640cde1SColin Riley     }
32534640cde1SColin Riley };
32544640cde1SColin Riley 
32554640cde1SColin Riley class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword
32564640cde1SColin Riley {
32574640cde1SColin Riley public:
32584640cde1SColin Riley     CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
32594640cde1SColin Riley         : CommandObjectMultiword(interpreter, "renderscript context", "Commands that deal with renderscript contexts.",
32604640cde1SColin Riley                                  NULL)
32614640cde1SColin Riley     {
32624640cde1SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(interpreter)));
32634640cde1SColin Riley     }
32644640cde1SColin Riley 
3265222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeContext() override = default;
32664640cde1SColin Riley };
32674640cde1SColin Riley 
3268a0f08674SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationDump : public CommandObjectParsed
3269a0f08674SEwan Crawford {
3270a0f08674SEwan Crawford public:
3271a0f08674SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationDump(CommandInterpreter &interpreter)
3272a0f08674SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation dump",
3273a0f08674SEwan Crawford                               "Displays the contents of a particular allocation", "renderscript allocation dump <ID>",
3274a0f08674SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter)
3275a0f08674SEwan Crawford     {
3276a0f08674SEwan Crawford     }
3277a0f08674SEwan Crawford 
3278222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
3279222b937cSEugene Zelenko 
3280222b937cSEugene Zelenko     Options*
3281222b937cSEugene Zelenko     GetOptions() override
3282a0f08674SEwan Crawford     {
3283a0f08674SEwan Crawford         return &m_options;
3284a0f08674SEwan Crawford     }
3285a0f08674SEwan Crawford 
3286a0f08674SEwan Crawford     class CommandOptions : public Options
3287a0f08674SEwan Crawford     {
3288a0f08674SEwan Crawford     public:
3289a0f08674SEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter)
3290a0f08674SEwan Crawford         {
3291a0f08674SEwan Crawford         }
3292a0f08674SEwan Crawford 
3293222b937cSEugene Zelenko         ~CommandOptions() override = default;
3294a0f08674SEwan Crawford 
3295222b937cSEugene Zelenko         Error
3296222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
3297a0f08674SEwan Crawford         {
3298a0f08674SEwan Crawford             Error error;
3299a0f08674SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
3300a0f08674SEwan Crawford 
3301a0f08674SEwan Crawford             switch (short_option)
3302a0f08674SEwan Crawford             {
3303a0f08674SEwan Crawford                 case 'f':
3304a0f08674SEwan Crawford                     m_outfile.SetFile(option_arg, true);
3305a0f08674SEwan Crawford                     if (m_outfile.Exists())
3306a0f08674SEwan Crawford                     {
3307a0f08674SEwan Crawford                         m_outfile.Clear();
3308a0f08674SEwan Crawford                         error.SetErrorStringWithFormat("file already exists: '%s'", option_arg);
3309a0f08674SEwan Crawford                     }
3310a0f08674SEwan Crawford                     break;
3311a0f08674SEwan Crawford                 default:
3312a0f08674SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3313a0f08674SEwan Crawford                     break;
3314a0f08674SEwan Crawford             }
3315a0f08674SEwan Crawford             return error;
3316a0f08674SEwan Crawford         }
3317a0f08674SEwan Crawford 
3318a0f08674SEwan Crawford         void
3319222b937cSEugene Zelenko         OptionParsingStarting() override
3320a0f08674SEwan Crawford         {
3321a0f08674SEwan Crawford             m_outfile.Clear();
3322a0f08674SEwan Crawford         }
3323a0f08674SEwan Crawford 
3324a0f08674SEwan Crawford         const OptionDefinition*
3325222b937cSEugene Zelenko         GetDefinitions() override
3326a0f08674SEwan Crawford         {
3327a0f08674SEwan Crawford             return g_option_table;
3328a0f08674SEwan Crawford         }
3329a0f08674SEwan Crawford 
3330a0f08674SEwan Crawford         static OptionDefinition g_option_table[];
3331a0f08674SEwan Crawford         FileSpec m_outfile;
3332a0f08674SEwan Crawford     };
3333a0f08674SEwan Crawford 
3334a0f08674SEwan Crawford     bool
3335222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
3336a0f08674SEwan Crawford     {
3337a0f08674SEwan Crawford         const size_t argc = command.GetArgumentCount();
3338a0f08674SEwan Crawford         if (argc < 1)
3339a0f08674SEwan Crawford         {
3340a0f08674SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. As well as an optional -f argument",
3341a0f08674SEwan Crawford                                          m_cmd_name.c_str());
3342a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3343a0f08674SEwan Crawford             return false;
3344a0f08674SEwan Crawford         }
3345a0f08674SEwan Crawford 
3346a0f08674SEwan Crawford         RenderScriptRuntime *runtime =
3347a0f08674SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
3348a0f08674SEwan Crawford 
3349a0f08674SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
3350a0f08674SEwan Crawford         bool convert_complete = false;
3351a0f08674SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
3352a0f08674SEwan Crawford         if (!convert_complete)
3353a0f08674SEwan Crawford         {
3354a0f08674SEwan Crawford             result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
3355a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3356a0f08674SEwan Crawford             return false;
3357a0f08674SEwan Crawford         }
3358a0f08674SEwan Crawford 
3359a0f08674SEwan Crawford         Stream* output_strm = nullptr;
3360a0f08674SEwan Crawford         StreamFile outfile_stream;
3361a0f08674SEwan Crawford         const FileSpec &outfile_spec = m_options.m_outfile; // Dump allocation to file instead
3362a0f08674SEwan Crawford         if (outfile_spec)
3363a0f08674SEwan Crawford         {
3364a0f08674SEwan Crawford             // Open output file
3365a0f08674SEwan Crawford             char path[256];
3366a0f08674SEwan Crawford             outfile_spec.GetPath(path, sizeof(path));
3367a0f08674SEwan Crawford             if (outfile_stream.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate).Success())
3368a0f08674SEwan Crawford             {
3369a0f08674SEwan Crawford                 output_strm = &outfile_stream;
3370a0f08674SEwan Crawford                 result.GetOutputStream().Printf("Results written to '%s'", path);
3371a0f08674SEwan Crawford                 result.GetOutputStream().EOL();
3372a0f08674SEwan Crawford             }
3373a0f08674SEwan Crawford             else
3374a0f08674SEwan Crawford             {
3375a0f08674SEwan Crawford                 result.AppendErrorWithFormat("Couldn't open file '%s'", path);
3376a0f08674SEwan Crawford                 result.SetStatus(eReturnStatusFailed);
3377a0f08674SEwan Crawford                 return false;
3378a0f08674SEwan Crawford             }
3379a0f08674SEwan Crawford         }
3380a0f08674SEwan Crawford         else
3381a0f08674SEwan Crawford             output_strm = &result.GetOutputStream();
3382a0f08674SEwan Crawford 
3383a0f08674SEwan Crawford         assert(output_strm != nullptr);
3384a0f08674SEwan Crawford         bool success = runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
3385a0f08674SEwan Crawford 
3386a0f08674SEwan Crawford         if (success)
3387a0f08674SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
3388a0f08674SEwan Crawford         else
3389a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3390a0f08674SEwan Crawford 
3391a0f08674SEwan Crawford         return true;
3392a0f08674SEwan Crawford     }
3393a0f08674SEwan Crawford 
3394a0f08674SEwan Crawford private:
3395a0f08674SEwan Crawford     CommandOptions m_options;
3396a0f08674SEwan Crawford };
3397a0f08674SEwan Crawford 
3398a0f08674SEwan Crawford OptionDefinition
3399a0f08674SEwan Crawford CommandObjectRenderScriptRuntimeAllocationDump::CommandOptions::g_option_table[] =
3400a0f08674SEwan Crawford {
3401a0f08674SEwan Crawford     { LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename,
3402a0f08674SEwan Crawford       "Print results to specified file instead of command line."},
3403a0f08674SEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
3404a0f08674SEwan Crawford };
3405a0f08674SEwan Crawford 
340615f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationList : public CommandObjectParsed
340715f2bd95SEwan Crawford {
340815f2bd95SEwan Crawford public:
340915f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationList(CommandInterpreter &interpreter)
341015f2bd95SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation list",
341115f2bd95SEwan Crawford                               "List renderscript allocations and their information.", "renderscript allocation list",
341215f2bd95SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter)
341315f2bd95SEwan Crawford     {
341415f2bd95SEwan Crawford     }
341515f2bd95SEwan Crawford 
3416222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
3417222b937cSEugene Zelenko 
3418222b937cSEugene Zelenko     Options*
3419222b937cSEugene Zelenko     GetOptions() override
342015f2bd95SEwan Crawford     {
342115f2bd95SEwan Crawford         return &m_options;
342215f2bd95SEwan Crawford     }
342315f2bd95SEwan Crawford 
342415f2bd95SEwan Crawford     class CommandOptions : public Options
342515f2bd95SEwan Crawford     {
342615f2bd95SEwan Crawford     public:
342715f2bd95SEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter), m_refresh(false)
342815f2bd95SEwan Crawford         {
342915f2bd95SEwan Crawford         }
343015f2bd95SEwan Crawford 
3431222b937cSEugene Zelenko         ~CommandOptions() override = default;
343215f2bd95SEwan Crawford 
3433222b937cSEugene Zelenko         Error
3434222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
343515f2bd95SEwan Crawford         {
343615f2bd95SEwan Crawford             Error error;
343715f2bd95SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
343815f2bd95SEwan Crawford 
343915f2bd95SEwan Crawford             switch (short_option)
344015f2bd95SEwan Crawford             {
344115f2bd95SEwan Crawford                 case 'r':
344215f2bd95SEwan Crawford                     m_refresh = true;
344315f2bd95SEwan Crawford                     break;
344415f2bd95SEwan Crawford                 default:
344515f2bd95SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
344615f2bd95SEwan Crawford                     break;
344715f2bd95SEwan Crawford             }
344815f2bd95SEwan Crawford             return error;
344915f2bd95SEwan Crawford         }
345015f2bd95SEwan Crawford 
345115f2bd95SEwan Crawford         void
3452222b937cSEugene Zelenko         OptionParsingStarting() override
345315f2bd95SEwan Crawford         {
345415f2bd95SEwan Crawford             m_refresh = false;
345515f2bd95SEwan Crawford         }
345615f2bd95SEwan Crawford 
345715f2bd95SEwan Crawford         const OptionDefinition*
3458222b937cSEugene Zelenko         GetDefinitions() override
345915f2bd95SEwan Crawford         {
346015f2bd95SEwan Crawford             return g_option_table;
346115f2bd95SEwan Crawford         }
346215f2bd95SEwan Crawford 
346315f2bd95SEwan Crawford         static OptionDefinition g_option_table[];
346415f2bd95SEwan Crawford         bool m_refresh;
346515f2bd95SEwan Crawford     };
346615f2bd95SEwan Crawford 
346715f2bd95SEwan Crawford     bool
3468222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
346915f2bd95SEwan Crawford     {
347015f2bd95SEwan Crawford         RenderScriptRuntime *runtime =
347115f2bd95SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
347215f2bd95SEwan Crawford         runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(), m_options.m_refresh);
347315f2bd95SEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
347415f2bd95SEwan Crawford         return true;
347515f2bd95SEwan Crawford     }
347615f2bd95SEwan Crawford 
347715f2bd95SEwan Crawford private:
347815f2bd95SEwan Crawford     CommandOptions m_options;
347915f2bd95SEwan Crawford };
348015f2bd95SEwan Crawford 
348115f2bd95SEwan Crawford OptionDefinition
348215f2bd95SEwan Crawford CommandObjectRenderScriptRuntimeAllocationList::CommandOptions::g_option_table[] =
348315f2bd95SEwan Crawford {
348415f2bd95SEwan Crawford     { LLDB_OPT_SET_1, false, "refresh", 'r', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone,
348515f2bd95SEwan Crawford       "Recompute allocation details."},
348615f2bd95SEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
348715f2bd95SEwan Crawford };
348815f2bd95SEwan Crawford 
348955232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationLoad : public CommandObjectParsed
349055232f09SEwan Crawford {
349155232f09SEwan Crawford public:
349255232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationLoad(CommandInterpreter &interpreter)
349355232f09SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation load",
349455232f09SEwan Crawford                               "Loads renderscript allocation contents from a file.", "renderscript allocation load <ID> <filename>",
349555232f09SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
349655232f09SEwan Crawford     {
349755232f09SEwan Crawford     }
349855232f09SEwan Crawford 
3499222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
350055232f09SEwan Crawford 
350155232f09SEwan Crawford     bool
3502222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
350355232f09SEwan Crawford     {
350455232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
350555232f09SEwan Crawford         if (argc != 2)
350655232f09SEwan Crawford         {
350755232f09SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str());
350855232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
350955232f09SEwan Crawford             return false;
351055232f09SEwan Crawford         }
351155232f09SEwan Crawford 
351255232f09SEwan Crawford         RenderScriptRuntime *runtime =
351355232f09SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
351455232f09SEwan Crawford 
351555232f09SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
351655232f09SEwan Crawford         bool convert_complete = false;
351755232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
351855232f09SEwan Crawford         if (!convert_complete)
351955232f09SEwan Crawford         {
352055232f09SEwan Crawford             result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr);
352155232f09SEwan Crawford             result.SetStatus (eReturnStatusFailed);
352255232f09SEwan Crawford             return false;
352355232f09SEwan Crawford         }
352455232f09SEwan Crawford 
352555232f09SEwan Crawford         const char* filename = command.GetArgumentAtIndex(1);
352655232f09SEwan Crawford         bool success = runtime->LoadAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
352755232f09SEwan Crawford 
352855232f09SEwan Crawford         if (success)
352955232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
353055232f09SEwan Crawford         else
353155232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
353255232f09SEwan Crawford 
353355232f09SEwan Crawford         return true;
353455232f09SEwan Crawford     }
353555232f09SEwan Crawford };
353655232f09SEwan Crawford 
353755232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationSave : public CommandObjectParsed
353855232f09SEwan Crawford {
353955232f09SEwan Crawford public:
354055232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationSave(CommandInterpreter &interpreter)
354155232f09SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation save",
354255232f09SEwan Crawford                               "Write renderscript allocation contents to a file.", "renderscript allocation save <ID> <filename>",
354355232f09SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
354455232f09SEwan Crawford     {
354555232f09SEwan Crawford     }
354655232f09SEwan Crawford 
3547222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
354855232f09SEwan Crawford 
354955232f09SEwan Crawford     bool
3550222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
355155232f09SEwan Crawford     {
355255232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
355355232f09SEwan Crawford         if (argc != 2)
355455232f09SEwan Crawford         {
355555232f09SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str());
355655232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
355755232f09SEwan Crawford             return false;
355855232f09SEwan Crawford         }
355955232f09SEwan Crawford 
356055232f09SEwan Crawford         RenderScriptRuntime *runtime =
356155232f09SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
356255232f09SEwan Crawford 
356355232f09SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
356455232f09SEwan Crawford         bool convert_complete = false;
356555232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
356655232f09SEwan Crawford         if (!convert_complete)
356755232f09SEwan Crawford         {
356855232f09SEwan Crawford             result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr);
356955232f09SEwan Crawford             result.SetStatus (eReturnStatusFailed);
357055232f09SEwan Crawford             return false;
357155232f09SEwan Crawford         }
357255232f09SEwan Crawford 
357355232f09SEwan Crawford         const char* filename = command.GetArgumentAtIndex(1);
357455232f09SEwan Crawford         bool success = runtime->SaveAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
357555232f09SEwan Crawford 
357655232f09SEwan Crawford         if (success)
357755232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
357855232f09SEwan Crawford         else
357955232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
358055232f09SEwan Crawford 
358155232f09SEwan Crawford         return true;
358255232f09SEwan Crawford     }
358355232f09SEwan Crawford };
358455232f09SEwan Crawford 
358515f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocation : public CommandObjectMultiword
358615f2bd95SEwan Crawford {
358715f2bd95SEwan Crawford public:
358815f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
358915f2bd95SEwan Crawford         : CommandObjectMultiword(interpreter, "renderscript allocation", "Commands that deal with renderscript allocations.",
359015f2bd95SEwan Crawford                                  NULL)
359115f2bd95SEwan Crawford     {
359215f2bd95SEwan Crawford         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
3593a0f08674SEwan Crawford         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
359455232f09SEwan Crawford         LoadSubCommand("save", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
359555232f09SEwan Crawford         LoadSubCommand("load", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
359615f2bd95SEwan Crawford     }
359715f2bd95SEwan Crawford 
3598222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocation() override = default;
359915f2bd95SEwan Crawford };
360015f2bd95SEwan Crawford 
36014640cde1SColin Riley class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed
36024640cde1SColin Riley {
36034640cde1SColin Riley public:
36044640cde1SColin Riley     CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
36054640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript status",
36064640cde1SColin Riley                               "Displays current renderscript runtime status.", "renderscript status",
36074640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
36084640cde1SColin Riley     {
36094640cde1SColin Riley     }
36104640cde1SColin Riley 
3611222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeStatus() override = default;
36124640cde1SColin Riley 
36134640cde1SColin Riley     bool
3614222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
36154640cde1SColin Riley     {
36164640cde1SColin Riley         RenderScriptRuntime *runtime =
36174640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
36184640cde1SColin Riley         runtime->Status(result.GetOutputStream());
36194640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
36204640cde1SColin Riley         return true;
36214640cde1SColin Riley     }
36224640cde1SColin Riley };
36234640cde1SColin Riley 
36245ec532a9SColin Riley class CommandObjectRenderScriptRuntime : public CommandObjectMultiword
36255ec532a9SColin Riley {
36265ec532a9SColin Riley public:
36275ec532a9SColin Riley     CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
36285ec532a9SColin Riley         : CommandObjectMultiword(interpreter, "renderscript", "A set of commands for operating on renderscript.",
36295ec532a9SColin Riley                                  "renderscript <subcommand> [<subcommand-options>]")
36305ec532a9SColin Riley     {
36315ec532a9SColin Riley         LoadSubCommand("module", CommandObjectSP(new CommandObjectRenderScriptRuntimeModule(interpreter)));
36324640cde1SColin Riley         LoadSubCommand("status", CommandObjectSP(new CommandObjectRenderScriptRuntimeStatus(interpreter)));
36334640cde1SColin Riley         LoadSubCommand("kernel", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernel(interpreter)));
36344640cde1SColin Riley         LoadSubCommand("context", CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(interpreter)));
363515f2bd95SEwan Crawford         LoadSubCommand("allocation", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
36365ec532a9SColin Riley     }
36375ec532a9SColin Riley 
3638222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntime() override = default;
36395ec532a9SColin Riley };
3640ef20b08fSColin Riley 
3641ef20b08fSColin Riley void
3642ef20b08fSColin Riley RenderScriptRuntime::Initiate()
36435ec532a9SColin Riley {
3644ef20b08fSColin Riley     assert(!m_initiated);
36455ec532a9SColin Riley }
3646ef20b08fSColin Riley 
3647ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
36487dc7771cSEwan Crawford     : lldb_private::CPPLanguageRuntime(process), m_initiated(false), m_debuggerPresentFlagged(false),
36497dc7771cSEwan Crawford       m_breakAllKernels(false)
3650ef20b08fSColin Riley {
36514640cde1SColin Riley     ModulesDidLoad(process->GetTarget().GetImages());
3652ef20b08fSColin Riley }
36534640cde1SColin Riley 
36544640cde1SColin Riley lldb::CommandObjectSP
36554640cde1SColin Riley RenderScriptRuntime::GetCommandObject(lldb_private::CommandInterpreter& interpreter)
36564640cde1SColin Riley {
36574640cde1SColin Riley     static CommandObjectSP command_object;
36584640cde1SColin Riley     if(!command_object)
36594640cde1SColin Riley     {
36604640cde1SColin Riley         command_object.reset(new CommandObjectRenderScriptRuntime(interpreter));
36614640cde1SColin Riley     }
36624640cde1SColin Riley     return command_object;
36634640cde1SColin Riley }
36644640cde1SColin Riley 
366578f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
3666