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"
21018f5a7eSEwan Crawford #include "lldb/Core/RegularExpression.h"
22a0f08674SEwan Crawford #include "lldb/Host/StringConvert.h"
235ec532a9SColin Riley #include "lldb/Symbol/Symbol.h"
244640cde1SColin Riley #include "lldb/Symbol/Type.h"
255ec532a9SColin Riley #include "lldb/Target/Process.h"
265ec532a9SColin Riley #include "lldb/Target/Target.h"
27018f5a7eSEwan Crawford #include "lldb/Target/Thread.h"
285ec532a9SColin Riley #include "lldb/Interpreter/Args.h"
295ec532a9SColin Riley #include "lldb/Interpreter/Options.h"
305ec532a9SColin Riley #include "lldb/Interpreter/CommandInterpreter.h"
315ec532a9SColin Riley #include "lldb/Interpreter/CommandReturnObject.h"
325ec532a9SColin Riley #include "lldb/Interpreter/CommandObjectMultiword.h"
334640cde1SColin Riley #include "lldb/Breakpoint/StoppointCallbackContext.h"
344640cde1SColin Riley #include "lldb/Target/RegisterContext.h"
3515f2bd95SEwan Crawford #include "lldb/Expression/UserExpression.h"
364640cde1SColin Riley #include "lldb/Symbol/VariableList.h"
375ec532a9SColin Riley 
385ec532a9SColin Riley using namespace lldb;
395ec532a9SColin Riley using namespace lldb_private;
4098156583SEwan Crawford using namespace lldb_renderscript;
415ec532a9SColin Riley 
4278f339d1SEwan Crawford namespace {
4378f339d1SEwan Crawford 
4478f339d1SEwan Crawford // The empirical_type adds a basic level of validation to arbitrary data
4578f339d1SEwan Crawford // allowing us to track if data has been discovered and stored or not.
4678f339d1SEwan Crawford // An empirical_type will be marked as valid only if it has been explicitly assigned to.
4778f339d1SEwan Crawford template <typename type_t>
4878f339d1SEwan Crawford class empirical_type
4978f339d1SEwan Crawford {
5078f339d1SEwan Crawford public:
5178f339d1SEwan Crawford     // Ctor. Contents is invalid when constructed.
5278f339d1SEwan Crawford     empirical_type()
5378f339d1SEwan Crawford         : valid(false)
5478f339d1SEwan Crawford     {}
5578f339d1SEwan Crawford 
5678f339d1SEwan Crawford     // Return true and copy contents to out if valid, else return false.
5778f339d1SEwan Crawford     bool get(type_t& out) const
5878f339d1SEwan Crawford     {
5978f339d1SEwan Crawford         if (valid)
6078f339d1SEwan Crawford             out = data;
6178f339d1SEwan Crawford         return valid;
6278f339d1SEwan Crawford     }
6378f339d1SEwan Crawford 
6478f339d1SEwan Crawford     // Return a pointer to the contents or nullptr if it was not valid.
6578f339d1SEwan Crawford     const type_t* get() const
6678f339d1SEwan Crawford     {
6778f339d1SEwan Crawford         return valid ? &data : nullptr;
6878f339d1SEwan Crawford     }
6978f339d1SEwan Crawford 
7078f339d1SEwan Crawford     // Assign data explicitly.
7178f339d1SEwan Crawford     void set(const type_t in)
7278f339d1SEwan Crawford     {
7378f339d1SEwan Crawford         data = in;
7478f339d1SEwan Crawford         valid = true;
7578f339d1SEwan Crawford     }
7678f339d1SEwan Crawford 
7778f339d1SEwan Crawford     // Mark contents as invalid.
7878f339d1SEwan Crawford     void invalidate()
7978f339d1SEwan Crawford     {
8078f339d1SEwan Crawford         valid = false;
8178f339d1SEwan Crawford     }
8278f339d1SEwan Crawford 
8378f339d1SEwan Crawford     // Returns true if this type contains valid data.
8478f339d1SEwan Crawford     bool isValid() const
8578f339d1SEwan Crawford     {
8678f339d1SEwan Crawford         return valid;
8778f339d1SEwan Crawford     }
8878f339d1SEwan Crawford 
8978f339d1SEwan Crawford     // Assignment operator.
9078f339d1SEwan Crawford     empirical_type<type_t>& operator = (const type_t in)
9178f339d1SEwan Crawford     {
9278f339d1SEwan Crawford         set(in);
9378f339d1SEwan Crawford         return *this;
9478f339d1SEwan Crawford     }
9578f339d1SEwan Crawford 
9678f339d1SEwan Crawford     // Dereference operator returns contents.
9778f339d1SEwan Crawford     // Warning: Will assert if not valid so use only when you know data is valid.
9878f339d1SEwan Crawford     const type_t& operator * () const
9978f339d1SEwan Crawford     {
10078f339d1SEwan Crawford         assert(valid);
10178f339d1SEwan Crawford         return data;
10278f339d1SEwan Crawford     }
10378f339d1SEwan Crawford 
10478f339d1SEwan Crawford protected:
10578f339d1SEwan Crawford     bool valid;
10678f339d1SEwan Crawford     type_t data;
10778f339d1SEwan Crawford };
10878f339d1SEwan Crawford 
109222b937cSEugene Zelenko } // anonymous namespace
11078f339d1SEwan Crawford 
11178f339d1SEwan Crawford // The ScriptDetails class collects data associated with a single script instance.
11278f339d1SEwan Crawford struct RenderScriptRuntime::ScriptDetails
11378f339d1SEwan Crawford {
114222b937cSEugene Zelenko     ~ScriptDetails() = default;
11578f339d1SEwan Crawford 
11678f339d1SEwan Crawford     enum ScriptType
11778f339d1SEwan Crawford     {
11878f339d1SEwan Crawford         eScript,
11978f339d1SEwan Crawford         eScriptC
12078f339d1SEwan Crawford     };
12178f339d1SEwan Crawford 
12278f339d1SEwan Crawford     // The derived type of the script.
12378f339d1SEwan Crawford     empirical_type<ScriptType> type;
12478f339d1SEwan Crawford     // The name of the original source file.
12578f339d1SEwan Crawford     empirical_type<std::string> resName;
12678f339d1SEwan Crawford     // Path to script .so file on the device.
12778f339d1SEwan Crawford     empirical_type<std::string> scriptDyLib;
12878f339d1SEwan Crawford     // Directory where kernel objects are cached on device.
12978f339d1SEwan Crawford     empirical_type<std::string> cacheDir;
13078f339d1SEwan Crawford     // Pointer to the context which owns this script.
13178f339d1SEwan Crawford     empirical_type<lldb::addr_t> context;
13278f339d1SEwan Crawford     // Pointer to the script object itself.
13378f339d1SEwan Crawford     empirical_type<lldb::addr_t> script;
13478f339d1SEwan Crawford };
13578f339d1SEwan Crawford 
13678f339d1SEwan Crawford // This AllocationDetails class collects data associated with a single
13778f339d1SEwan Crawford // allocation instance.
13878f339d1SEwan Crawford struct RenderScriptRuntime::AllocationDetails
13978f339d1SEwan Crawford {
14015f2bd95SEwan Crawford    // Taken from rsDefines.h
14115f2bd95SEwan Crawford    enum DataKind
14215f2bd95SEwan Crawford    {
14315f2bd95SEwan Crawford        RS_KIND_USER,
14415f2bd95SEwan Crawford        RS_KIND_PIXEL_L = 7,
14515f2bd95SEwan Crawford        RS_KIND_PIXEL_A,
14615f2bd95SEwan Crawford        RS_KIND_PIXEL_LA,
14715f2bd95SEwan Crawford        RS_KIND_PIXEL_RGB,
14815f2bd95SEwan Crawford        RS_KIND_PIXEL_RGBA,
14915f2bd95SEwan Crawford        RS_KIND_PIXEL_DEPTH,
15015f2bd95SEwan Crawford        RS_KIND_PIXEL_YUV,
15115f2bd95SEwan Crawford        RS_KIND_INVALID = 100
15215f2bd95SEwan Crawford    };
15378f339d1SEwan Crawford 
15415f2bd95SEwan Crawford    // Taken from rsDefines.h
15578f339d1SEwan Crawford    enum DataType
15678f339d1SEwan Crawford    {
15715f2bd95SEwan Crawford        RS_TYPE_NONE = 0,
15815f2bd95SEwan Crawford        RS_TYPE_FLOAT_16,
15915f2bd95SEwan Crawford        RS_TYPE_FLOAT_32,
16015f2bd95SEwan Crawford        RS_TYPE_FLOAT_64,
16115f2bd95SEwan Crawford        RS_TYPE_SIGNED_8,
16215f2bd95SEwan Crawford        RS_TYPE_SIGNED_16,
16315f2bd95SEwan Crawford        RS_TYPE_SIGNED_32,
16415f2bd95SEwan Crawford        RS_TYPE_SIGNED_64,
16515f2bd95SEwan Crawford        RS_TYPE_UNSIGNED_8,
16615f2bd95SEwan Crawford        RS_TYPE_UNSIGNED_16,
16715f2bd95SEwan Crawford        RS_TYPE_UNSIGNED_32,
16815f2bd95SEwan Crawford        RS_TYPE_UNSIGNED_64,
16915f2bd95SEwan Crawford        RS_TYPE_BOOLEAN
17078f339d1SEwan Crawford     };
17178f339d1SEwan Crawford 
17215f2bd95SEwan Crawford     struct Dimension
17378f339d1SEwan Crawford     {
17415f2bd95SEwan Crawford         uint32_t dim_1;
17515f2bd95SEwan Crawford         uint32_t dim_2;
17615f2bd95SEwan Crawford         uint32_t dim_3;
17715f2bd95SEwan Crawford         uint32_t cubeMap;
17815f2bd95SEwan Crawford 
17915f2bd95SEwan Crawford         Dimension()
18015f2bd95SEwan Crawford         {
18115f2bd95SEwan Crawford              dim_1 = 0;
18215f2bd95SEwan Crawford              dim_2 = 0;
18315f2bd95SEwan Crawford              dim_3 = 0;
18415f2bd95SEwan Crawford              cubeMap = 0;
18515f2bd95SEwan Crawford         }
18678f339d1SEwan Crawford     };
18778f339d1SEwan Crawford 
18855232f09SEwan Crawford     // Header for reading and writing allocation contents
18955232f09SEwan Crawford     // to a binary file.
19055232f09SEwan Crawford     struct FileHeader
19155232f09SEwan Crawford     {
19255232f09SEwan Crawford         uint8_t ident[4];      // ASCII 'RSAD' identifying the file
19355232f09SEwan Crawford         uint16_t hdr_size;     // Header size in bytes, for backwards compatability
19455232f09SEwan Crawford         uint16_t type;         // DataType enum
19555232f09SEwan Crawford         uint32_t kind;         // DataKind enum
19655232f09SEwan Crawford         uint32_t dims[3];      // Dimensions
19755232f09SEwan Crawford         uint32_t element_size; // Size of a single element, including padding
19855232f09SEwan Crawford     };
19955232f09SEwan Crawford 
20015f2bd95SEwan Crawford     // Monotonically increasing from 1
20115f2bd95SEwan Crawford     static unsigned int ID;
20215f2bd95SEwan Crawford 
20315f2bd95SEwan Crawford     // Maps Allocation DataType enum and vector size to printable strings
20415f2bd95SEwan Crawford     // using mapping from RenderScript numerical types summary documentation
20515f2bd95SEwan Crawford     static const char* RsDataTypeToString[][4];
20615f2bd95SEwan Crawford 
20715f2bd95SEwan Crawford     // Maps Allocation DataKind enum to printable strings
20815f2bd95SEwan Crawford     static const char* RsDataKindToString[];
20915f2bd95SEwan Crawford 
210a0f08674SEwan Crawford     // Maps allocation types to format sizes for printing.
211a0f08674SEwan Crawford     static const unsigned int RSTypeToFormat[][3];
212a0f08674SEwan Crawford 
21315f2bd95SEwan Crawford     // Give each allocation an ID as a way
21415f2bd95SEwan Crawford     // for commands to reference it.
21515f2bd95SEwan Crawford     const unsigned int id;
21615f2bd95SEwan Crawford 
21715f2bd95SEwan Crawford     empirical_type<DataType> type;            // Type of each data pointer stored by the allocation
21815f2bd95SEwan Crawford     empirical_type<DataKind> type_kind;       // Defines pixel type if Allocation is created from an image
21915f2bd95SEwan Crawford     empirical_type<uint32_t> type_vec_size;   // Vector size of each data point, e.g '4' for uchar4
22015f2bd95SEwan Crawford     empirical_type<Dimension> dimension;      // Dimensions of the Allocation
22115f2bd95SEwan Crawford     empirical_type<lldb::addr_t> address;     // Pointer to address of the RS Allocation
22215f2bd95SEwan Crawford     empirical_type<lldb::addr_t> data_ptr;    // Pointer to the data held by the Allocation
22315f2bd95SEwan Crawford     empirical_type<lldb::addr_t> type_ptr;    // Pointer to the RS Type of the Allocation
22415f2bd95SEwan Crawford     empirical_type<lldb::addr_t> element_ptr; // Pointer to the RS Element of the Type
22515f2bd95SEwan Crawford     empirical_type<lldb::addr_t> context;     // Pointer to the RS Context of the Allocation
226a0f08674SEwan Crawford     empirical_type<uint32_t> size;            // Size of the allocation
227a0f08674SEwan Crawford     empirical_type<uint32_t> stride;          // Stride between rows of the allocation
22815f2bd95SEwan Crawford 
22915f2bd95SEwan Crawford     // Give each allocation an id, so we can reference it in user commands.
23015f2bd95SEwan Crawford     AllocationDetails(): id(ID++)
23115f2bd95SEwan Crawford     {
23215f2bd95SEwan Crawford     }
23315f2bd95SEwan Crawford };
23415f2bd95SEwan Crawford 
23515f2bd95SEwan Crawford unsigned int RenderScriptRuntime::AllocationDetails::ID = 1;
23615f2bd95SEwan Crawford 
23715f2bd95SEwan Crawford const char* RenderScriptRuntime::AllocationDetails::RsDataKindToString[] =
23815f2bd95SEwan Crawford {
23915f2bd95SEwan Crawford    "User",
24015f2bd95SEwan Crawford    "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7
24115f2bd95SEwan Crawford    "Undefined", "Undefined", "Undefined",
24215f2bd95SEwan Crawford    "L Pixel",
24315f2bd95SEwan Crawford    "A Pixel",
24415f2bd95SEwan Crawford    "LA Pixel",
24515f2bd95SEwan Crawford    "RGB Pixel",
24615f2bd95SEwan Crawford    "RGBA Pixel",
24715f2bd95SEwan Crawford    "Pixel Depth",
24815f2bd95SEwan Crawford    "YUV Pixel"
24915f2bd95SEwan Crawford };
25015f2bd95SEwan Crawford 
25115f2bd95SEwan Crawford const char* RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] =
25215f2bd95SEwan Crawford {
25315f2bd95SEwan Crawford     {"None", "None", "None", "None"},
25415f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
25515f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
25615f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
25715f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
25815f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
25915f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
26015f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
26115f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
26215f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
26315f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
26415f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
26515f2bd95SEwan Crawford     {"bool", "bool2", "bool3", "bool4"}
26678f339d1SEwan Crawford };
26778f339d1SEwan Crawford 
268a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
269a0f08674SEwan Crawford enum TypeToFormatIndex {
270a0f08674SEwan Crawford    eFormatSingle = 0,
271a0f08674SEwan Crawford    eFormatVector,
272a0f08674SEwan Crawford    eElementSize
273a0f08674SEwan Crawford };
274a0f08674SEwan Crawford 
275a0f08674SEwan Crawford // { format enum of single element, format enum of element vector, size of element}
276a0f08674SEwan Crawford const unsigned int RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] =
277a0f08674SEwan Crawford {
278a0f08674SEwan Crawford     {eFormatHex, eFormatHex, 1}, // RS_TYPE_NONE
279a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat16, 2}, // RS_TYPE_FLOAT_16
280a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)}, // RS_TYPE_FLOAT_32
281a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)}, // RS_TYPE_FLOAT_64
282a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)}, // RS_TYPE_SIGNED_8
283a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)}, // RS_TYPE_SIGNED_16
284a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)}, // RS_TYPE_SIGNED_32
285a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)}, // RS_TYPE_SIGNED_64
286a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)}, // RS_TYPE_UNSIGNED_8
287a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_16
288a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)}, // RS_TYPE_UNSIGNED_32
289a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)}, // RS_TYPE_UNSIGNED_64
290a0f08674SEwan Crawford     {eFormatBoolean, eFormatBoolean, sizeof(bool)} // RS_TYPE_BOOL
291a0f08674SEwan Crawford };
292a0f08674SEwan Crawford 
2935ec532a9SColin Riley //------------------------------------------------------------------
2945ec532a9SColin Riley // Static Functions
2955ec532a9SColin Riley //------------------------------------------------------------------
2965ec532a9SColin Riley LanguageRuntime *
2975ec532a9SColin Riley RenderScriptRuntime::CreateInstance(Process *process, lldb::LanguageType language)
2985ec532a9SColin Riley {
2995ec532a9SColin Riley 
3005ec532a9SColin Riley     if (language == eLanguageTypeExtRenderScript)
3015ec532a9SColin Riley         return new RenderScriptRuntime(process);
3025ec532a9SColin Riley     else
3035ec532a9SColin Riley         return NULL;
3045ec532a9SColin Riley }
3055ec532a9SColin Riley 
30698156583SEwan Crawford // Callback with a module to search for matching symbols.
30798156583SEwan Crawford // We first check that the module contains RS kernels.
30898156583SEwan Crawford // Then look for a symbol which matches our kernel name.
30998156583SEwan Crawford // The breakpoint address is finally set using the address of this symbol.
31098156583SEwan Crawford Searcher::CallbackReturn
31198156583SEwan Crawford RSBreakpointResolver::SearchCallback(SearchFilter &filter,
31298156583SEwan Crawford                                      SymbolContext &context,
31398156583SEwan Crawford                                      Address*,
31498156583SEwan Crawford                                      bool)
31598156583SEwan Crawford {
31698156583SEwan Crawford     ModuleSP module = context.module_sp;
31798156583SEwan Crawford 
31898156583SEwan Crawford     if (!module)
31998156583SEwan Crawford         return Searcher::eCallbackReturnContinue;
32098156583SEwan Crawford 
32198156583SEwan Crawford     // Is this a module containing renderscript kernels?
32298156583SEwan Crawford     if (nullptr == module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData))
32398156583SEwan Crawford         return Searcher::eCallbackReturnContinue;
32498156583SEwan Crawford 
32598156583SEwan Crawford     // Attempt to set a breakpoint on the kernel name symbol within the module library.
32698156583SEwan Crawford     // If it's not found, it's likely debug info is unavailable - try to set a
32798156583SEwan Crawford     // breakpoint on <name>.expand.
32898156583SEwan Crawford 
32998156583SEwan Crawford     const Symbol* kernel_sym = module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
33098156583SEwan Crawford     if (!kernel_sym)
33198156583SEwan Crawford     {
33298156583SEwan Crawford         std::string kernel_name_expanded(m_kernel_name.AsCString());
33398156583SEwan Crawford         kernel_name_expanded.append(".expand");
33498156583SEwan Crawford         kernel_sym = module->FindFirstSymbolWithNameAndType(ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
33598156583SEwan Crawford     }
33698156583SEwan Crawford 
33798156583SEwan Crawford     if (kernel_sym)
33898156583SEwan Crawford     {
33998156583SEwan Crawford         Address bp_addr = kernel_sym->GetAddress();
34098156583SEwan Crawford         if (filter.AddressPasses(bp_addr))
34198156583SEwan Crawford             m_breakpoint->AddLocation(bp_addr);
34298156583SEwan Crawford     }
34398156583SEwan Crawford 
34498156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
34598156583SEwan Crawford }
34698156583SEwan Crawford 
3475ec532a9SColin Riley void
3485ec532a9SColin Riley RenderScriptRuntime::Initialize()
3495ec532a9SColin Riley {
3504640cde1SColin Riley     PluginManager::RegisterPlugin(GetPluginNameStatic(), "RenderScript language support", CreateInstance, GetCommandObject);
3515ec532a9SColin Riley }
3525ec532a9SColin Riley 
3535ec532a9SColin Riley void
3545ec532a9SColin Riley RenderScriptRuntime::Terminate()
3555ec532a9SColin Riley {
3565ec532a9SColin Riley     PluginManager::UnregisterPlugin(CreateInstance);
3575ec532a9SColin Riley }
3585ec532a9SColin Riley 
3595ec532a9SColin Riley lldb_private::ConstString
3605ec532a9SColin Riley RenderScriptRuntime::GetPluginNameStatic()
3615ec532a9SColin Riley {
3625ec532a9SColin Riley     static ConstString g_name("renderscript");
3635ec532a9SColin Riley     return g_name;
3645ec532a9SColin Riley }
3655ec532a9SColin Riley 
366ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
367ef20b08fSColin Riley RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp)
368ef20b08fSColin Riley {
369ef20b08fSColin Riley     if (module_sp)
370ef20b08fSColin Riley     {
371ef20b08fSColin Riley         // Is this a module containing renderscript kernels?
372ef20b08fSColin Riley         const Symbol *info_sym = module_sp->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
373ef20b08fSColin Riley         if (info_sym)
374ef20b08fSColin Riley         {
375ef20b08fSColin Riley             return eModuleKindKernelObj;
376ef20b08fSColin Riley         }
3774640cde1SColin Riley 
3784640cde1SColin Riley         // Is this the main RS runtime library
3794640cde1SColin Riley         const ConstString rs_lib("libRS.so");
3804640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_lib)
3814640cde1SColin Riley         {
3824640cde1SColin Riley             return eModuleKindLibRS;
3834640cde1SColin Riley         }
3844640cde1SColin Riley 
3854640cde1SColin Riley         const ConstString rs_driverlib("libRSDriver.so");
3864640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_driverlib)
3874640cde1SColin Riley         {
3884640cde1SColin Riley             return eModuleKindDriver;
3894640cde1SColin Riley         }
3904640cde1SColin Riley 
39115f2bd95SEwan Crawford         const ConstString rs_cpureflib("libRSCpuRef.so");
3924640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib)
3934640cde1SColin Riley         {
3944640cde1SColin Riley             return eModuleKindImpl;
3954640cde1SColin Riley         }
3964640cde1SColin Riley 
397ef20b08fSColin Riley     }
398ef20b08fSColin Riley     return eModuleKindIgnored;
399ef20b08fSColin Riley }
400ef20b08fSColin Riley 
401ef20b08fSColin Riley bool
402ef20b08fSColin Riley RenderScriptRuntime::IsRenderScriptModule(const lldb::ModuleSP &module_sp)
403ef20b08fSColin Riley {
404ef20b08fSColin Riley     return GetModuleKind(module_sp) != eModuleKindIgnored;
405ef20b08fSColin Riley }
406ef20b08fSColin Riley 
407ef20b08fSColin Riley void
408ef20b08fSColin Riley RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list )
409ef20b08fSColin Riley {
410ef20b08fSColin Riley     Mutex::Locker locker (module_list.GetMutex ());
411ef20b08fSColin Riley 
412ef20b08fSColin Riley     size_t num_modules = module_list.GetSize();
413ef20b08fSColin Riley     for (size_t i = 0; i < num_modules; i++)
414ef20b08fSColin Riley     {
415ef20b08fSColin Riley         auto mod = module_list.GetModuleAtIndex (i);
416ef20b08fSColin Riley         if (IsRenderScriptModule (mod))
417ef20b08fSColin Riley         {
418ef20b08fSColin Riley             LoadModule(mod);
419ef20b08fSColin Riley         }
420ef20b08fSColin Riley     }
421ef20b08fSColin Riley }
422ef20b08fSColin Riley 
4235ec532a9SColin Riley //------------------------------------------------------------------
4245ec532a9SColin Riley // PluginInterface protocol
4255ec532a9SColin Riley //------------------------------------------------------------------
4265ec532a9SColin Riley lldb_private::ConstString
4275ec532a9SColin Riley RenderScriptRuntime::GetPluginName()
4285ec532a9SColin Riley {
4295ec532a9SColin Riley     return GetPluginNameStatic();
4305ec532a9SColin Riley }
4315ec532a9SColin Riley 
4325ec532a9SColin Riley uint32_t
4335ec532a9SColin Riley RenderScriptRuntime::GetPluginVersion()
4345ec532a9SColin Riley {
4355ec532a9SColin Riley     return 1;
4365ec532a9SColin Riley }
4375ec532a9SColin Riley 
4385ec532a9SColin Riley bool
4395ec532a9SColin Riley RenderScriptRuntime::IsVTableName(const char *name)
4405ec532a9SColin Riley {
4415ec532a9SColin Riley     return false;
4425ec532a9SColin Riley }
4435ec532a9SColin Riley 
4445ec532a9SColin Riley bool
4455ec532a9SColin Riley RenderScriptRuntime::GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic,
4460b6003f3SEnrico Granata                                               TypeAndOrName &class_type_or_name, Address &address,
4470b6003f3SEnrico Granata                                               Value::ValueType &value_type)
4485ec532a9SColin Riley {
4495ec532a9SColin Riley     return false;
4505ec532a9SColin Riley }
4515ec532a9SColin Riley 
452c74275bcSEnrico Granata TypeAndOrName
453c74275bcSEnrico Granata RenderScriptRuntime::FixUpDynamicType (const TypeAndOrName& type_and_or_name,
4547eed4877SEnrico Granata                                        ValueObject& static_value)
455c74275bcSEnrico Granata {
456c74275bcSEnrico Granata     return type_and_or_name;
457c74275bcSEnrico Granata }
458c74275bcSEnrico Granata 
4595ec532a9SColin Riley bool
4605ec532a9SColin Riley RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value)
4615ec532a9SColin Riley {
4625ec532a9SColin Riley     return false;
4635ec532a9SColin Riley }
4645ec532a9SColin Riley 
4655ec532a9SColin Riley lldb::BreakpointResolverSP
4665ec532a9SColin Riley RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp, bool throw_bp)
4675ec532a9SColin Riley {
4685ec532a9SColin Riley     BreakpointResolverSP resolver_sp;
4695ec532a9SColin Riley     return resolver_sp;
4705ec532a9SColin Riley }
4715ec532a9SColin Riley 
4724640cde1SColin Riley const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
4734640cde1SColin Riley {
4744640cde1SColin Riley     //rsdScript
47582780287SAidan Dodds     {
47682780287SAidan Dodds         "rsdScriptInit", //name
47782780287SAidan Dodds         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhjj", // symbol name 32 bit
47882780287SAidan Dodds         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhmj", // symbol name 64 bit
47982780287SAidan Dodds         0, // version
48082780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
48182780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureScriptInit1 // handler
48282780287SAidan Dodds     },
48382780287SAidan Dodds     {
48482780287SAidan Dodds         "rsdScriptInvokeForEach", // name
48582780287SAidan Dodds         "_Z22rsdScriptInvokeForEachPKN7android12renderscript7ContextEPNS0_6ScriptEjPKNS0_10AllocationEPS6_PKvjPK12RsScriptCall", // symbol name 32bit
48682780287SAidan Dodds         "_Z22rsdScriptInvokeForEachPKN7android12renderscript7ContextEPNS0_6ScriptEjPKNS0_10AllocationEPS6_PKvmPK12RsScriptCall", // symbol name 64bit
48782780287SAidan Dodds         0, // version
48882780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
48982780287SAidan Dodds         nullptr // handler
49082780287SAidan Dodds     },
49182780287SAidan Dodds     {
49282780287SAidan Dodds         "rsdScriptInvokeForEachMulti", // name
49382780287SAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall", // symbol name 32bit
49482780287SAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall", // symbol name 64bit
49582780287SAidan Dodds         0, // version
49682780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
49782780287SAidan Dodds         nullptr // handler
49882780287SAidan Dodds     },
49982780287SAidan Dodds     {
50082780287SAidan Dodds         "rsdScriptInvokeFunction", // name
50182780287SAidan Dodds         "_Z23rsdScriptInvokeFunctionPKN7android12renderscript7ContextEPNS0_6ScriptEjPKvj", // symbol name 32bit
50282780287SAidan Dodds         "_Z23rsdScriptInvokeFunctionPKN7android12renderscript7ContextEPNS0_6ScriptEjPKvm", // symbol name 64bit
50382780287SAidan Dodds         0, // version
50482780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
50582780287SAidan Dodds         nullptr // handler
50682780287SAidan Dodds     },
50782780287SAidan Dodds     {
50882780287SAidan Dodds         "rsdScriptSetGlobalVar", // name
50982780287SAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvj", // symbol name 32bit
51082780287SAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvm", // symbol name 64bit
51182780287SAidan Dodds         0, // version
51282780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
51382780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar1 // handler
51482780287SAidan Dodds     },
5154640cde1SColin Riley 
5164640cde1SColin Riley     //rsdAllocation
51782780287SAidan Dodds     {
51882780287SAidan Dodds         "rsdAllocationInit", // name
51982780287SAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 32bit
52082780287SAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 64bit
52182780287SAidan Dodds         0, // version
52282780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
52382780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureAllocationInit1 // handler
52482780287SAidan Dodds     },
52582780287SAidan Dodds     {
52682780287SAidan Dodds         "rsdAllocationRead2D", //name
52782780287SAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvjj", // symbol name 32bit
52882780287SAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvmm", // symbol name 64bit
52982780287SAidan Dodds         0, // version
53082780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
53182780287SAidan Dodds         nullptr // handler
53282780287SAidan Dodds     },
5334640cde1SColin Riley };
5344640cde1SColin Riley 
535222b937cSEugene Zelenko const size_t RenderScriptRuntime::s_runtimeHookCount = sizeof(s_runtimeHookDefns)/sizeof(s_runtimeHookDefns[0]);
5364640cde1SColin Riley 
5374640cde1SColin Riley bool
5384640cde1SColin Riley RenderScriptRuntime::HookCallback(void *baton, StoppointCallbackContext *ctx, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
5394640cde1SColin Riley {
5404640cde1SColin Riley     RuntimeHook* hook_info = (RuntimeHook*)baton;
5414640cde1SColin Riley     ExecutionContext context(ctx->exe_ctx_ref);
5424640cde1SColin Riley 
5434640cde1SColin Riley     RenderScriptRuntime *lang_rt = (RenderScriptRuntime *)context.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
5444640cde1SColin Riley 
5454640cde1SColin Riley     lang_rt->HookCallback(hook_info, context);
5464640cde1SColin Riley 
5474640cde1SColin Riley     return false;
5484640cde1SColin Riley }
5494640cde1SColin Riley 
5504640cde1SColin Riley void
5514640cde1SColin Riley RenderScriptRuntime::HookCallback(RuntimeHook* hook_info, ExecutionContext& context)
5524640cde1SColin Riley {
5534640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
5544640cde1SColin Riley 
5554640cde1SColin Riley     if (log)
5564640cde1SColin Riley         log->Printf ("RenderScriptRuntime::HookCallback - '%s' .", hook_info->defn->name);
5574640cde1SColin Riley 
5584640cde1SColin Riley     if (hook_info->defn->grabber)
5594640cde1SColin Riley     {
5604640cde1SColin Riley         (this->*(hook_info->defn->grabber))(hook_info, context);
5614640cde1SColin Riley     }
5624640cde1SColin Riley }
5634640cde1SColin Riley 
5644640cde1SColin Riley bool
56582780287SAidan Dodds RenderScriptRuntime::GetArgSimple(ExecutionContext &context, uint32_t arg, uint64_t *data)
5664640cde1SColin Riley {
5674640cde1SColin Riley     if (!data)
5684640cde1SColin Riley         return false;
5694640cde1SColin Riley 
57082780287SAidan Dodds     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
5714640cde1SColin Riley     Error error;
5724640cde1SColin Riley     RegisterContext* reg_ctx = context.GetRegisterContext();
5734640cde1SColin Riley     Process* process = context.GetProcessPtr();
57482780287SAidan Dodds     bool success = false; // return value
5754640cde1SColin Riley 
57682780287SAidan Dodds     if (!context.GetTargetPtr())
57782780287SAidan Dodds     {
57882780287SAidan Dodds         if (log)
57982780287SAidan Dodds             log->Printf("RenderScriptRuntime::GetArgSimple - Invalid target");
58082780287SAidan Dodds 
58182780287SAidan Dodds         return false;
58282780287SAidan Dodds     }
58382780287SAidan Dodds 
58482780287SAidan Dodds     switch (context.GetTargetPtr()->GetArchitecture().GetMachine())
58582780287SAidan Dodds     {
58682780287SAidan Dodds         case llvm::Triple::ArchType::x86:
5874640cde1SColin Riley         {
5884640cde1SColin Riley             uint64_t sp = reg_ctx->GetSP();
5894640cde1SColin Riley             uint32_t offset = (1 + arg) * sizeof(uint32_t);
59082780287SAidan Dodds             uint32_t result = 0;
59182780287SAidan Dodds             process->ReadMemory(sp + offset, &result, sizeof(uint32_t), error);
5924640cde1SColin Riley             if (error.Fail())
5934640cde1SColin Riley             {
5944640cde1SColin Riley                 if (log)
59582780287SAidan Dodds                     log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading X86 stack: %s.", error.AsCString());
5964640cde1SColin Riley             }
59782780287SAidan Dodds             else
5984640cde1SColin Riley             {
59982780287SAidan Dodds                 *data = result;
60082780287SAidan Dodds                 success = true;
60182780287SAidan Dodds             }
60282780287SAidan Dodds 
60382780287SAidan Dodds             break;
60482780287SAidan Dodds         }
60582780287SAidan Dodds         case llvm::Triple::ArchType::arm:
60682780287SAidan Dodds         {
60782780287SAidan Dodds             // arm 32 bit
6084640cde1SColin Riley             if (arg < 4)
6094640cde1SColin Riley             {
6104640cde1SColin Riley                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg);
6114640cde1SColin Riley                 RegisterValue rVal;
61202f1c5d1SEwan Crawford                 success = reg_ctx->ReadRegister(rArg, rVal);
61302f1c5d1SEwan Crawford                 if (success)
61402f1c5d1SEwan Crawford                 {
6154640cde1SColin Riley                     (*data) = rVal.GetAsUInt32();
61602f1c5d1SEwan Crawford                 }
61702f1c5d1SEwan Crawford                 else
61802f1c5d1SEwan Crawford                 {
61902f1c5d1SEwan Crawford                     if (log)
62002f1c5d1SEwan Crawford                         log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading ARM register: %d.", arg);
62102f1c5d1SEwan Crawford                 }
6224640cde1SColin Riley             }
6234640cde1SColin Riley             else
6244640cde1SColin Riley             {
6254640cde1SColin Riley                 uint64_t sp = reg_ctx->GetSP();
6264640cde1SColin Riley                 uint32_t offset = (arg-4) * sizeof(uint32_t);
6274640cde1SColin Riley                 process->ReadMemory(sp + offset, &data, sizeof(uint32_t), error);
6284640cde1SColin Riley                 if (error.Fail())
6294640cde1SColin Riley                 {
6304640cde1SColin Riley                     if (log)
63182780287SAidan Dodds                         log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading ARM stack: %s.", error.AsCString());
63282780287SAidan Dodds                 }
63382780287SAidan Dodds                 else
63482780287SAidan Dodds                 {
63582780287SAidan Dodds                     success = true;
6364640cde1SColin Riley                 }
6374640cde1SColin Riley             }
63882780287SAidan Dodds 
63982780287SAidan Dodds             break;
6404640cde1SColin Riley         }
64182780287SAidan Dodds         case llvm::Triple::ArchType::aarch64:
64282780287SAidan Dodds         {
64382780287SAidan Dodds             // arm 64 bit
64482780287SAidan Dodds             // first 8 arguments are in the registers
64582780287SAidan Dodds             if (arg < 8)
64682780287SAidan Dodds             {
64782780287SAidan Dodds                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg);
64882780287SAidan Dodds                 RegisterValue rVal;
64982780287SAidan Dodds                 success = reg_ctx->ReadRegister(rArg, rVal);
65082780287SAidan Dodds                 if (success)
65182780287SAidan Dodds                 {
65282780287SAidan Dodds                     *data = rVal.GetAsUInt64();
65382780287SAidan Dodds                 }
65482780287SAidan Dodds                 else
65582780287SAidan Dodds                 {
65682780287SAidan Dodds                     if (log)
65782780287SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple() - AARCH64 - Error while reading the argument #%d", arg);
65882780287SAidan Dodds                 }
65982780287SAidan Dodds             }
66082780287SAidan Dodds             else
66182780287SAidan Dodds             {
66282780287SAidan Dodds                 // @TODO: need to find the argument in the stack
66382780287SAidan Dodds                 if (log)
66482780287SAidan Dodds                     log->Printf("RenderScriptRuntime::GetArgSimple - AARCH64 - FOR #ARG >= 8 NOT IMPLEMENTED YET. Argument number: %d", arg);
66582780287SAidan Dodds             }
66682780287SAidan Dodds             break;
66782780287SAidan Dodds         }
668*74b396d9SAidan Dodds         case llvm::Triple::ArchType::mipsel:
669*74b396d9SAidan Dodds         {
670*74b396d9SAidan Dodds 
671*74b396d9SAidan Dodds             // read from the registers
672*74b396d9SAidan Dodds             if (arg < 4){
673*74b396d9SAidan Dodds                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg + 4);
674*74b396d9SAidan Dodds                 RegisterValue rVal;
675*74b396d9SAidan Dodds                 success = reg_ctx->ReadRegister(rArg, rVal);
676*74b396d9SAidan Dodds                 if (success)
677*74b396d9SAidan Dodds                 {
678*74b396d9SAidan Dodds                     *data = rVal.GetAsUInt64();
679*74b396d9SAidan Dodds                 }
680*74b396d9SAidan Dodds                 else
681*74b396d9SAidan Dodds                 {
682*74b396d9SAidan Dodds                     if (log)
683*74b396d9SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple() - Mips - Error while reading the argument #%d", arg);
684*74b396d9SAidan Dodds                 }
685*74b396d9SAidan Dodds 
686*74b396d9SAidan Dodds             }
687*74b396d9SAidan Dodds 
688*74b396d9SAidan Dodds             // read from the stack
689*74b396d9SAidan Dodds             else
690*74b396d9SAidan Dodds             {
691*74b396d9SAidan Dodds                 uint64_t sp = reg_ctx->GetSP();
692*74b396d9SAidan Dodds                 uint32_t offset = arg * sizeof(uint32_t);
693*74b396d9SAidan Dodds                 process->ReadMemory(sp + offset, &data, sizeof(uint32_t), error);
694*74b396d9SAidan Dodds                 if (error.Fail())
695*74b396d9SAidan Dodds                 {
696*74b396d9SAidan Dodds                     if (log)
697*74b396d9SAidan Dodds                         log->Printf ("RenderScriptRuntime::GetArgSimple - error reading Mips stack: %s.", error.AsCString());
698*74b396d9SAidan Dodds                 }
699*74b396d9SAidan Dodds                 else
700*74b396d9SAidan Dodds                 {
701*74b396d9SAidan Dodds                     success = true;
702*74b396d9SAidan Dodds                 }
703*74b396d9SAidan Dodds             }
704*74b396d9SAidan Dodds 
705*74b396d9SAidan Dodds             break;
706*74b396d9SAidan Dodds         }
70702f1c5d1SEwan Crawford         case llvm::Triple::ArchType::mips64el:
70802f1c5d1SEwan Crawford         {
70902f1c5d1SEwan Crawford             // read from the registers
71002f1c5d1SEwan Crawford             if (arg < 8)
71102f1c5d1SEwan Crawford             {
71202f1c5d1SEwan Crawford                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg + 4);
71302f1c5d1SEwan Crawford                 RegisterValue rVal;
71402f1c5d1SEwan Crawford                 success = reg_ctx->ReadRegister(rArg, rVal);
71502f1c5d1SEwan Crawford                 if (success)
71602f1c5d1SEwan Crawford                 {
71702f1c5d1SEwan Crawford                     (*data) = rVal.GetAsUInt64();
71802f1c5d1SEwan Crawford                 }
71902f1c5d1SEwan Crawford                 else
72002f1c5d1SEwan Crawford                 {
72102f1c5d1SEwan Crawford                     if (log)
72202f1c5d1SEwan Crawford                         log->Printf("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading the argument #%d", arg);
72302f1c5d1SEwan Crawford                 }
72402f1c5d1SEwan Crawford             }
72502f1c5d1SEwan Crawford 
72602f1c5d1SEwan Crawford             // read from the stack
72702f1c5d1SEwan Crawford             else
72802f1c5d1SEwan Crawford             {
72902f1c5d1SEwan Crawford                 uint64_t sp = reg_ctx->GetSP();
73002f1c5d1SEwan Crawford                 uint32_t offset = (arg - 8) * sizeof(uint64_t);
73102f1c5d1SEwan Crawford                 process->ReadMemory(sp + offset, &data, sizeof(uint64_t), error);
73202f1c5d1SEwan Crawford                 if (error.Fail())
73302f1c5d1SEwan Crawford                 {
73402f1c5d1SEwan Crawford                     if (log)
73502f1c5d1SEwan Crawford                         log->Printf ("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading Mips64 stack: %s.", error.AsCString());
73602f1c5d1SEwan Crawford                 }
73702f1c5d1SEwan Crawford                 else
73802f1c5d1SEwan Crawford                 {
73902f1c5d1SEwan Crawford                     success = true;
74002f1c5d1SEwan Crawford                 }
74102f1c5d1SEwan Crawford             }
74202f1c5d1SEwan Crawford 
74302f1c5d1SEwan Crawford             break;
74402f1c5d1SEwan Crawford         }
74582780287SAidan Dodds         default:
74682780287SAidan Dodds         {
74782780287SAidan Dodds             // invalid architecture
74882780287SAidan Dodds             if (log)
74982780287SAidan Dodds                 log->Printf("RenderScriptRuntime::GetArgSimple - Architecture not supported");
75082780287SAidan Dodds 
75182780287SAidan Dodds         }
75282780287SAidan Dodds     }
75382780287SAidan Dodds 
75482780287SAidan Dodds     return success;
7554640cde1SColin Riley }
7564640cde1SColin Riley 
7574640cde1SColin Riley void
7584640cde1SColin Riley RenderScriptRuntime::CaptureSetGlobalVar1(RuntimeHook* hook_info, ExecutionContext& context)
7594640cde1SColin Riley {
7604640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
7614640cde1SColin Riley 
7624640cde1SColin Riley     //Context, Script, int, data, length
7634640cde1SColin Riley 
76482780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
76582780287SAidan Dodds     uint64_t rs_script_u64 = 0U;
76682780287SAidan Dodds     uint64_t rs_id_u64 = 0U;
76782780287SAidan Dodds     uint64_t rs_data_u64 = 0U;
76882780287SAidan Dodds     uint64_t rs_length_u64 = 0U;
7694640cde1SColin Riley 
77082780287SAidan Dodds     bool success =
77182780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
77282780287SAidan Dodds         GetArgSimple(context, 1, &rs_script_u64) &&
77382780287SAidan Dodds         GetArgSimple(context, 2, &rs_id_u64) &&
77482780287SAidan Dodds         GetArgSimple(context, 3, &rs_data_u64) &&
77582780287SAidan Dodds         GetArgSimple(context, 4, &rs_length_u64);
7764640cde1SColin Riley 
77782780287SAidan Dodds     if (!success)
77882780287SAidan Dodds     {
77982780287SAidan Dodds         if (log)
78082780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureSetGlobalVar1 - Error while reading the function parameters");
78182780287SAidan Dodds         return;
78282780287SAidan Dodds     }
7834640cde1SColin Riley 
7844640cde1SColin Riley     if (log)
7854640cde1SColin Riley     {
7864640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64 ":%" PRIu64 "bytes.",
78782780287SAidan Dodds                         rs_context_u64, rs_script_u64, rs_id_u64, rs_data_u64, rs_length_u64);
7884640cde1SColin Riley 
78982780287SAidan Dodds         addr_t script_addr =  (addr_t)rs_script_u64;
7904640cde1SColin Riley         if (m_scriptMappings.find( script_addr ) != m_scriptMappings.end())
7914640cde1SColin Riley         {
7924640cde1SColin Riley             auto rsm = m_scriptMappings[script_addr];
79382780287SAidan Dodds             if (rs_id_u64 < rsm->m_globals.size())
7944640cde1SColin Riley             {
79582780287SAidan Dodds                 auto rsg = rsm->m_globals[rs_id_u64];
7964640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - Setting of '%s' within '%s' inferred", rsg.m_name.AsCString(),
7974640cde1SColin Riley                                 rsm->m_module->GetFileSpec().GetFilename().AsCString());
7984640cde1SColin Riley             }
7994640cde1SColin Riley         }
8004640cde1SColin Riley     }
8014640cde1SColin Riley }
8024640cde1SColin Riley 
8034640cde1SColin Riley void
8044640cde1SColin Riley RenderScriptRuntime::CaptureAllocationInit1(RuntimeHook* hook_info, ExecutionContext& context)
8054640cde1SColin Riley {
8064640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
8074640cde1SColin Riley 
8084640cde1SColin Riley     //Context, Alloc, bool
8094640cde1SColin Riley 
81082780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
81182780287SAidan Dodds     uint64_t rs_alloc_u64 = 0U;
81282780287SAidan Dodds     uint64_t rs_forceZero_u64 = 0U;
8134640cde1SColin Riley 
81482780287SAidan Dodds     bool success =
81582780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
81682780287SAidan Dodds         GetArgSimple(context, 1, &rs_alloc_u64) &&
81782780287SAidan Dodds         GetArgSimple(context, 2, &rs_forceZero_u64);
81882780287SAidan Dodds     if (!success) // error case
81982780287SAidan Dodds     {
82082780287SAidan Dodds         if (log)
82182780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureAllocationInit1 - Error while reading the function parameters");
82282780287SAidan Dodds         return; // abort
82382780287SAidan Dodds     }
8244640cde1SColin Riley 
8254640cde1SColin Riley     if (log)
8264640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureAllocationInit1 - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
82782780287SAidan Dodds                         rs_context_u64, rs_alloc_u64, rs_forceZero_u64);
82878f339d1SEwan Crawford 
82978f339d1SEwan Crawford     AllocationDetails* alloc = LookUpAllocation(rs_alloc_u64, true);
83078f339d1SEwan Crawford     if (alloc)
83178f339d1SEwan Crawford         alloc->context = rs_context_u64;
8324640cde1SColin Riley }
8334640cde1SColin Riley 
8344640cde1SColin Riley void
8354640cde1SColin Riley RenderScriptRuntime::CaptureScriptInit1(RuntimeHook* hook_info, ExecutionContext& context)
8364640cde1SColin Riley {
8374640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
8384640cde1SColin Riley 
8394640cde1SColin Riley     //Context, Script, resname Str, cachedir Str
8404640cde1SColin Riley     Error error;
8414640cde1SColin Riley     Process* process = context.GetProcessPtr();
8424640cde1SColin Riley 
84382780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
84482780287SAidan Dodds     uint64_t rs_script_u64 = 0U;
84582780287SAidan Dodds     uint64_t rs_resnameptr_u64 = 0U;
84682780287SAidan Dodds     uint64_t rs_cachedirptr_u64 = 0U;
8474640cde1SColin Riley 
8484640cde1SColin Riley     std::string resname;
8494640cde1SColin Riley     std::string cachedir;
8504640cde1SColin Riley 
85182780287SAidan Dodds     // read the function parameters
85282780287SAidan Dodds     bool success =
85382780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
85482780287SAidan Dodds         GetArgSimple(context, 1, &rs_script_u64) &&
85582780287SAidan Dodds         GetArgSimple(context, 2, &rs_resnameptr_u64) &&
85682780287SAidan Dodds         GetArgSimple(context, 3, &rs_cachedirptr_u64);
8574640cde1SColin Riley 
85882780287SAidan Dodds     if (!success)
85982780287SAidan Dodds     {
86082780287SAidan Dodds         if (log)
86182780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureScriptInit1 - Error while reading the function parameters");
86282780287SAidan Dodds         return;
86382780287SAidan Dodds     }
86482780287SAidan Dodds 
86582780287SAidan Dodds     process->ReadCStringFromMemory((lldb::addr_t)rs_resnameptr_u64, resname, error);
8664640cde1SColin Riley     if (error.Fail())
8674640cde1SColin Riley     {
8684640cde1SColin Riley         if (log)
8694640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading resname: %s.", error.AsCString());
8704640cde1SColin Riley 
8714640cde1SColin Riley     }
8724640cde1SColin Riley 
87382780287SAidan Dodds     process->ReadCStringFromMemory((lldb::addr_t)rs_cachedirptr_u64, cachedir, error);
8744640cde1SColin Riley     if (error.Fail())
8754640cde1SColin Riley     {
8764640cde1SColin Riley         if (log)
8774640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading cachedir: %s.", error.AsCString());
8784640cde1SColin Riley     }
8794640cde1SColin Riley 
8804640cde1SColin Riley     if (log)
8814640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
88282780287SAidan Dodds                      rs_context_u64, rs_script_u64, resname.c_str(), cachedir.c_str());
8834640cde1SColin Riley 
8844640cde1SColin Riley     if (resname.size() > 0)
8854640cde1SColin Riley     {
8864640cde1SColin Riley         StreamString strm;
8874640cde1SColin Riley         strm.Printf("librs.%s.so", resname.c_str());
8884640cde1SColin Riley 
88978f339d1SEwan Crawford         ScriptDetails* script = LookUpScript(rs_script_u64, true);
89078f339d1SEwan Crawford         if (script)
89178f339d1SEwan Crawford         {
89278f339d1SEwan Crawford             script->type = ScriptDetails::eScriptC;
89378f339d1SEwan Crawford             script->cacheDir = cachedir;
89478f339d1SEwan Crawford             script->resName = resname;
89578f339d1SEwan Crawford             script->scriptDyLib = strm.GetData();
89678f339d1SEwan Crawford             script->context = addr_t(rs_context_u64);
89778f339d1SEwan Crawford         }
8984640cde1SColin Riley 
8994640cde1SColin Riley         if (log)
9004640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - '%s' tagged with context 0x%" PRIx64 " and script 0x%" PRIx64 ".",
90182780287SAidan Dodds                          strm.GetData(), rs_context_u64, rs_script_u64);
9024640cde1SColin Riley     }
9034640cde1SColin Riley     else if (log)
9044640cde1SColin Riley     {
9054640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - resource name invalid, Script not tagged");
9064640cde1SColin Riley     }
9074640cde1SColin Riley }
9084640cde1SColin Riley 
9094640cde1SColin Riley void
9104640cde1SColin Riley RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind)
9114640cde1SColin Riley {
9124640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
9134640cde1SColin Riley 
9144640cde1SColin Riley     if (!module)
9154640cde1SColin Riley     {
9164640cde1SColin Riley         return;
9174640cde1SColin Riley     }
9184640cde1SColin Riley 
91982780287SAidan Dodds     Target &target = GetProcess()->GetTarget();
92082780287SAidan Dodds     llvm::Triple::ArchType targetArchType = target.GetArchitecture().GetMachine();
92182780287SAidan Dodds 
92282780287SAidan Dodds     if (targetArchType != llvm::Triple::ArchType::x86
92382780287SAidan Dodds         && targetArchType != llvm::Triple::ArchType::arm
92402f1c5d1SEwan Crawford         && targetArchType != llvm::Triple::ArchType::aarch64
925*74b396d9SAidan Dodds         && targetArchType != llvm::Triple::ArchType::mipsel
92602f1c5d1SEwan Crawford         && targetArchType != llvm::Triple::ArchType::mips64el
92702f1c5d1SEwan Crawford     )
9284640cde1SColin Riley     {
9294640cde1SColin Riley         if (log)
930*74b396d9SAidan Dodds             log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to hook runtime. Only X86, ARM, Mips supported currently.");
9314640cde1SColin Riley 
9324640cde1SColin Riley         return;
9334640cde1SColin Riley     }
9344640cde1SColin Riley 
93582780287SAidan Dodds     uint32_t archByteSize = target.GetArchitecture().GetAddressByteSize();
9364640cde1SColin Riley 
9374640cde1SColin Riley     for (size_t idx = 0; idx < s_runtimeHookCount; idx++)
9384640cde1SColin Riley     {
9394640cde1SColin Riley         const HookDefn* hook_defn = &s_runtimeHookDefns[idx];
9404640cde1SColin Riley         if (hook_defn->kind != kind) {
9414640cde1SColin Riley             continue;
9424640cde1SColin Riley         }
9434640cde1SColin Riley 
94482780287SAidan Dodds         const char* symbol_name = (archByteSize == 4) ? hook_defn->symbol_name_m32 : hook_defn->symbol_name_m64;
94582780287SAidan Dodds 
94682780287SAidan Dodds         const Symbol *sym = module->FindFirstSymbolWithNameAndType(ConstString(symbol_name), eSymbolTypeCode);
94782780287SAidan Dodds         if (!sym){
94882780287SAidan Dodds             if (log){
94982780287SAidan Dodds                 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - ERROR: Symbol '%s' related to the function %s not found", symbol_name, hook_defn->name);
95082780287SAidan Dodds             }
95182780287SAidan Dodds             continue;
95282780287SAidan Dodds         }
9534640cde1SColin Riley 
954358cf1eaSGreg Clayton         addr_t addr = sym->GetLoadAddress(&target);
9554640cde1SColin Riley         if (addr == LLDB_INVALID_ADDRESS)
9564640cde1SColin Riley         {
9574640cde1SColin Riley             if (log)
9584640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to resolve the address of hook function '%s' with symbol '%s'.",
95982780287SAidan Dodds                              hook_defn->name, symbol_name);
9604640cde1SColin Riley             continue;
9614640cde1SColin Riley         }
96282780287SAidan Dodds         else
96382780287SAidan Dodds         {
96482780287SAidan Dodds             if (log)
96582780287SAidan Dodds                 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - Function %s, address resolved at 0x%" PRIx64, hook_defn->name, addr);
96682780287SAidan Dodds         }
9674640cde1SColin Riley 
9684640cde1SColin Riley         RuntimeHookSP hook(new RuntimeHook());
9694640cde1SColin Riley         hook->address = addr;
9704640cde1SColin Riley         hook->defn = hook_defn;
9714640cde1SColin Riley         hook->bp_sp = target.CreateBreakpoint(addr, true, false);
9724640cde1SColin Riley         hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
9734640cde1SColin Riley         m_runtimeHooks[addr] = hook;
9744640cde1SColin Riley         if (log)
9754640cde1SColin Riley         {
9764640cde1SColin Riley             log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Successfully hooked '%s' in '%s' version %" PRIu64 " at 0x%" PRIx64 ".",
9774640cde1SColin Riley                 hook_defn->name, module->GetFileSpec().GetFilename().AsCString(), (uint64_t)hook_defn->version, (uint64_t)addr);
9784640cde1SColin Riley         }
9794640cde1SColin Riley     }
9804640cde1SColin Riley }
9814640cde1SColin Riley 
9824640cde1SColin Riley void
9834640cde1SColin Riley RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp)
9844640cde1SColin Riley {
9854640cde1SColin Riley     if (!rsmodule_sp)
9864640cde1SColin Riley         return;
9874640cde1SColin Riley 
9884640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
9894640cde1SColin Riley 
9904640cde1SColin Riley     const ModuleSP module = rsmodule_sp->m_module;
9914640cde1SColin Riley     const FileSpec& file = module->GetPlatformFileSpec();
9924640cde1SColin Riley 
99378f339d1SEwan Crawford     // Iterate over all of the scripts that we currently know of.
99478f339d1SEwan Crawford     // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
9954640cde1SColin Riley     for (const auto & rs_script : m_scripts)
9964640cde1SColin Riley     {
99778f339d1SEwan Crawford         // Extract the expected .so file path for this script.
99878f339d1SEwan Crawford         std::string dylib;
99978f339d1SEwan Crawford         if (!rs_script->scriptDyLib.get(dylib))
100078f339d1SEwan Crawford             continue;
100178f339d1SEwan Crawford 
100278f339d1SEwan Crawford         // Only proceed if the module that has loaded corresponds to this script.
100378f339d1SEwan Crawford         if (file.GetFilename() != ConstString(dylib.c_str()))
100478f339d1SEwan Crawford             continue;
100578f339d1SEwan Crawford 
100678f339d1SEwan Crawford         // Obtain the script address which we use as a key.
100778f339d1SEwan Crawford         lldb::addr_t script;
100878f339d1SEwan Crawford         if (!rs_script->script.get(script))
100978f339d1SEwan Crawford             continue;
101078f339d1SEwan Crawford 
101178f339d1SEwan Crawford         // If we have a script mapping for the current script.
101278f339d1SEwan Crawford         if (m_scriptMappings.find(script) != m_scriptMappings.end())
10134640cde1SColin Riley         {
101478f339d1SEwan Crawford             // if the module we have stored is different to the one we just received.
101578f339d1SEwan Crawford             if (m_scriptMappings[script] != rsmodule_sp)
10164640cde1SColin Riley             {
10174640cde1SColin Riley                 if (log)
10184640cde1SColin Riley                     log->Printf ("RenderScriptRuntime::FixupScriptDetails - Error: script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
101978f339d1SEwan Crawford                                     (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
10204640cde1SColin Riley             }
10214640cde1SColin Riley         }
102278f339d1SEwan Crawford         // We don't have a script mapping for the current script.
10234640cde1SColin Riley         else
10244640cde1SColin Riley         {
102578f339d1SEwan Crawford             // Obtain the script resource name.
102678f339d1SEwan Crawford             std::string resName;
102778f339d1SEwan Crawford             if (rs_script->resName.get(resName))
102878f339d1SEwan Crawford                 // Set the modules resource name.
102978f339d1SEwan Crawford                 rsmodule_sp->m_resname = resName;
103078f339d1SEwan Crawford             // Add Script/Module pair to map.
103178f339d1SEwan Crawford             m_scriptMappings[script] = rsmodule_sp;
10324640cde1SColin Riley             if (log)
10334640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::FixupScriptDetails - script %" PRIx64 " associated with rsmodule '%s'.",
103478f339d1SEwan Crawford                                 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
10354640cde1SColin Riley         }
10364640cde1SColin Riley     }
10374640cde1SColin Riley }
10384640cde1SColin Riley 
103915f2bd95SEwan Crawford // Uses the Target API to evaluate the expression passed as a parameter to the function
104015f2bd95SEwan Crawford // The result of that expression is returned an unsigned 64 bit int, via the result* paramter.
104115f2bd95SEwan Crawford // Function returns true on success, and false on failure
104215f2bd95SEwan Crawford bool
104315f2bd95SEwan Crawford RenderScriptRuntime::EvalRSExpression(const char* expression, StackFrame* frame_ptr, uint64_t* result)
104415f2bd95SEwan Crawford {
104515f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
104615f2bd95SEwan Crawford     if (log)
104715f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::EvalRSExpression(%s)", expression);
104815f2bd95SEwan Crawford 
104915f2bd95SEwan Crawford     ValueObjectSP expr_result;
105015f2bd95SEwan Crawford     // Perform the actual expression evaluation
105115f2bd95SEwan Crawford     GetProcess()->GetTarget().EvaluateExpression(expression, frame_ptr, expr_result);
105215f2bd95SEwan Crawford 
105315f2bd95SEwan Crawford     if (!expr_result)
105415f2bd95SEwan Crawford     {
105515f2bd95SEwan Crawford        if (log)
105615f2bd95SEwan Crawford            log->Printf("RenderScriptRuntime::EvalRSExpression -  Error: Couldn't evaluate expression");
105715f2bd95SEwan Crawford        return false;
105815f2bd95SEwan Crawford     }
105915f2bd95SEwan Crawford 
106015f2bd95SEwan Crawford     // The result of the expression is invalid
106115f2bd95SEwan Crawford     if (!expr_result->GetError().Success())
106215f2bd95SEwan Crawford     {
106315f2bd95SEwan Crawford         Error err = expr_result->GetError();
106415f2bd95SEwan Crawford         if (err.GetError() == UserExpression::kNoResult) // Expression returned void, so this is actually a success
106515f2bd95SEwan Crawford         {
106615f2bd95SEwan Crawford             if (log)
106715f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::EvalRSExpression - Expression returned void");
106815f2bd95SEwan Crawford 
106915f2bd95SEwan Crawford             result = nullptr;
107015f2bd95SEwan Crawford             return true;
107115f2bd95SEwan Crawford         }
107215f2bd95SEwan Crawford 
107315f2bd95SEwan Crawford         if (log)
107415f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::EvalRSExpression - Error evaluating expression result: %s", err.AsCString());
107515f2bd95SEwan Crawford         return false;
107615f2bd95SEwan Crawford     }
107715f2bd95SEwan Crawford 
107815f2bd95SEwan Crawford     bool success = false;
107915f2bd95SEwan Crawford     *result = expr_result->GetValueAsUnsigned(0, &success); // We only read the result as an unsigned int.
108015f2bd95SEwan Crawford 
108115f2bd95SEwan Crawford     if (!success)
108215f2bd95SEwan Crawford     {
108315f2bd95SEwan Crawford        if (log)
108415f2bd95SEwan Crawford            log->Printf("RenderScriptRuntime::EvalRSExpression -  Error: Couldn't convert expression result to unsigned int");
108515f2bd95SEwan Crawford        return false;
108615f2bd95SEwan Crawford     }
108715f2bd95SEwan Crawford 
108815f2bd95SEwan Crawford     return true;
108915f2bd95SEwan Crawford }
109015f2bd95SEwan Crawford 
109115f2bd95SEwan Crawford // Used to index expression format strings
109215f2bd95SEwan Crawford enum ExpressionStrings
109315f2bd95SEwan Crawford {
109415f2bd95SEwan Crawford    eExprGetOffsetPtr = 0,
109515f2bd95SEwan Crawford    eExprAllocGetType,
109615f2bd95SEwan Crawford    eExprTypeDimX,
109715f2bd95SEwan Crawford    eExprTypeDimY,
109815f2bd95SEwan Crawford    eExprTypeDimZ,
109915f2bd95SEwan Crawford    eExprTypeElemPtr,
110015f2bd95SEwan Crawford    eExprElementType,
110115f2bd95SEwan Crawford    eExprElementKind,
110215f2bd95SEwan Crawford    eExprElementVec
110315f2bd95SEwan Crawford };
110415f2bd95SEwan Crawford 
110515f2bd95SEwan Crawford // Format strings containing the expressions we may need to evaluate.
110615f2bd95SEwan Crawford const char runtimeExpressions[][256] =
110715f2bd95SEwan Crawford {
110815f2bd95SEwan Crawford  // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
110915f2bd95SEwan Crawford  "(int*)_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace(0x%lx, %u, %u, %u, 0, 0)",
111015f2bd95SEwan Crawford 
111115f2bd95SEwan Crawford  // Type* rsaAllocationGetType(Context*, Allocation*)
111215f2bd95SEwan Crawford  "(void*)rsaAllocationGetType(0x%lx, 0x%lx)",
111315f2bd95SEwan Crawford 
111415f2bd95SEwan Crawford  // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
111515f2bd95SEwan Crawford  // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ;
111615f2bd95SEwan Crawford  // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
111715f2bd95SEwan Crawford  // Need to specify 32 or 64 bit for uint_t since this differs between devices
111815f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[0]", // X dim
111915f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[1]", // Y dim
112015f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[2]", // Z dim
112115f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[5]", // Element ptr
112215f2bd95SEwan Crawford 
112315f2bd95SEwan Crawford  // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
112415f2bd95SEwan Crawford  // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData
112515f2bd95SEwan Crawford  "uint32_t data[6]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[0]", // Type
112615f2bd95SEwan Crawford  "uint32_t data[6]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[1]", // Kind
112715f2bd95SEwan Crawford  "uint32_t data[6]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[3]"  // Vector Size
112815f2bd95SEwan Crawford };
112915f2bd95SEwan Crawford 
113015f2bd95SEwan Crawford // JITs the RS runtime for the internal data pointer of an allocation.
113115f2bd95SEwan Crawford // Is passed x,y,z coordinates for the pointer to a specific element.
113215f2bd95SEwan Crawford // Then sets the data_ptr member in Allocation with the result.
113315f2bd95SEwan Crawford // Returns true on success, false otherwise
113415f2bd95SEwan Crawford bool
113515f2bd95SEwan Crawford RenderScriptRuntime::JITDataPointer(AllocationDetails* allocation, StackFrame* frame_ptr,
113615f2bd95SEwan Crawford                                     unsigned int x, unsigned int y, unsigned int z)
113715f2bd95SEwan Crawford {
113815f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
113915f2bd95SEwan Crawford 
114015f2bd95SEwan Crawford     if (!allocation->address.isValid())
114115f2bd95SEwan Crawford     {
114215f2bd95SEwan Crawford         if (log)
114315f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Failed to find allocation details");
114415f2bd95SEwan Crawford         return false;
114515f2bd95SEwan Crawford     }
114615f2bd95SEwan Crawford 
114715f2bd95SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprGetOffsetPtr];
114815f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
114915f2bd95SEwan Crawford     char buffer[max_expr_size];
115015f2bd95SEwan Crawford 
115115f2bd95SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->address.get(), x, y, z);
115215f2bd95SEwan Crawford     if (chars_written < 0)
115315f2bd95SEwan Crawford     {
115415f2bd95SEwan Crawford         if (log)
115515f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
115615f2bd95SEwan Crawford         return false;
115715f2bd95SEwan Crawford     }
115815f2bd95SEwan Crawford     else if (chars_written >= max_expr_size)
115915f2bd95SEwan Crawford     {
116015f2bd95SEwan Crawford         if (log)
116115f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Expression too long");
116215f2bd95SEwan Crawford         return false;
116315f2bd95SEwan Crawford     }
116415f2bd95SEwan Crawford 
116515f2bd95SEwan Crawford     uint64_t result = 0;
116615f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
116715f2bd95SEwan Crawford         return false;
116815f2bd95SEwan Crawford 
116915f2bd95SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
117015f2bd95SEwan Crawford     allocation->data_ptr = mem_ptr;
117115f2bd95SEwan Crawford 
117215f2bd95SEwan Crawford     return true;
117315f2bd95SEwan Crawford }
117415f2bd95SEwan Crawford 
117515f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
117615f2bd95SEwan Crawford // Then sets the type_ptr member in Allocation with the result.
117715f2bd95SEwan Crawford // Returns true on success, false otherwise
117815f2bd95SEwan Crawford bool
117915f2bd95SEwan Crawford RenderScriptRuntime::JITTypePointer(AllocationDetails* allocation, StackFrame* frame_ptr)
118015f2bd95SEwan Crawford {
118115f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
118215f2bd95SEwan Crawford 
118315f2bd95SEwan Crawford     if (!allocation->address.isValid() || !allocation->context.isValid())
118415f2bd95SEwan Crawford     {
118515f2bd95SEwan Crawford         if (log)
118615f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePointer - Failed to find allocation details");
118715f2bd95SEwan Crawford         return false;
118815f2bd95SEwan Crawford     }
118915f2bd95SEwan Crawford 
119015f2bd95SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprAllocGetType];
119115f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
119215f2bd95SEwan Crawford     char buffer[max_expr_size];
119315f2bd95SEwan Crawford 
119415f2bd95SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->context.get(), *allocation->address.get());
119515f2bd95SEwan Crawford     if (chars_written < 0)
119615f2bd95SEwan Crawford     {
119715f2bd95SEwan Crawford         if (log)
119815f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
119915f2bd95SEwan Crawford         return false;
120015f2bd95SEwan Crawford     }
120115f2bd95SEwan Crawford     else if (chars_written >= max_expr_size)
120215f2bd95SEwan Crawford     {
120315f2bd95SEwan Crawford         if (log)
120415f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePointer - Expression too long");
120515f2bd95SEwan Crawford         return false;
120615f2bd95SEwan Crawford     }
120715f2bd95SEwan Crawford 
120815f2bd95SEwan Crawford     uint64_t result = 0;
120915f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
121015f2bd95SEwan Crawford         return false;
121115f2bd95SEwan Crawford 
121215f2bd95SEwan Crawford     addr_t type_ptr = static_cast<lldb::addr_t>(result);
121315f2bd95SEwan Crawford     allocation->type_ptr = type_ptr;
121415f2bd95SEwan Crawford 
121515f2bd95SEwan Crawford     return true;
121615f2bd95SEwan Crawford }
121715f2bd95SEwan Crawford 
121815f2bd95SEwan Crawford // JITs the RS runtime for information about the dimensions and type of an allocation
121915f2bd95SEwan Crawford // Then sets dimension and element_ptr members in Allocation with the result.
122015f2bd95SEwan Crawford // Returns true on success, false otherwise
122115f2bd95SEwan Crawford bool
122215f2bd95SEwan Crawford RenderScriptRuntime::JITTypePacked(AllocationDetails* allocation, StackFrame* frame_ptr)
122315f2bd95SEwan Crawford {
122415f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
122515f2bd95SEwan Crawford 
122615f2bd95SEwan Crawford     if (!allocation->type_ptr.isValid() || !allocation->context.isValid())
122715f2bd95SEwan Crawford     {
122815f2bd95SEwan Crawford         if (log)
122915f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePacked - Failed to find allocation details");
123015f2bd95SEwan Crawford         return false;
123115f2bd95SEwan Crawford     }
123215f2bd95SEwan Crawford 
123315f2bd95SEwan Crawford     // Expression is different depending on if device is 32 or 64 bit
123415f2bd95SEwan Crawford     uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
123515f2bd95SEwan Crawford     const unsigned int bits = archByteSize == 4 ? 32 : 64;
123615f2bd95SEwan Crawford 
123715f2bd95SEwan Crawford     // We want 4 elements from packed data
123815f2bd95SEwan Crawford     const unsigned int num_exprs = 4;
123915f2bd95SEwan Crawford     assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) && "Invalid number of expressions");
124015f2bd95SEwan Crawford 
124115f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
124215f2bd95SEwan Crawford     char buffer[num_exprs][max_expr_size];
124315f2bd95SEwan Crawford     uint64_t results[num_exprs];
124415f2bd95SEwan Crawford 
124515f2bd95SEwan Crawford     for (unsigned int i = 0; i < num_exprs; ++i)
124615f2bd95SEwan Crawford     {
124715f2bd95SEwan Crawford         int chars_written = snprintf(buffer[i], max_expr_size, runtimeExpressions[eExprTypeDimX + i], bits,
124815f2bd95SEwan Crawford                                      *allocation->context.get(), *allocation->type_ptr.get());
124915f2bd95SEwan Crawford         if (chars_written < 0)
125015f2bd95SEwan Crawford         {
125115f2bd95SEwan Crawford             if (log)
125215f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
125315f2bd95SEwan Crawford             return false;
125415f2bd95SEwan Crawford         }
125515f2bd95SEwan Crawford         else if (chars_written >= max_expr_size)
125615f2bd95SEwan Crawford         {
125715f2bd95SEwan Crawford             if (log)
125815f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITTypePacked - Expression too long");
125915f2bd95SEwan Crawford             return false;
126015f2bd95SEwan Crawford         }
126115f2bd95SEwan Crawford 
126215f2bd95SEwan Crawford         // Perform expression evaluation
126315f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
126415f2bd95SEwan Crawford             return false;
126515f2bd95SEwan Crawford     }
126615f2bd95SEwan Crawford 
126715f2bd95SEwan Crawford     // Assign results to allocation members
126815f2bd95SEwan Crawford     AllocationDetails::Dimension dims;
126915f2bd95SEwan Crawford     dims.dim_1 = static_cast<uint32_t>(results[0]);
127015f2bd95SEwan Crawford     dims.dim_2 = static_cast<uint32_t>(results[1]);
127115f2bd95SEwan Crawford     dims.dim_3 = static_cast<uint32_t>(results[2]);
127215f2bd95SEwan Crawford     allocation->dimension = dims;
127315f2bd95SEwan Crawford 
127415f2bd95SEwan Crawford     addr_t elem_ptr = static_cast<lldb::addr_t>(results[3]);
127515f2bd95SEwan Crawford     allocation->element_ptr = elem_ptr;
127615f2bd95SEwan Crawford 
127715f2bd95SEwan Crawford     if (log)
127815f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::JITTypePacked - dims (%u, %u, %u) Element*: 0x%" PRIx64,
127915f2bd95SEwan Crawford                     dims.dim_1, dims.dim_2, dims.dim_3, elem_ptr);
128015f2bd95SEwan Crawford 
128115f2bd95SEwan Crawford     return true;
128215f2bd95SEwan Crawford }
128315f2bd95SEwan Crawford 
128415f2bd95SEwan Crawford // JITs the RS runtime for information about the Element of an allocation
128515f2bd95SEwan Crawford // Then sets type, type_vec_size, and type_kind members in Allocation with the result.
128615f2bd95SEwan Crawford // Returns true on success, false otherwise
128715f2bd95SEwan Crawford bool
128815f2bd95SEwan Crawford RenderScriptRuntime::JITElementPacked(AllocationDetails* allocation, StackFrame* frame_ptr)
128915f2bd95SEwan Crawford {
129015f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
129115f2bd95SEwan Crawford 
129215f2bd95SEwan Crawford     if (!allocation->element_ptr.isValid() || !allocation->context.isValid())
129315f2bd95SEwan Crawford     {
129415f2bd95SEwan Crawford         if (log)
129515f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITElementPacked - Failed to find allocation details");
129615f2bd95SEwan Crawford         return false;
129715f2bd95SEwan Crawford     }
129815f2bd95SEwan Crawford 
129915f2bd95SEwan Crawford     // We want 3 elements from packed data
130015f2bd95SEwan Crawford     const unsigned int num_exprs = 3;
130115f2bd95SEwan Crawford     assert(num_exprs == (eExprElementVec - eExprElementType + 1) && "Invalid number of expressions");
130215f2bd95SEwan Crawford 
130315f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
130415f2bd95SEwan Crawford     char buffer[num_exprs][max_expr_size];
130515f2bd95SEwan Crawford     uint64_t results[num_exprs];
130615f2bd95SEwan Crawford 
130715f2bd95SEwan Crawford     for (unsigned int i = 0; i < num_exprs; i++)
130815f2bd95SEwan Crawford     {
130915f2bd95SEwan Crawford         int chars_written = snprintf(buffer[i], max_expr_size, runtimeExpressions[eExprElementType + i], *allocation->context.get(), *allocation->element_ptr.get());
131015f2bd95SEwan Crawford         if (chars_written < 0)
131115f2bd95SEwan Crawford         {
131215f2bd95SEwan Crawford             if (log)
131315f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
131415f2bd95SEwan Crawford             return false;
131515f2bd95SEwan Crawford         }
131615f2bd95SEwan Crawford         else if (chars_written >= max_expr_size)
131715f2bd95SEwan Crawford         {
131815f2bd95SEwan Crawford             if (log)
131915f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITElementPacked - Expression too long");
132015f2bd95SEwan Crawford             return false;
132115f2bd95SEwan Crawford         }
132215f2bd95SEwan Crawford 
132315f2bd95SEwan Crawford         // Perform expression evaluation
132415f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
132515f2bd95SEwan Crawford             return false;
132615f2bd95SEwan Crawford     }
132715f2bd95SEwan Crawford 
132815f2bd95SEwan Crawford     // Assign results to allocation members
132915f2bd95SEwan Crawford     allocation->type = static_cast<RenderScriptRuntime::AllocationDetails::DataType>(results[0]);
133015f2bd95SEwan Crawford     allocation->type_kind = static_cast<RenderScriptRuntime::AllocationDetails::DataKind>(results[1]);
133115f2bd95SEwan Crawford     allocation->type_vec_size = static_cast<uint32_t>(results[2]);
133215f2bd95SEwan Crawford 
133315f2bd95SEwan Crawford     if (log)
133415f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::JITElementPacked - data type %u, pixel type %u, vector size %u",
133515f2bd95SEwan Crawford                     *allocation->type.get(), *allocation->type_kind.get(), *allocation->type_vec_size.get());
133615f2bd95SEwan Crawford 
133715f2bd95SEwan Crawford     return true;
133815f2bd95SEwan Crawford }
133915f2bd95SEwan Crawford 
1340a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
1341a0f08674SEwan Crawford // The `elem_size` paramter represents the size of a single element, including padding.
1342a0f08674SEwan Crawford // Which is needed as an offset from the last element pointer.
1343a0f08674SEwan Crawford // Using this offset minus the starting address we can calculate the size of the allocation.
1344a0f08674SEwan Crawford // Returns true on success, false otherwise
1345a0f08674SEwan Crawford bool
1346a0f08674SEwan Crawford RenderScriptRuntime::JITAllocationSize(AllocationDetails* allocation, StackFrame* frame_ptr,
1347a0f08674SEwan Crawford                                        const uint32_t elem_size)
1348a0f08674SEwan Crawford {
1349a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1350a0f08674SEwan Crawford 
1351a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->dimension.isValid()
1352a0f08674SEwan Crawford         || !allocation->data_ptr.isValid())
1353a0f08674SEwan Crawford     {
1354a0f08674SEwan Crawford         if (log)
1355a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Failed to find allocation details");
1356a0f08674SEwan Crawford         return false;
1357a0f08674SEwan Crawford     }
1358a0f08674SEwan Crawford 
1359a0f08674SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprGetOffsetPtr];
1360a0f08674SEwan Crawford     const int max_expr_size = 512; // Max expression size
1361a0f08674SEwan Crawford     char buffer[max_expr_size];
1362a0f08674SEwan Crawford 
1363a0f08674SEwan Crawford     // Find dimensions
1364a0f08674SEwan Crawford     unsigned int dim_x = allocation->dimension.get()->dim_1;
1365a0f08674SEwan Crawford     unsigned int dim_y = allocation->dimension.get()->dim_2;
1366a0f08674SEwan Crawford     unsigned int dim_z = allocation->dimension.get()->dim_3;
1367a0f08674SEwan Crawford 
1368a0f08674SEwan Crawford     // Calculate last element
1369a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 0 : dim_x - 1;
1370a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 0 : dim_y - 1;
1371a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 0 : dim_z - 1;
1372a0f08674SEwan Crawford 
1373a0f08674SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->address.get(),
1374a0f08674SEwan Crawford                                  dim_x, dim_y, dim_z);
1375a0f08674SEwan Crawford     if (chars_written < 0)
1376a0f08674SEwan Crawford     {
1377a0f08674SEwan Crawford         if (log)
1378a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Encoding error in snprintf()");
1379a0f08674SEwan Crawford         return false;
1380a0f08674SEwan Crawford     }
1381a0f08674SEwan Crawford     else if (chars_written >= max_expr_size)
1382a0f08674SEwan Crawford     {
1383a0f08674SEwan Crawford         if (log)
1384a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Expression too long");
1385a0f08674SEwan Crawford         return false;
1386a0f08674SEwan Crawford     }
1387a0f08674SEwan Crawford 
1388a0f08674SEwan Crawford     uint64_t result = 0;
1389a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1390a0f08674SEwan Crawford         return false;
1391a0f08674SEwan Crawford 
1392a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1393a0f08674SEwan Crawford     // Find pointer to last element and add on size of an element
1394a0f08674SEwan Crawford     allocation->size = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()) + elem_size;
1395a0f08674SEwan Crawford 
1396a0f08674SEwan Crawford     return true;
1397a0f08674SEwan Crawford }
1398a0f08674SEwan Crawford 
1399a0f08674SEwan Crawford // JITs the RS runtime for information about the stride between rows in the allocation.
1400a0f08674SEwan Crawford // This is done to detect padding, since allocated memory is 16-byte aligned.
1401a0f08674SEwan Crawford // Returns true on success, false otherwise
1402a0f08674SEwan Crawford bool
1403a0f08674SEwan Crawford RenderScriptRuntime::JITAllocationStride(AllocationDetails* allocation, StackFrame* frame_ptr)
1404a0f08674SEwan Crawford {
1405a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1406a0f08674SEwan Crawford 
1407a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->data_ptr.isValid())
1408a0f08674SEwan Crawford     {
1409a0f08674SEwan Crawford         if (log)
1410a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Failed to find allocation details");
1411a0f08674SEwan Crawford         return false;
1412a0f08674SEwan Crawford     }
1413a0f08674SEwan Crawford 
1414a0f08674SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprGetOffsetPtr];
1415a0f08674SEwan Crawford     const int max_expr_size = 512; // Max expression size
1416a0f08674SEwan Crawford     char buffer[max_expr_size];
1417a0f08674SEwan Crawford 
1418a0f08674SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->address.get(),
1419a0f08674SEwan Crawford                                  0, 1, 0);
1420a0f08674SEwan Crawford     if (chars_written < 0)
1421a0f08674SEwan Crawford     {
1422a0f08674SEwan Crawford         if (log)
1423a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Encoding error in snprintf()");
1424a0f08674SEwan Crawford         return false;
1425a0f08674SEwan Crawford     }
1426a0f08674SEwan Crawford     else if (chars_written >= max_expr_size)
1427a0f08674SEwan Crawford     {
1428a0f08674SEwan Crawford         if (log)
1429a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Expression too long");
1430a0f08674SEwan Crawford         return false;
1431a0f08674SEwan Crawford     }
1432a0f08674SEwan Crawford 
1433a0f08674SEwan Crawford     uint64_t result = 0;
1434a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1435a0f08674SEwan Crawford         return false;
1436a0f08674SEwan Crawford 
1437a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1438a0f08674SEwan Crawford     allocation->stride = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get());
1439a0f08674SEwan Crawford 
1440a0f08674SEwan Crawford     return true;
1441a0f08674SEwan Crawford }
1442a0f08674SEwan Crawford 
144315f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
144415f2bd95SEwan Crawford bool
144515f2bd95SEwan Crawford RenderScriptRuntime::RefreshAllocation(AllocationDetails* allocation, StackFrame* frame_ptr)
144615f2bd95SEwan Crawford {
144715f2bd95SEwan Crawford     // GetOffsetPointer()
144815f2bd95SEwan Crawford     if (!JITDataPointer(allocation, frame_ptr))
144915f2bd95SEwan Crawford         return false;
145015f2bd95SEwan Crawford 
145115f2bd95SEwan Crawford     // rsaAllocationGetType()
145215f2bd95SEwan Crawford     if (!JITTypePointer(allocation, frame_ptr))
145315f2bd95SEwan Crawford         return false;
145415f2bd95SEwan Crawford 
145515f2bd95SEwan Crawford     // rsaTypeGetNativeData()
145615f2bd95SEwan Crawford     if (!JITTypePacked(allocation, frame_ptr))
145715f2bd95SEwan Crawford         return false;
145815f2bd95SEwan Crawford 
145915f2bd95SEwan Crawford     // rsaElementGetNativeData()
146015f2bd95SEwan Crawford     if (!JITElementPacked(allocation, frame_ptr))
146115f2bd95SEwan Crawford         return false;
146215f2bd95SEwan Crawford 
146355232f09SEwan Crawford     // Use GetOffsetPointer() to infer size of the allocation
146455232f09SEwan Crawford     const unsigned int element_size = GetElementSize(allocation);
146555232f09SEwan Crawford     if (!JITAllocationSize(allocation, frame_ptr, element_size))
146655232f09SEwan Crawford         return false;
146755232f09SEwan Crawford 
146855232f09SEwan Crawford     return true;
146955232f09SEwan Crawford }
147055232f09SEwan Crawford 
147155232f09SEwan Crawford // Returns the size of a single allocation element including padding.
147255232f09SEwan Crawford // Assumes the relevant allocation information has already been jitted.
147355232f09SEwan Crawford unsigned int
147455232f09SEwan Crawford RenderScriptRuntime::GetElementSize(const AllocationDetails* allocation)
147555232f09SEwan Crawford {
147655232f09SEwan Crawford     const AllocationDetails::DataType type = *allocation->type.get();
147755232f09SEwan Crawford     assert(type >= AllocationDetails::RS_TYPE_NONE && type <= AllocationDetails::RS_TYPE_BOOLEAN
147855232f09SEwan Crawford                                                    && "Invalid allocation type");
147955232f09SEwan Crawford 
148055232f09SEwan Crawford     const unsigned int vec_size = *allocation->type_vec_size.get();
148155232f09SEwan Crawford     const unsigned int data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
148255232f09SEwan Crawford     const unsigned int padding = vec_size == 3 ? AllocationDetails::RSTypeToFormat[type][eElementSize] : 0;
148355232f09SEwan Crawford 
148455232f09SEwan Crawford     return data_size + padding;
148555232f09SEwan Crawford }
148655232f09SEwan Crawford 
148755232f09SEwan Crawford // Given an allocation, this function copies the allocation contents from device into a buffer on the heap.
148855232f09SEwan Crawford // Returning a shared pointer to the buffer containing the data.
148955232f09SEwan Crawford std::shared_ptr<uint8_t>
149055232f09SEwan Crawford RenderScriptRuntime::GetAllocationData(AllocationDetails* allocation, StackFrame* frame_ptr)
149155232f09SEwan Crawford {
149255232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
149355232f09SEwan Crawford 
149455232f09SEwan Crawford     // JIT all the allocation details
149555232f09SEwan Crawford     if (!allocation->data_ptr.isValid() || !allocation->type.isValid() || !allocation->type_vec_size.isValid()
149655232f09SEwan Crawford         || !allocation->size.isValid())
149755232f09SEwan Crawford     {
149855232f09SEwan Crawford         if (log)
149955232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - Allocation details not calculated yet, jitting info");
150055232f09SEwan Crawford 
150155232f09SEwan Crawford         if (!RefreshAllocation(allocation, frame_ptr))
150255232f09SEwan Crawford         {
150355232f09SEwan Crawford             if (log)
150455232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't JIT allocation details");
150555232f09SEwan Crawford             return nullptr;
150655232f09SEwan Crawford         }
150755232f09SEwan Crawford     }
150855232f09SEwan Crawford 
150955232f09SEwan Crawford     assert(allocation->data_ptr.isValid() && allocation->type.isValid() && allocation->type_vec_size.isValid()
151055232f09SEwan Crawford            && allocation->size.isValid() && "Allocation information not available");
151155232f09SEwan Crawford 
151255232f09SEwan Crawford     // Allocate a buffer to copy data into
151355232f09SEwan Crawford     const unsigned int size = *allocation->size.get();
151455232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
151555232f09SEwan Crawford     if (!buffer)
151655232f09SEwan Crawford     {
151755232f09SEwan Crawford         if (log)
151855232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't allocate a %u byte buffer", size);
151955232f09SEwan Crawford         return nullptr;
152055232f09SEwan Crawford     }
152155232f09SEwan Crawford 
152255232f09SEwan Crawford     // Read the inferior memory
152355232f09SEwan Crawford     Error error;
152455232f09SEwan Crawford     lldb::addr_t data_ptr = *allocation->data_ptr.get();
152555232f09SEwan Crawford     GetProcess()->ReadMemory(data_ptr, buffer.get(), size, error);
152655232f09SEwan Crawford     if (error.Fail())
152755232f09SEwan Crawford     {
152855232f09SEwan Crawford         if (log)
152955232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - '%s' Couldn't read %u bytes of allocation data from 0x%" PRIx64,
153055232f09SEwan Crawford                         error.AsCString(), size, data_ptr);
153155232f09SEwan Crawford         return nullptr;
153255232f09SEwan Crawford     }
153355232f09SEwan Crawford 
153455232f09SEwan Crawford     return buffer;
153555232f09SEwan Crawford }
153655232f09SEwan Crawford 
153755232f09SEwan Crawford // Function copies data from a binary file into an allocation.
153855232f09SEwan Crawford // There is a header at the start of the file, FileHeader, before the data content itself.
153955232f09SEwan Crawford // Information from this header is used to display warnings to the user about incompatabilities
154055232f09SEwan Crawford bool
154155232f09SEwan Crawford RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr)
154255232f09SEwan Crawford {
154355232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
154455232f09SEwan Crawford 
154555232f09SEwan Crawford     // Find allocation with the given id
154655232f09SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, alloc_id);
154755232f09SEwan Crawford     if (!alloc)
154855232f09SEwan Crawford         return false;
154955232f09SEwan Crawford 
155055232f09SEwan Crawford     if (log)
155155232f09SEwan Crawford         log->Printf("RenderScriptRuntime::LoadAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
155255232f09SEwan Crawford 
155355232f09SEwan Crawford     // JIT all the allocation details
155455232f09SEwan Crawford     if (!alloc->data_ptr.isValid() || !alloc->type.isValid() || !alloc->type_vec_size.isValid() || !alloc->size.isValid())
155555232f09SEwan Crawford     {
155655232f09SEwan Crawford         if (log)
155755232f09SEwan Crawford             log->Printf("RenderScriptRuntime::LoadAllocation - Allocation details not calculated yet, jitting info");
155855232f09SEwan Crawford 
155955232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
156055232f09SEwan Crawford         {
156155232f09SEwan Crawford             if (log)
156255232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::LoadAllocation - Couldn't JIT allocation details");
15634cfc9198SSylvestre Ledru             return false;
156455232f09SEwan Crawford         }
156555232f09SEwan Crawford     }
156655232f09SEwan Crawford 
156755232f09SEwan Crawford     assert(alloc->data_ptr.isValid() && alloc->type.isValid() && alloc->type_vec_size.isValid() && alloc->size.isValid()
156855232f09SEwan Crawford            && "Allocation information not available");
156955232f09SEwan Crawford 
157055232f09SEwan Crawford     // Check we can read from file
157155232f09SEwan Crawford     FileSpec file(filename, true);
157255232f09SEwan Crawford     if (!file.Exists())
157355232f09SEwan Crawford     {
157455232f09SEwan Crawford         strm.Printf("Error: File %s does not exist", filename);
157555232f09SEwan Crawford         strm.EOL();
157655232f09SEwan Crawford         return false;
157755232f09SEwan Crawford     }
157855232f09SEwan Crawford 
157955232f09SEwan Crawford     if (!file.Readable())
158055232f09SEwan Crawford     {
158155232f09SEwan Crawford         strm.Printf("Error: File %s does not have readable permissions", filename);
158255232f09SEwan Crawford         strm.EOL();
158355232f09SEwan Crawford         return false;
158455232f09SEwan Crawford     }
158555232f09SEwan Crawford 
158655232f09SEwan Crawford     // Read file into data buffer
158755232f09SEwan Crawford     DataBufferSP data_sp(file.ReadFileContents());
158855232f09SEwan Crawford 
158955232f09SEwan Crawford     // Cast start of buffer to FileHeader and use pointer to read metadata
159055232f09SEwan Crawford     void* file_buffer = data_sp->GetBytes();
159155232f09SEwan Crawford     const AllocationDetails::FileHeader* head = static_cast<AllocationDetails::FileHeader*>(file_buffer);
159255232f09SEwan Crawford 
159355232f09SEwan Crawford     // Advance buffer past header
159455232f09SEwan Crawford     file_buffer = static_cast<uint8_t*>(file_buffer) + head->hdr_size;
159555232f09SEwan Crawford 
159655232f09SEwan Crawford     if (log)
159755232f09SEwan Crawford         log->Printf("RenderScriptRuntime::LoadAllocation - header type %u, element size %u",
159855232f09SEwan Crawford                     head->type, head->element_size);
159955232f09SEwan Crawford 
160055232f09SEwan Crawford     // Check if the target allocation and file both have the same number of bytes for an Element
160155232f09SEwan Crawford     const unsigned int elem_size = GetElementSize(alloc);
160255232f09SEwan Crawford     if (elem_size != head->element_size)
160355232f09SEwan Crawford     {
160455232f09SEwan Crawford         strm.Printf("Warning: Mismatched Element sizes - file %u bytes, allocation %u bytes",
160555232f09SEwan Crawford                     head->element_size, elem_size);
160655232f09SEwan Crawford         strm.EOL();
160755232f09SEwan Crawford     }
160855232f09SEwan Crawford 
160955232f09SEwan Crawford     // Check if the target allocation and file both have the same integral type
161055232f09SEwan Crawford     const unsigned int type = static_cast<unsigned int>(*alloc->type.get());
161155232f09SEwan Crawford     if (type != head->type)
161255232f09SEwan Crawford     {
161355232f09SEwan Crawford         const char* file_type_cstr = AllocationDetails::RsDataTypeToString[head->type][0];
161455232f09SEwan Crawford         const char* alloc_type_cstr = AllocationDetails::RsDataTypeToString[type][0];
161555232f09SEwan Crawford 
161655232f09SEwan Crawford         strm.Printf("Warning: Mismatched Types - file '%s' type, allocation '%s' type",
161755232f09SEwan Crawford                     file_type_cstr, alloc_type_cstr);
161855232f09SEwan Crawford         strm.EOL();
161955232f09SEwan Crawford     }
162055232f09SEwan Crawford 
162155232f09SEwan Crawford     // Calculate size of allocation data in file
162255232f09SEwan Crawford     size_t length = data_sp->GetByteSize() - head->hdr_size;
162355232f09SEwan Crawford 
162455232f09SEwan Crawford     // Check if the target allocation and file both have the same total data size.
162555232f09SEwan Crawford     const unsigned int alloc_size = *alloc->size.get();
162655232f09SEwan Crawford     if (alloc_size != length)
162755232f09SEwan Crawford     {
162855232f09SEwan Crawford         strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64 " bytes, allocation 0x%x bytes",
1629eba832beSJason Molenda                     (uint64_t) length, alloc_size);
163055232f09SEwan Crawford         strm.EOL();
163155232f09SEwan Crawford         length = alloc_size < length ? alloc_size : length; // Set length to copy to minimum
163255232f09SEwan Crawford     }
163355232f09SEwan Crawford 
163455232f09SEwan Crawford     // Copy file data from our buffer into the target allocation.
163555232f09SEwan Crawford     lldb::addr_t alloc_data = *alloc->data_ptr.get();
163655232f09SEwan Crawford     Error error;
163755232f09SEwan Crawford     size_t bytes_written = GetProcess()->WriteMemory(alloc_data, file_buffer, length, error);
163855232f09SEwan Crawford     if (!error.Success() || bytes_written != length)
163955232f09SEwan Crawford     {
164055232f09SEwan Crawford         strm.Printf("Error: Couldn't write data to allocation %s", error.AsCString());
164155232f09SEwan Crawford         strm.EOL();
164255232f09SEwan Crawford         return false;
164355232f09SEwan Crawford     }
164455232f09SEwan Crawford 
164555232f09SEwan Crawford     strm.Printf("Contents of file '%s' read into allocation %u", filename, alloc->id);
164655232f09SEwan Crawford     strm.EOL();
164755232f09SEwan Crawford 
164855232f09SEwan Crawford     return true;
164955232f09SEwan Crawford }
165055232f09SEwan Crawford 
165155232f09SEwan Crawford // Function copies allocation contents into a binary file.
165255232f09SEwan Crawford // This file can then be loaded later into a different allocation.
165355232f09SEwan Crawford // There is a header, FileHeader, before the allocation data containing meta-data.
165455232f09SEwan Crawford bool
165555232f09SEwan Crawford RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr)
165655232f09SEwan Crawford {
165755232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
165855232f09SEwan Crawford 
165955232f09SEwan Crawford     // Find allocation with the given id
166055232f09SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, alloc_id);
166155232f09SEwan Crawford     if (!alloc)
166255232f09SEwan Crawford         return false;
166355232f09SEwan Crawford 
166455232f09SEwan Crawford     if (log)
166555232f09SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
166655232f09SEwan Crawford 
166755232f09SEwan Crawford      // JIT all the allocation details
166855232f09SEwan Crawford     if (!alloc->data_ptr.isValid() || !alloc->type.isValid() || !alloc->type_vec_size.isValid()
166955232f09SEwan Crawford         || !alloc->type_kind.isValid() || !alloc->dimension.isValid())
167055232f09SEwan Crawford     {
167155232f09SEwan Crawford         if (log)
167255232f09SEwan Crawford             log->Printf("RenderScriptRuntime::SaveAllocation - Allocation details not calculated yet, jitting info");
167355232f09SEwan Crawford 
167455232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
167555232f09SEwan Crawford         {
167655232f09SEwan Crawford             if (log)
167755232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::SaveAllocation - Couldn't JIT allocation details");
16784cfc9198SSylvestre Ledru             return false;
167955232f09SEwan Crawford         }
168055232f09SEwan Crawford     }
168155232f09SEwan Crawford 
168255232f09SEwan Crawford     assert(alloc->data_ptr.isValid() && alloc->type.isValid() && alloc->type_vec_size.isValid() && alloc->type_kind.isValid()
168355232f09SEwan Crawford            && alloc->dimension.isValid() && "Allocation information not available");
168455232f09SEwan Crawford 
168555232f09SEwan Crawford     // Check we can create writable file
168655232f09SEwan Crawford     FileSpec file_spec(filename, true);
168755232f09SEwan Crawford     File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionTruncate);
168855232f09SEwan Crawford     if (!file)
168955232f09SEwan Crawford     {
169055232f09SEwan Crawford         strm.Printf("Error: Failed to open '%s' for writing", filename);
169155232f09SEwan Crawford         strm.EOL();
169255232f09SEwan Crawford         return false;
169355232f09SEwan Crawford     }
169455232f09SEwan Crawford 
169555232f09SEwan Crawford     // Read allocation into buffer of heap memory
169655232f09SEwan Crawford     const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
169755232f09SEwan Crawford     if (!buffer)
169855232f09SEwan Crawford     {
169955232f09SEwan Crawford         strm.Printf("Error: Couldn't read allocation data into buffer");
170055232f09SEwan Crawford         strm.EOL();
170155232f09SEwan Crawford         return false;
170255232f09SEwan Crawford     }
170355232f09SEwan Crawford 
170455232f09SEwan Crawford     // Create the file header
170555232f09SEwan Crawford     AllocationDetails::FileHeader head;
170655232f09SEwan Crawford     head.ident[0] = 'R'; head.ident[1] = 'S'; head.ident[2] = 'A'; head.ident[3] = 'D';
170755232f09SEwan Crawford     head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader));
170855232f09SEwan Crawford     head.type = static_cast<uint16_t>(*alloc->type.get());
170955232f09SEwan Crawford     head.kind = static_cast<uint32_t>(*alloc->type_kind.get());
17102d62328aSEwan Crawford     head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
17112d62328aSEwan Crawford     head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
17122d62328aSEwan Crawford     head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
171355232f09SEwan Crawford     head.element_size = static_cast<uint32_t>(GetElementSize(alloc));
171455232f09SEwan Crawford 
171555232f09SEwan Crawford     // Write the file header
171655232f09SEwan Crawford     size_t num_bytes = sizeof(AllocationDetails::FileHeader);
171755232f09SEwan Crawford     Error err = file.Write(static_cast<const void*>(&head), num_bytes);
171855232f09SEwan Crawford     if (!err.Success())
171955232f09SEwan Crawford     {
172055232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
172155232f09SEwan Crawford         strm.EOL();
172255232f09SEwan Crawford         return false;
172355232f09SEwan Crawford     }
172455232f09SEwan Crawford 
172555232f09SEwan Crawford     // Write allocation data to file
172655232f09SEwan Crawford     num_bytes = static_cast<size_t>(*alloc->size.get());
172755232f09SEwan Crawford     if (log)
1728eba832beSJason Molenda         log->Printf("RenderScriptRuntime::SaveAllocation - Writing 0x%" PRIx64 " bytes from %p", (uint64_t) num_bytes, buffer.get());
172955232f09SEwan Crawford 
173055232f09SEwan Crawford     err = file.Write(buffer.get(), num_bytes);
173155232f09SEwan Crawford     if (!err.Success())
173255232f09SEwan Crawford     {
173355232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
173455232f09SEwan Crawford         strm.EOL();
173555232f09SEwan Crawford         return false;
173655232f09SEwan Crawford     }
173755232f09SEwan Crawford 
173855232f09SEwan Crawford     strm.Printf("Allocation written to file '%s'", filename);
173955232f09SEwan Crawford     strm.EOL();
174015f2bd95SEwan Crawford     return true;
174115f2bd95SEwan Crawford }
174215f2bd95SEwan Crawford 
17435ec532a9SColin Riley bool
17445ec532a9SColin Riley RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp)
17455ec532a9SColin Riley {
17464640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
17474640cde1SColin Riley 
17485ec532a9SColin Riley     if (module_sp)
17495ec532a9SColin Riley     {
17505ec532a9SColin Riley         for (const auto &rs_module : m_rsmodules)
17515ec532a9SColin Riley         {
17524640cde1SColin Riley             if (rs_module->m_module == module_sp)
17537dc7771cSEwan Crawford             {
17547dc7771cSEwan Crawford                 // Check if the user has enabled automatically breaking on
17557dc7771cSEwan Crawford                 // all RS kernels.
17567dc7771cSEwan Crawford                 if (m_breakAllKernels)
17577dc7771cSEwan Crawford                     BreakOnModuleKernels(rs_module);
17587dc7771cSEwan Crawford 
17595ec532a9SColin Riley                 return false;
17605ec532a9SColin Riley             }
17617dc7771cSEwan Crawford         }
1762ef20b08fSColin Riley         bool module_loaded = false;
1763ef20b08fSColin Riley         switch (GetModuleKind(module_sp))
1764ef20b08fSColin Riley         {
1765ef20b08fSColin Riley             case eModuleKindKernelObj:
1766ef20b08fSColin Riley             {
17674640cde1SColin Riley                 RSModuleDescriptorSP module_desc;
17684640cde1SColin Riley                 module_desc.reset(new RSModuleDescriptor(module_sp));
17694640cde1SColin Riley                 if (module_desc->ParseRSInfo())
17705ec532a9SColin Riley                 {
17715ec532a9SColin Riley                     m_rsmodules.push_back(module_desc);
1772ef20b08fSColin Riley                     module_loaded = true;
17735ec532a9SColin Riley                 }
17744640cde1SColin Riley                 if (module_loaded)
17754640cde1SColin Riley                 {
17764640cde1SColin Riley                     FixupScriptDetails(module_desc);
17774640cde1SColin Riley                 }
1778ef20b08fSColin Riley                 break;
1779ef20b08fSColin Riley             }
1780ef20b08fSColin Riley             case eModuleKindDriver:
17814640cde1SColin Riley             {
17824640cde1SColin Riley                 if (!m_libRSDriver)
17834640cde1SColin Riley                 {
17844640cde1SColin Riley                     m_libRSDriver = module_sp;
17854640cde1SColin Riley                     LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
17864640cde1SColin Riley                 }
17874640cde1SColin Riley                 break;
17884640cde1SColin Riley             }
1789ef20b08fSColin Riley             case eModuleKindImpl:
17904640cde1SColin Riley             {
17914640cde1SColin Riley                 m_libRSCpuRef = module_sp;
17924640cde1SColin Riley                 break;
17934640cde1SColin Riley             }
1794ef20b08fSColin Riley             case eModuleKindLibRS:
17954640cde1SColin Riley             {
17964640cde1SColin Riley                 if (!m_libRS)
17974640cde1SColin Riley                 {
17984640cde1SColin Riley                     m_libRS = module_sp;
17994640cde1SColin Riley                     static ConstString gDbgPresentStr("gDebuggerPresent");
18004640cde1SColin Riley                     const Symbol* debug_present = m_libRS->FindFirstSymbolWithNameAndType(gDbgPresentStr, eSymbolTypeData);
18014640cde1SColin Riley                     if (debug_present)
18024640cde1SColin Riley                     {
18034640cde1SColin Riley                         Error error;
18044640cde1SColin Riley                         uint32_t flag = 0x00000001U;
18054640cde1SColin Riley                         Target &target = GetProcess()->GetTarget();
1806358cf1eaSGreg Clayton                         addr_t addr = debug_present->GetLoadAddress(&target);
18074640cde1SColin Riley                         GetProcess()->WriteMemory(addr, &flag, sizeof(flag), error);
18084640cde1SColin Riley                         if(error.Success())
18094640cde1SColin Riley                         {
18104640cde1SColin Riley                             if (log)
18114640cde1SColin Riley                                 log->Printf ("RenderScriptRuntime::LoadModule - Debugger present flag set on debugee");
18124640cde1SColin Riley 
18134640cde1SColin Riley                             m_debuggerPresentFlagged = true;
18144640cde1SColin Riley                         }
18154640cde1SColin Riley                         else if (log)
18164640cde1SColin Riley                         {
18174640cde1SColin Riley                             log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags '%s' ", error.AsCString());
18184640cde1SColin Riley                         }
18194640cde1SColin Riley                     }
18204640cde1SColin Riley                     else if (log)
18214640cde1SColin Riley                     {
18224640cde1SColin Riley                         log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags - symbol not found");
18234640cde1SColin Riley                     }
18244640cde1SColin Riley                 }
18254640cde1SColin Riley                 break;
18264640cde1SColin Riley             }
1827ef20b08fSColin Riley             default:
1828ef20b08fSColin Riley                 break;
1829ef20b08fSColin Riley         }
1830ef20b08fSColin Riley         if (module_loaded)
1831ef20b08fSColin Riley             Update();
1832ef20b08fSColin Riley         return module_loaded;
18335ec532a9SColin Riley     }
18345ec532a9SColin Riley     return false;
18355ec532a9SColin Riley }
18365ec532a9SColin Riley 
1837ef20b08fSColin Riley void
1838ef20b08fSColin Riley RenderScriptRuntime::Update()
1839ef20b08fSColin Riley {
1840ef20b08fSColin Riley     if (m_rsmodules.size() > 0)
1841ef20b08fSColin Riley     {
1842ef20b08fSColin Riley         if (!m_initiated)
1843ef20b08fSColin Riley         {
1844ef20b08fSColin Riley             Initiate();
1845ef20b08fSColin Riley         }
1846ef20b08fSColin Riley     }
1847ef20b08fSColin Riley }
1848ef20b08fSColin Riley 
18495ec532a9SColin Riley // The maximum line length of an .rs.info packet
18505ec532a9SColin Riley #define MAXLINE 500
18515ec532a9SColin Riley 
18525ec532a9SColin Riley // The .rs.info symbol in renderscript modules contains a string which needs to be parsed.
18535ec532a9SColin Riley // The string is basic and is parsed on a line by line basis.
18545ec532a9SColin Riley bool
18555ec532a9SColin Riley RSModuleDescriptor::ParseRSInfo()
18565ec532a9SColin Riley {
18575ec532a9SColin Riley     const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
18585ec532a9SColin Riley     if (info_sym)
18595ec532a9SColin Riley     {
1860358cf1eaSGreg Clayton         const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
18615ec532a9SColin Riley         const addr_t size = info_sym->GetByteSize();
18625ec532a9SColin Riley         const FileSpec fs = m_module->GetFileSpec();
18635ec532a9SColin Riley 
18645ec532a9SColin Riley         DataBufferSP buffer = fs.ReadFileContents(addr, size);
18655ec532a9SColin Riley 
18665ec532a9SColin Riley         if (!buffer)
18675ec532a9SColin Riley             return false;
18685ec532a9SColin Riley 
18695ec532a9SColin Riley         std::string info((const char *)buffer->GetBytes());
18705ec532a9SColin Riley 
18715ec532a9SColin Riley         std::vector<std::string> info_lines;
1872e8433cc1SBruce Mitchener         size_t lpos = info.find('\n');
18735ec532a9SColin Riley         while (lpos != std::string::npos)
18745ec532a9SColin Riley         {
18755ec532a9SColin Riley             info_lines.push_back(info.substr(0, lpos));
18765ec532a9SColin Riley             info = info.substr(lpos + 1);
1877e8433cc1SBruce Mitchener             lpos = info.find('\n');
18785ec532a9SColin Riley         }
18795ec532a9SColin Riley         size_t offset = 0;
18805ec532a9SColin Riley         while (offset < info_lines.size())
18815ec532a9SColin Riley         {
18825ec532a9SColin Riley             std::string line = info_lines[offset];
18835ec532a9SColin Riley             // Parse directives
18845ec532a9SColin Riley             uint32_t numDefns = 0;
18855ec532a9SColin Riley             if (sscanf(line.c_str(), "exportVarCount: %u", &numDefns) == 1)
18865ec532a9SColin Riley             {
18875ec532a9SColin Riley                 while (numDefns--)
18884640cde1SColin Riley                     m_globals.push_back(RSGlobalDescriptor(this, info_lines[++offset].c_str()));
18895ec532a9SColin Riley             }
18905ec532a9SColin Riley             else if (sscanf(line.c_str(), "exportFuncCount: %u", &numDefns) == 1)
18915ec532a9SColin Riley             {
18925ec532a9SColin Riley             }
18935ec532a9SColin Riley             else if (sscanf(line.c_str(), "exportForEachCount: %u", &numDefns) == 1)
18945ec532a9SColin Riley             {
18955ec532a9SColin Riley                 char name[MAXLINE];
18965ec532a9SColin Riley                 while (numDefns--)
18975ec532a9SColin Riley                 {
18985ec532a9SColin Riley                     uint32_t slot = 0;
18995ec532a9SColin Riley                     name[0] = '\0';
19005ec532a9SColin Riley                     if (sscanf(info_lines[++offset].c_str(), "%u - %s", &slot, &name[0]) == 2)
19015ec532a9SColin Riley                     {
19024640cde1SColin Riley                         m_kernels.push_back(RSKernelDescriptor(this, name, slot));
19034640cde1SColin Riley                     }
19044640cde1SColin Riley                 }
19054640cde1SColin Riley             }
19064640cde1SColin Riley             else if (sscanf(line.c_str(), "pragmaCount: %u", &numDefns) == 1)
19074640cde1SColin Riley             {
19084640cde1SColin Riley                 char name[MAXLINE];
19094640cde1SColin Riley                 char value[MAXLINE];
19104640cde1SColin Riley                 while (numDefns--)
19114640cde1SColin Riley                 {
19124640cde1SColin Riley                     name[0] = '\0';
19134640cde1SColin Riley                     value[0] = '\0';
19144640cde1SColin Riley                     if (sscanf(info_lines[++offset].c_str(), "%s - %s", &name[0], &value[0]) != 0
19154640cde1SColin Riley                         && (name[0] != '\0'))
19164640cde1SColin Riley                     {
19174640cde1SColin Riley                         m_pragmas[std::string(name)] = value;
19185ec532a9SColin Riley                     }
19195ec532a9SColin Riley                 }
19205ec532a9SColin Riley             }
19215ec532a9SColin Riley             else if (sscanf(line.c_str(), "objectSlotCount: %u", &numDefns) == 1)
19225ec532a9SColin Riley             {
19235ec532a9SColin Riley             }
19245ec532a9SColin Riley 
19255ec532a9SColin Riley             offset++;
19265ec532a9SColin Riley         }
19275ec532a9SColin Riley         return m_kernels.size() > 0;
19285ec532a9SColin Riley     }
19295ec532a9SColin Riley     return false;
19305ec532a9SColin Riley }
19315ec532a9SColin Riley 
19325ec532a9SColin Riley bool
19335ec532a9SColin Riley RenderScriptRuntime::ProbeModules(const ModuleList module_list)
19345ec532a9SColin Riley {
19355ec532a9SColin Riley     bool rs_found = false;
19365ec532a9SColin Riley     size_t num_modules = module_list.GetSize();
19375ec532a9SColin Riley     for (size_t i = 0; i < num_modules; i++)
19385ec532a9SColin Riley     {
19395ec532a9SColin Riley         auto module = module_list.GetModuleAtIndex(i);
19405ec532a9SColin Riley         rs_found |= LoadModule(module);
19415ec532a9SColin Riley     }
19425ec532a9SColin Riley     return rs_found;
19435ec532a9SColin Riley }
19445ec532a9SColin Riley 
19455ec532a9SColin Riley void
19464640cde1SColin Riley RenderScriptRuntime::Status(Stream &strm) const
19474640cde1SColin Riley {
19484640cde1SColin Riley     if (m_libRS)
19494640cde1SColin Riley     {
19504640cde1SColin Riley         strm.Printf("Runtime Library discovered.");
19514640cde1SColin Riley         strm.EOL();
19524640cde1SColin Riley     }
19534640cde1SColin Riley     if (m_libRSDriver)
19544640cde1SColin Riley     {
19554640cde1SColin Riley         strm.Printf("Runtime Driver discovered.");
19564640cde1SColin Riley         strm.EOL();
19574640cde1SColin Riley     }
19584640cde1SColin Riley     if (m_libRSCpuRef)
19594640cde1SColin Riley     {
19604640cde1SColin Riley         strm.Printf("CPU Reference Implementation discovered.");
19614640cde1SColin Riley         strm.EOL();
19624640cde1SColin Riley     }
19634640cde1SColin Riley 
19644640cde1SColin Riley     if (m_runtimeHooks.size())
19654640cde1SColin Riley     {
19664640cde1SColin Riley         strm.Printf("Runtime functions hooked:");
19674640cde1SColin Riley         strm.EOL();
19684640cde1SColin Riley         for (auto b : m_runtimeHooks)
19694640cde1SColin Riley         {
19704640cde1SColin Riley             strm.Indent(b.second->defn->name);
19714640cde1SColin Riley             strm.EOL();
19724640cde1SColin Riley         }
19734640cde1SColin Riley         strm.EOL();
19744640cde1SColin Riley     }
19754640cde1SColin Riley     else
19764640cde1SColin Riley     {
19774640cde1SColin Riley         strm.Printf("Runtime is not hooked.");
19784640cde1SColin Riley         strm.EOL();
19794640cde1SColin Riley     }
19804640cde1SColin Riley }
19814640cde1SColin Riley 
19824640cde1SColin Riley void
19834640cde1SColin Riley RenderScriptRuntime::DumpContexts(Stream &strm) const
19844640cde1SColin Riley {
19854640cde1SColin Riley     strm.Printf("Inferred RenderScript Contexts:");
19864640cde1SColin Riley     strm.EOL();
19874640cde1SColin Riley     strm.IndentMore();
19884640cde1SColin Riley 
19894640cde1SColin Riley     std::map<addr_t, uint64_t> contextReferences;
19904640cde1SColin Riley 
199178f339d1SEwan Crawford     // Iterate over all of the currently discovered scripts.
199278f339d1SEwan Crawford     // Note: We cant push or pop from m_scripts inside this loop or it may invalidate script.
19934640cde1SColin Riley     for (const auto & script : m_scripts)
19944640cde1SColin Riley     {
199578f339d1SEwan Crawford         if (!script->context.isValid())
199678f339d1SEwan Crawford             continue;
199778f339d1SEwan Crawford         lldb::addr_t context = *script->context;
199878f339d1SEwan Crawford 
199978f339d1SEwan Crawford         if (contextReferences.find(context) != contextReferences.end())
20004640cde1SColin Riley         {
200178f339d1SEwan Crawford             contextReferences[context]++;
20024640cde1SColin Riley         }
20034640cde1SColin Riley         else
20044640cde1SColin Riley         {
200578f339d1SEwan Crawford             contextReferences[context] = 1;
20064640cde1SColin Riley         }
20074640cde1SColin Riley     }
20084640cde1SColin Riley 
20094640cde1SColin Riley     for (const auto& cRef : contextReferences)
20104640cde1SColin Riley     {
20114640cde1SColin Riley         strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances", cRef.first, cRef.second);
20124640cde1SColin Riley         strm.EOL();
20134640cde1SColin Riley     }
20144640cde1SColin Riley     strm.IndentLess();
20154640cde1SColin Riley }
20164640cde1SColin Riley 
20174640cde1SColin Riley void
20184640cde1SColin Riley RenderScriptRuntime::DumpKernels(Stream &strm) const
20194640cde1SColin Riley {
20204640cde1SColin Riley     strm.Printf("RenderScript Kernels:");
20214640cde1SColin Riley     strm.EOL();
20224640cde1SColin Riley     strm.IndentMore();
20234640cde1SColin Riley     for (const auto &module : m_rsmodules)
20244640cde1SColin Riley     {
20254640cde1SColin Riley         strm.Printf("Resource '%s':",module->m_resname.c_str());
20264640cde1SColin Riley         strm.EOL();
20274640cde1SColin Riley         for (const auto &kernel : module->m_kernels)
20284640cde1SColin Riley         {
20294640cde1SColin Riley             strm.Indent(kernel.m_name.AsCString());
20304640cde1SColin Riley             strm.EOL();
20314640cde1SColin Riley         }
20324640cde1SColin Riley     }
20334640cde1SColin Riley     strm.IndentLess();
20344640cde1SColin Riley }
20354640cde1SColin Riley 
2036a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails*
2037a0f08674SEwan Crawford RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id)
2038a0f08674SEwan Crawford {
2039a0f08674SEwan Crawford     AllocationDetails* alloc = nullptr;
2040a0f08674SEwan Crawford 
2041a0f08674SEwan Crawford     // See if we can find allocation using id as an index;
2042a0f08674SEwan Crawford     if (alloc_id <= m_allocations.size() && alloc_id != 0
2043a0f08674SEwan Crawford         && m_allocations[alloc_id-1]->id == alloc_id)
2044a0f08674SEwan Crawford     {
2045a0f08674SEwan Crawford         alloc = m_allocations[alloc_id-1].get();
2046a0f08674SEwan Crawford         return alloc;
2047a0f08674SEwan Crawford     }
2048a0f08674SEwan Crawford 
2049a0f08674SEwan Crawford     // Fallback to searching
2050a0f08674SEwan Crawford     for (const auto & a : m_allocations)
2051a0f08674SEwan Crawford     {
2052a0f08674SEwan Crawford        if (a->id == alloc_id)
2053a0f08674SEwan Crawford        {
2054a0f08674SEwan Crawford            alloc = a.get();
2055a0f08674SEwan Crawford            break;
2056a0f08674SEwan Crawford        }
2057a0f08674SEwan Crawford     }
2058a0f08674SEwan Crawford 
2059a0f08674SEwan Crawford     if (alloc == nullptr)
2060a0f08674SEwan Crawford     {
2061a0f08674SEwan Crawford         strm.Printf("Error: Couldn't find allocation with id matching %u", alloc_id);
2062a0f08674SEwan Crawford         strm.EOL();
2063a0f08674SEwan Crawford     }
2064a0f08674SEwan Crawford 
2065a0f08674SEwan Crawford     return alloc;
2066a0f08674SEwan Crawford }
2067a0f08674SEwan Crawford 
2068a0f08674SEwan Crawford // Prints the contents of an allocation to the output stream, which may be a file
2069a0f08674SEwan Crawford bool
2070a0f08674SEwan Crawford RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame* frame_ptr, const uint32_t id)
2071a0f08674SEwan Crawford {
2072a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2073a0f08674SEwan Crawford 
2074a0f08674SEwan Crawford     // Check we can find the desired allocation
2075a0f08674SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, id);
2076a0f08674SEwan Crawford     if (!alloc)
2077a0f08674SEwan Crawford         return false; // FindAllocByID() will print error message for us here
2078a0f08674SEwan Crawford 
2079a0f08674SEwan Crawford     if (log)
2080a0f08674SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
2081a0f08674SEwan Crawford 
2082a0f08674SEwan Crawford     // Check we have information about the allocation, if not calculate it
2083a0f08674SEwan Crawford     if (!alloc->data_ptr.isValid() || !alloc->type.isValid() ||
2084a0f08674SEwan Crawford         !alloc->type_vec_size.isValid() || !alloc->dimension.isValid())
2085a0f08674SEwan Crawford     {
2086a0f08674SEwan Crawford         if (log)
2087a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::DumpAllocation - Allocation details not calculated yet, jitting info");
2088a0f08674SEwan Crawford 
2089a0f08674SEwan Crawford         // JIT all the allocation information
2090a0f08674SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
2091a0f08674SEwan Crawford         {
2092a0f08674SEwan Crawford             strm.Printf("Error: Couldn't JIT allocation details");
2093a0f08674SEwan Crawford             strm.EOL();
2094a0f08674SEwan Crawford             return false;
2095a0f08674SEwan Crawford         }
2096a0f08674SEwan Crawford     }
2097a0f08674SEwan Crawford 
2098a0f08674SEwan Crawford     // Establish format and size of each data element
2099a0f08674SEwan Crawford     const unsigned int vec_size = *alloc->type_vec_size.get();
2100a0f08674SEwan Crawford     const AllocationDetails::DataType type = *alloc->type.get();
2101a0f08674SEwan Crawford 
2102a0f08674SEwan Crawford     assert(type >= AllocationDetails::RS_TYPE_NONE && type <= AllocationDetails::RS_TYPE_BOOLEAN
2103a0f08674SEwan Crawford                                                    && "Invalid allocation type");
2104a0f08674SEwan Crawford 
2105a0f08674SEwan Crawford     lldb::Format format = vec_size == 1 ? static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatSingle])
2106a0f08674SEwan Crawford                                         : static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatVector]);
2107a0f08674SEwan Crawford 
2108a0f08674SEwan Crawford     const unsigned int data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
2109a0f08674SEwan Crawford     // Renderscript pads vector 3 elements to vector 4
2110a0f08674SEwan Crawford     const unsigned int elem_padding = vec_size == 3 ? AllocationDetails::RSTypeToFormat[type][eElementSize] : 0;
2111a0f08674SEwan Crawford 
2112a0f08674SEwan Crawford     if (log)
2113a0f08674SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - Element size %u bytes, element padding %u bytes",
2114a0f08674SEwan Crawford                     data_size, elem_padding);
2115a0f08674SEwan Crawford 
211655232f09SEwan Crawford     // Allocate a buffer to copy data into
211755232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
211855232f09SEwan Crawford     if (!buffer)
211955232f09SEwan Crawford     {
212055232f09SEwan Crawford         strm.Printf("Error: Couldn't allocate a read allocation data into memory");
212155232f09SEwan Crawford         strm.EOL();
212255232f09SEwan Crawford         return false;
212355232f09SEwan Crawford     }
212455232f09SEwan Crawford 
2125a0f08674SEwan Crawford     // Calculate stride between rows as there may be padding at end of rows since
2126a0f08674SEwan Crawford     // allocated memory is 16-byte aligned
2127a0f08674SEwan Crawford     if (!alloc->stride.isValid())
2128a0f08674SEwan Crawford     {
2129a0f08674SEwan Crawford         if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
2130a0f08674SEwan Crawford             alloc->stride = 0;
2131a0f08674SEwan Crawford         else if (!JITAllocationStride(alloc, frame_ptr))
2132a0f08674SEwan Crawford         {
2133a0f08674SEwan Crawford             strm.Printf("Error: Couldn't calculate allocation row stride");
2134a0f08674SEwan Crawford             strm.EOL();
2135a0f08674SEwan Crawford             return false;
2136a0f08674SEwan Crawford         }
2137a0f08674SEwan Crawford     }
2138a0f08674SEwan Crawford     const unsigned int stride = *alloc->stride.get();
2139a0f08674SEwan Crawford     const unsigned int size = *alloc->size.get(); //size of last element
2140a0f08674SEwan Crawford 
2141a0f08674SEwan Crawford     if (log)
2142a0f08674SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - stride %u bytes, size %u bytes", stride, size);
2143a0f08674SEwan Crawford 
2144a0f08674SEwan Crawford     // Find dimensions used to index loops, so need to be non-zero
2145a0f08674SEwan Crawford     unsigned int dim_x = alloc->dimension.get()->dim_1;
2146a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 1 : dim_x;
2147a0f08674SEwan Crawford 
2148a0f08674SEwan Crawford     unsigned int dim_y = alloc->dimension.get()->dim_2;
2149a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 1 : dim_y;
2150a0f08674SEwan Crawford 
2151a0f08674SEwan Crawford     unsigned int dim_z = alloc->dimension.get()->dim_3;
2152a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 1 : dim_z;
2153a0f08674SEwan Crawford 
215455232f09SEwan Crawford     // Use data extractor to format output
215555232f09SEwan Crawford     const uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
215655232f09SEwan Crawford     DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(), archByteSize);
215755232f09SEwan Crawford 
2158a0f08674SEwan Crawford     unsigned int offset = 0;   // Offset in buffer to next element to be printed
2159a0f08674SEwan Crawford     unsigned int prev_row = 0; // Offset to the start of the previous row
2160a0f08674SEwan Crawford 
2161a0f08674SEwan Crawford     // Iterate over allocation dimensions, printing results to user
2162a0f08674SEwan Crawford     strm.Printf("Data (X, Y, Z):");
2163a0f08674SEwan Crawford     for (unsigned int z = 0; z < dim_z; ++z)
2164a0f08674SEwan Crawford     {
2165a0f08674SEwan Crawford         for (unsigned int y = 0; y < dim_y; ++y)
2166a0f08674SEwan Crawford         {
2167a0f08674SEwan Crawford             // Use stride to index start of next row.
2168a0f08674SEwan Crawford             if (!(y==0 && z==0))
2169a0f08674SEwan Crawford                 offset = prev_row + stride;
2170a0f08674SEwan Crawford             prev_row = offset;
2171a0f08674SEwan Crawford 
2172a0f08674SEwan Crawford             // Print each element in the row individually
2173a0f08674SEwan Crawford             for (unsigned int x = 0; x < dim_x; ++x)
2174a0f08674SEwan Crawford             {
2175a0f08674SEwan Crawford                 strm.Printf("\n(%u, %u, %u) = ", x, y, z);
2176a0f08674SEwan Crawford                 alloc_data.Dump(&strm, offset, format, data_size, 1, 1, LLDB_INVALID_ADDRESS, 0, 0);
2177a0f08674SEwan Crawford                 offset += data_size + elem_padding;
2178a0f08674SEwan Crawford             }
2179a0f08674SEwan Crawford         }
2180a0f08674SEwan Crawford     }
2181a0f08674SEwan Crawford     strm.EOL();
2182a0f08674SEwan Crawford 
2183a0f08674SEwan Crawford     return true;
2184a0f08674SEwan Crawford }
2185a0f08674SEwan Crawford 
218615f2bd95SEwan Crawford // Prints infomation regarding all the currently loaded allocations.
218715f2bd95SEwan Crawford // These details are gathered by jitting the runtime, which has as latency.
218815f2bd95SEwan Crawford void
218915f2bd95SEwan Crawford RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame* frame_ptr, bool recompute)
219015f2bd95SEwan Crawford {
219115f2bd95SEwan Crawford     strm.Printf("RenderScript Allocations:");
219215f2bd95SEwan Crawford     strm.EOL();
219315f2bd95SEwan Crawford     strm.IndentMore();
219415f2bd95SEwan Crawford 
219515f2bd95SEwan Crawford     for (auto &alloc : m_allocations)
219615f2bd95SEwan Crawford     {
219715f2bd95SEwan Crawford         // JIT the allocation info if we haven't done it, or the user forces us to.
219815f2bd95SEwan Crawford         bool do_refresh = !alloc->data_ptr.isValid() || recompute;
219915f2bd95SEwan Crawford 
220015f2bd95SEwan Crawford         // JIT current allocation information
220115f2bd95SEwan Crawford         if (do_refresh && !RefreshAllocation(alloc.get(), frame_ptr))
220215f2bd95SEwan Crawford         {
220315f2bd95SEwan Crawford             strm.Printf("Error: Couldn't evaluate details for allocation %u\n", alloc->id);
220415f2bd95SEwan Crawford             continue;
220515f2bd95SEwan Crawford         }
220615f2bd95SEwan Crawford 
220715f2bd95SEwan Crawford         strm.Printf("%u:\n",alloc->id);
220815f2bd95SEwan Crawford         strm.IndentMore();
220915f2bd95SEwan Crawford 
221015f2bd95SEwan Crawford         strm.Indent("Context: ");
221115f2bd95SEwan Crawford         if (!alloc->context.isValid())
221215f2bd95SEwan Crawford             strm.Printf("unknown\n");
221315f2bd95SEwan Crawford         else
221415f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
221515f2bd95SEwan Crawford 
221615f2bd95SEwan Crawford         strm.Indent("Address: ");
221715f2bd95SEwan Crawford         if (!alloc->address.isValid())
221815f2bd95SEwan Crawford             strm.Printf("unknown\n");
221915f2bd95SEwan Crawford         else
222015f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
222115f2bd95SEwan Crawford 
222215f2bd95SEwan Crawford         strm.Indent("Data pointer: ");
222315f2bd95SEwan Crawford         if (!alloc->data_ptr.isValid())
222415f2bd95SEwan Crawford             strm.Printf("unknown\n");
222515f2bd95SEwan Crawford         else
222615f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
222715f2bd95SEwan Crawford 
222815f2bd95SEwan Crawford         strm.Indent("Dimensions: ");
222915f2bd95SEwan Crawford         if (!alloc->dimension.isValid())
223015f2bd95SEwan Crawford             strm.Printf("unknown\n");
223115f2bd95SEwan Crawford         else
223215f2bd95SEwan Crawford             strm.Printf("(%d, %d, %d)\n", alloc->dimension.get()->dim_1,
223315f2bd95SEwan Crawford                                           alloc->dimension.get()->dim_2,
223415f2bd95SEwan Crawford                                           alloc->dimension.get()->dim_3);
223515f2bd95SEwan Crawford 
223615f2bd95SEwan Crawford         strm.Indent("Data Type: ");
223715f2bd95SEwan Crawford         if (!alloc->type.isValid() || !alloc->type_vec_size.isValid())
223815f2bd95SEwan Crawford             strm.Printf("unknown\n");
223915f2bd95SEwan Crawford         else
224015f2bd95SEwan Crawford         {
224115f2bd95SEwan Crawford             const int vector_size = *alloc->type_vec_size.get();
224215f2bd95SEwan Crawford             const AllocationDetails::DataType type = *alloc->type.get();
224315f2bd95SEwan Crawford 
224415f2bd95SEwan Crawford             if (vector_size > 4 || vector_size < 1 ||
224515f2bd95SEwan Crawford                 type < AllocationDetails::RS_TYPE_NONE || type > AllocationDetails::RS_TYPE_BOOLEAN)
224615f2bd95SEwan Crawford                 strm.Printf("invalid type\n");
224715f2bd95SEwan Crawford             else
224815f2bd95SEwan Crawford                 strm.Printf("%s\n", AllocationDetails::RsDataTypeToString[static_cast<unsigned int>(type)][vector_size-1]);
224915f2bd95SEwan Crawford         }
225015f2bd95SEwan Crawford 
225115f2bd95SEwan Crawford         strm.Indent("Data Kind: ");
225215f2bd95SEwan Crawford         if (!alloc->type_kind.isValid())
225315f2bd95SEwan Crawford             strm.Printf("unknown\n");
225415f2bd95SEwan Crawford         else
225515f2bd95SEwan Crawford         {
225615f2bd95SEwan Crawford             const AllocationDetails::DataKind kind = *alloc->type_kind.get();
225715f2bd95SEwan Crawford             if (kind < AllocationDetails::RS_KIND_USER || kind > AllocationDetails::RS_KIND_PIXEL_YUV)
225815f2bd95SEwan Crawford                 strm.Printf("invalid kind\n");
225915f2bd95SEwan Crawford             else
226015f2bd95SEwan Crawford                 strm.Printf("%s\n", AllocationDetails::RsDataKindToString[static_cast<unsigned int>(kind)]);
226115f2bd95SEwan Crawford         }
226215f2bd95SEwan Crawford 
226315f2bd95SEwan Crawford         strm.EOL();
226415f2bd95SEwan Crawford         strm.IndentLess();
226515f2bd95SEwan Crawford     }
226615f2bd95SEwan Crawford     strm.IndentLess();
226715f2bd95SEwan Crawford }
226815f2bd95SEwan Crawford 
22697dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
22707dc7771cSEwan Crawford void
22717dc7771cSEwan Crawford RenderScriptRuntime::BreakOnModuleKernels(const RSModuleDescriptorSP rsmodule_sp)
22727dc7771cSEwan Crawford {
22737dc7771cSEwan Crawford     for (const auto &kernel : rsmodule_sp->m_kernels)
22747dc7771cSEwan Crawford     {
22757dc7771cSEwan Crawford         // Don't set breakpoint on 'root' kernel
22767dc7771cSEwan Crawford         if (strcmp(kernel.m_name.AsCString(), "root") == 0)
22777dc7771cSEwan Crawford             continue;
22787dc7771cSEwan Crawford 
22797dc7771cSEwan Crawford         CreateKernelBreakpoint(kernel.m_name);
22807dc7771cSEwan Crawford     }
22817dc7771cSEwan Crawford }
22827dc7771cSEwan Crawford 
22837dc7771cSEwan Crawford // Method is internally called by the 'kernel breakpoint all' command to
22847dc7771cSEwan Crawford // enable or disable breaking on all kernels.
22857dc7771cSEwan Crawford //
22867dc7771cSEwan Crawford // When do_break is true we want to enable this functionality.
22877dc7771cSEwan Crawford // When do_break is false we want to disable it.
22887dc7771cSEwan Crawford void
22897dc7771cSEwan Crawford RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target)
22907dc7771cSEwan Crawford {
229154782db7SEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
22927dc7771cSEwan Crawford 
22937dc7771cSEwan Crawford     InitSearchFilter(target);
22947dc7771cSEwan Crawford 
22957dc7771cSEwan Crawford     // Set breakpoints on all the kernels
22967dc7771cSEwan Crawford     if (do_break && !m_breakAllKernels)
22977dc7771cSEwan Crawford     {
22987dc7771cSEwan Crawford         m_breakAllKernels = true;
22997dc7771cSEwan Crawford 
23007dc7771cSEwan Crawford         for (const auto &module : m_rsmodules)
23017dc7771cSEwan Crawford             BreakOnModuleKernels(module);
23027dc7771cSEwan Crawford 
23037dc7771cSEwan Crawford         if (log)
23047dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::SetBreakAllKernels(True)"
23057dc7771cSEwan Crawford                         "- breakpoints set on all currently loaded kernels");
23067dc7771cSEwan Crawford     }
23077dc7771cSEwan Crawford     else if (!do_break && m_breakAllKernels) // Breakpoints won't be set on any new kernels.
23087dc7771cSEwan Crawford     {
23097dc7771cSEwan Crawford         m_breakAllKernels = false;
23107dc7771cSEwan Crawford 
23117dc7771cSEwan Crawford         if (log)
23127dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::SetBreakAllKernels(False) - breakpoints no longer automatically set");
23137dc7771cSEwan Crawford     }
23147dc7771cSEwan Crawford }
23157dc7771cSEwan Crawford 
23167dc7771cSEwan Crawford // Given the name of a kernel this function creates a breakpoint using our
23177dc7771cSEwan Crawford // own breakpoint resolver, and returns the Breakpoint shared pointer.
23187dc7771cSEwan Crawford BreakpointSP
23197dc7771cSEwan Crawford RenderScriptRuntime::CreateKernelBreakpoint(const ConstString& name)
23207dc7771cSEwan Crawford {
232154782db7SEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
23227dc7771cSEwan Crawford 
23237dc7771cSEwan Crawford     if (!m_filtersp)
23247dc7771cSEwan Crawford     {
23257dc7771cSEwan Crawford         if (log)
23267dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::CreateKernelBreakpoint - Error: No breakpoint search filter set");
23277dc7771cSEwan Crawford         return nullptr;
23287dc7771cSEwan Crawford     }
23297dc7771cSEwan Crawford 
23307dc7771cSEwan Crawford     BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
23317dc7771cSEwan Crawford     BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(m_filtersp, resolver_sp, false, false, false);
23327dc7771cSEwan Crawford 
233354782db7SEwan Crawford     // Give RS breakpoints a specific name, so the user can manipulate them as a group.
233454782db7SEwan Crawford     Error err;
233554782db7SEwan Crawford     if (!bp->AddName("RenderScriptKernel", err) && log)
233654782db7SEwan Crawford         log->Printf("RenderScriptRuntime::CreateKernelBreakpoint: Error setting break name, %s", err.AsCString());
233754782db7SEwan Crawford 
23387dc7771cSEwan Crawford     return bp;
23397dc7771cSEwan Crawford }
23407dc7771cSEwan Crawford 
2341018f5a7eSEwan Crawford // Given an expression for a variable this function tries to calculate the variable's value.
2342018f5a7eSEwan Crawford // If this is possible it returns true and sets the uint64_t parameter to the variables unsigned value.
2343018f5a7eSEwan Crawford // Otherwise function returns false.
2344018f5a7eSEwan Crawford bool
2345018f5a7eSEwan Crawford RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp, const char* var_name, uint64_t& val)
2346018f5a7eSEwan Crawford {
2347018f5a7eSEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2348018f5a7eSEwan Crawford     Error error;
2349018f5a7eSEwan Crawford     VariableSP var_sp;
2350018f5a7eSEwan Crawford 
2351018f5a7eSEwan Crawford     // Find variable in stack frame
2352018f5a7eSEwan Crawford     ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(var_name,
2353018f5a7eSEwan Crawford                                                                        eNoDynamicValues,
2354018f5a7eSEwan Crawford                                                                        StackFrame::eExpressionPathOptionCheckPtrVsMember |
2355018f5a7eSEwan Crawford                                                                        StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
2356018f5a7eSEwan Crawford                                                                        var_sp,
2357018f5a7eSEwan Crawford                                                                        error));
2358018f5a7eSEwan Crawford     if (!error.Success())
2359018f5a7eSEwan Crawford     {
2360018f5a7eSEwan Crawford         if (log)
2361018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't find '%s' in frame", var_name);
2362018f5a7eSEwan Crawford 
2363018f5a7eSEwan Crawford         return false;
2364018f5a7eSEwan Crawford     }
2365018f5a7eSEwan Crawford 
2366018f5a7eSEwan Crawford     // Find the unsigned int value for the variable
2367018f5a7eSEwan Crawford     bool success = false;
2368018f5a7eSEwan Crawford     val = value_sp->GetValueAsUnsigned(0, &success);
2369018f5a7eSEwan Crawford     if (!success)
2370018f5a7eSEwan Crawford     {
2371018f5a7eSEwan Crawford         if (log)
2372018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't parse '%s' as an unsigned int", var_name);
2373018f5a7eSEwan Crawford 
2374018f5a7eSEwan Crawford         return false;
2375018f5a7eSEwan Crawford     }
2376018f5a7eSEwan Crawford 
2377018f5a7eSEwan Crawford     return true;
2378018f5a7eSEwan Crawford }
2379018f5a7eSEwan Crawford 
2380018f5a7eSEwan Crawford // Callback when a kernel breakpoint hits and we're looking for a specific coordinate.
2381018f5a7eSEwan Crawford // Baton parameter contains a pointer to the target coordinate we want to break on.
2382018f5a7eSEwan Crawford // Function then checks the .expand frame for the current coordinate and breaks to user if it matches.
2383018f5a7eSEwan Crawford // Parameter 'break_id' is the id of the Breakpoint which made the callback.
2384018f5a7eSEwan Crawford // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
2385018f5a7eSEwan Crawford // a single logical breakpoint can have multiple addresses.
2386018f5a7eSEwan Crawford bool
2387018f5a7eSEwan Crawford RenderScriptRuntime::KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx,
2388018f5a7eSEwan Crawford                                          user_id_t break_id, user_id_t break_loc_id)
2389018f5a7eSEwan Crawford {
2390018f5a7eSEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
2391018f5a7eSEwan Crawford 
2392018f5a7eSEwan Crawford     assert(baton && "Error: null baton in conditional kernel breakpoint callback");
2393018f5a7eSEwan Crawford 
2394018f5a7eSEwan Crawford     // Coordinate we want to stop on
2395018f5a7eSEwan Crawford     const int* target_coord = static_cast<const int*>(baton);
2396018f5a7eSEwan Crawford 
2397018f5a7eSEwan Crawford     if (log)
2398018f5a7eSEwan Crawford         log->Printf("RenderScriptRuntime::KernelBreakpointHit - Break ID %" PRIu64 ", target coord (%d, %d, %d)",
2399018f5a7eSEwan Crawford                     break_id, target_coord[0], target_coord[1], target_coord[2]);
2400018f5a7eSEwan Crawford 
2401018f5a7eSEwan Crawford     // Go up one stack frame to .expand kernel
2402018f5a7eSEwan Crawford     ExecutionContext context(ctx->exe_ctx_ref);
2403018f5a7eSEwan Crawford     ThreadSP thread_sp = context.GetThreadSP();
2404018f5a7eSEwan Crawford     if (!thread_sp->SetSelectedFrameByIndex(1))
2405018f5a7eSEwan Crawford     {
2406018f5a7eSEwan Crawford         if (log)
2407018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't go up stack frame");
2408018f5a7eSEwan Crawford 
2409018f5a7eSEwan Crawford        return false;
2410018f5a7eSEwan Crawford     }
2411018f5a7eSEwan Crawford 
2412018f5a7eSEwan Crawford     StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
2413018f5a7eSEwan Crawford     if (!frame_sp)
2414018f5a7eSEwan Crawford     {
2415018f5a7eSEwan Crawford         if (log)
2416018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't select .expand stack frame");
2417018f5a7eSEwan Crawford 
2418018f5a7eSEwan Crawford         return false;
2419018f5a7eSEwan Crawford     }
2420018f5a7eSEwan Crawford 
2421018f5a7eSEwan Crawford     // Get values for variables in .expand frame that tell us the current kernel invocation
2422018f5a7eSEwan Crawford     const char* coord_expressions[] = {"rsIndex", "p->current.y", "p->current.z"};
2423018f5a7eSEwan Crawford     uint64_t current_coord[3] = {0, 0, 0};
2424018f5a7eSEwan Crawford 
2425018f5a7eSEwan Crawford     for(int i = 0; i < 3; ++i)
2426018f5a7eSEwan Crawford     {
2427018f5a7eSEwan Crawford         if (!GetFrameVarAsUnsigned(frame_sp, coord_expressions[i], current_coord[i]))
2428018f5a7eSEwan Crawford             return false;
2429018f5a7eSEwan Crawford 
2430018f5a7eSEwan Crawford         if (log)
2431018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit, %s = %" PRIu64, coord_expressions[i], current_coord[i]);
2432018f5a7eSEwan Crawford     }
2433018f5a7eSEwan Crawford 
2434018f5a7eSEwan Crawford     // Check if the current kernel invocation coordinate matches our target coordinate
2435018f5a7eSEwan Crawford     if (current_coord[0] == static_cast<uint64_t>(target_coord[0]) &&
2436018f5a7eSEwan Crawford         current_coord[1] == static_cast<uint64_t>(target_coord[1]) &&
2437018f5a7eSEwan Crawford         current_coord[2] == static_cast<uint64_t>(target_coord[2]))
2438018f5a7eSEwan Crawford     {
2439018f5a7eSEwan Crawford         if (log)
2440018f5a7eSEwan Crawford              log->Printf("RenderScriptRuntime::KernelBreakpointHit, BREAKING %" PRIu64 ", %" PRIu64 ", %" PRIu64,
2441018f5a7eSEwan Crawford                          current_coord[0], current_coord[1], current_coord[2]);
2442018f5a7eSEwan Crawford 
2443018f5a7eSEwan Crawford         BreakpointSP breakpoint_sp = context.GetTargetPtr()->GetBreakpointByID(break_id);
2444018f5a7eSEwan Crawford         assert(breakpoint_sp != nullptr && "Error: Couldn't find breakpoint matching break id for callback");
2445018f5a7eSEwan Crawford         breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint should only be hit once.
2446018f5a7eSEwan Crawford         return true;
2447018f5a7eSEwan Crawford     }
2448018f5a7eSEwan Crawford 
2449018f5a7eSEwan Crawford     // No match on coordinate
2450018f5a7eSEwan Crawford     return false;
2451018f5a7eSEwan Crawford }
2452018f5a7eSEwan Crawford 
2453018f5a7eSEwan Crawford // Tries to set a breakpoint on the start of a kernel, resolved using the kernel name.
2454018f5a7eSEwan Crawford // Argument 'coords', represents a three dimensional coordinate which can be used to specify
2455018f5a7eSEwan Crawford // a single kernel instance to break on. If this is set then we add a callback to the breakpoint.
24564640cde1SColin Riley void
2457018f5a7eSEwan Crawford RenderScriptRuntime::PlaceBreakpointOnKernel(Stream &strm, const char* name, const std::array<int,3> coords,
2458018f5a7eSEwan Crawford                                              Error& error, TargetSP target)
24594640cde1SColin Riley {
24604640cde1SColin Riley     if (!name)
24614640cde1SColin Riley     {
24624640cde1SColin Riley         error.SetErrorString("invalid kernel name");
24634640cde1SColin Riley         return;
24644640cde1SColin Riley     }
24654640cde1SColin Riley 
24667dc7771cSEwan Crawford     InitSearchFilter(target);
246798156583SEwan Crawford 
24684640cde1SColin Riley     ConstString kernel_name(name);
24697dc7771cSEwan Crawford     BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
2470018f5a7eSEwan Crawford 
2471018f5a7eSEwan Crawford     // We have a conditional breakpoint on a specific coordinate
2472018f5a7eSEwan Crawford     if (coords[0] != -1)
2473018f5a7eSEwan Crawford     {
2474018f5a7eSEwan Crawford         strm.Printf("Conditional kernel breakpoint on coordinate %d, %d, %d", coords[0], coords[1], coords[2]);
2475018f5a7eSEwan Crawford         strm.EOL();
2476018f5a7eSEwan Crawford 
2477018f5a7eSEwan Crawford         // Allocate memory for the baton, and copy over coordinate
2478018f5a7eSEwan Crawford         int* baton = new int[3];
2479018f5a7eSEwan Crawford         baton[0] = coords[0]; baton[1] = coords[1]; baton[2] = coords[2];
2480018f5a7eSEwan Crawford 
2481018f5a7eSEwan Crawford         // Create a callback that will be invoked everytime the breakpoint is hit.
2482018f5a7eSEwan Crawford         // The baton object passed to the handler is the target coordinate we want to break on.
2483018f5a7eSEwan Crawford         bp->SetCallback(KernelBreakpointHit, baton, true);
2484018f5a7eSEwan Crawford 
2485018f5a7eSEwan Crawford         // Store a shared pointer to the baton, so the memory will eventually be cleaned up after destruction
2486018f5a7eSEwan Crawford         m_conditional_breaks[bp->GetID()] = std::shared_ptr<int>(baton);
2487018f5a7eSEwan Crawford     }
2488018f5a7eSEwan Crawford 
248998156583SEwan Crawford     if (bp)
249098156583SEwan Crawford         bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
24914640cde1SColin Riley }
24924640cde1SColin Riley 
24934640cde1SColin Riley void
24945ec532a9SColin Riley RenderScriptRuntime::DumpModules(Stream &strm) const
24955ec532a9SColin Riley {
24965ec532a9SColin Riley     strm.Printf("RenderScript Modules:");
24975ec532a9SColin Riley     strm.EOL();
24985ec532a9SColin Riley     strm.IndentMore();
24995ec532a9SColin Riley     for (const auto &module : m_rsmodules)
25005ec532a9SColin Riley     {
25014640cde1SColin Riley         module->Dump(strm);
25025ec532a9SColin Riley     }
25035ec532a9SColin Riley     strm.IndentLess();
25045ec532a9SColin Riley }
25055ec532a9SColin Riley 
250678f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails*
250778f339d1SEwan Crawford RenderScriptRuntime::LookUpScript(addr_t address, bool create)
250878f339d1SEwan Crawford {
250978f339d1SEwan Crawford     for (const auto & s : m_scripts)
251078f339d1SEwan Crawford     {
251178f339d1SEwan Crawford         if (s->script.isValid())
251278f339d1SEwan Crawford             if (*s->script == address)
251378f339d1SEwan Crawford                 return s.get();
251478f339d1SEwan Crawford     }
251578f339d1SEwan Crawford     if (create)
251678f339d1SEwan Crawford     {
251778f339d1SEwan Crawford         std::unique_ptr<ScriptDetails> s(new ScriptDetails);
251878f339d1SEwan Crawford         s->script = address;
251978f339d1SEwan Crawford         m_scripts.push_back(std::move(s));
2520d10ca9deSEwan Crawford         return m_scripts.back().get();
252178f339d1SEwan Crawford     }
252278f339d1SEwan Crawford     return nullptr;
252378f339d1SEwan Crawford }
252478f339d1SEwan Crawford 
252578f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails*
252678f339d1SEwan Crawford RenderScriptRuntime::LookUpAllocation(addr_t address, bool create)
252778f339d1SEwan Crawford {
252878f339d1SEwan Crawford     for (const auto & a : m_allocations)
252978f339d1SEwan Crawford     {
253078f339d1SEwan Crawford         if (a->address.isValid())
253178f339d1SEwan Crawford             if (*a->address == address)
253278f339d1SEwan Crawford                 return a.get();
253378f339d1SEwan Crawford     }
253478f339d1SEwan Crawford     if (create)
253578f339d1SEwan Crawford     {
253678f339d1SEwan Crawford         std::unique_ptr<AllocationDetails> a(new AllocationDetails);
253778f339d1SEwan Crawford         a->address = address;
253878f339d1SEwan Crawford         m_allocations.push_back(std::move(a));
2539d10ca9deSEwan Crawford         return m_allocations.back().get();
254078f339d1SEwan Crawford     }
254178f339d1SEwan Crawford     return nullptr;
254278f339d1SEwan Crawford }
254378f339d1SEwan Crawford 
25445ec532a9SColin Riley void
25455ec532a9SColin Riley RSModuleDescriptor::Dump(Stream &strm) const
25465ec532a9SColin Riley {
25475ec532a9SColin Riley     strm.Indent();
25485ec532a9SColin Riley     m_module->GetFileSpec().Dump(&strm);
25494640cde1SColin Riley     if(m_module->GetNumCompileUnits())
25504640cde1SColin Riley     {
25514640cde1SColin Riley         strm.Indent("Debug info loaded.");
25524640cde1SColin Riley     }
25534640cde1SColin Riley     else
25544640cde1SColin Riley     {
25554640cde1SColin Riley         strm.Indent("Debug info does not exist.");
25564640cde1SColin Riley     }
25575ec532a9SColin Riley     strm.EOL();
25585ec532a9SColin Riley     strm.IndentMore();
25595ec532a9SColin Riley     strm.Indent();
2560189598edSColin Riley     strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
25615ec532a9SColin Riley     strm.EOL();
25625ec532a9SColin Riley     strm.IndentMore();
25635ec532a9SColin Riley     for (const auto &global : m_globals)
25645ec532a9SColin Riley     {
25655ec532a9SColin Riley         global.Dump(strm);
25665ec532a9SColin Riley     }
25675ec532a9SColin Riley     strm.IndentLess();
25685ec532a9SColin Riley     strm.Indent();
2569189598edSColin Riley     strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
25705ec532a9SColin Riley     strm.EOL();
25715ec532a9SColin Riley     strm.IndentMore();
25725ec532a9SColin Riley     for (const auto &kernel : m_kernels)
25735ec532a9SColin Riley     {
25745ec532a9SColin Riley         kernel.Dump(strm);
25755ec532a9SColin Riley     }
25764640cde1SColin Riley     strm.Printf("Pragmas: %"  PRIu64 , static_cast<uint64_t>(m_pragmas.size()));
25774640cde1SColin Riley     strm.EOL();
25784640cde1SColin Riley     strm.IndentMore();
25794640cde1SColin Riley     for (const auto &key_val : m_pragmas)
25804640cde1SColin Riley     {
25814640cde1SColin Riley         strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
25824640cde1SColin Riley         strm.EOL();
25834640cde1SColin Riley     }
25845ec532a9SColin Riley     strm.IndentLess(4);
25855ec532a9SColin Riley }
25865ec532a9SColin Riley 
25875ec532a9SColin Riley void
25885ec532a9SColin Riley RSGlobalDescriptor::Dump(Stream &strm) const
25895ec532a9SColin Riley {
25905ec532a9SColin Riley     strm.Indent(m_name.AsCString());
25914640cde1SColin Riley     VariableList var_list;
25924640cde1SColin Riley     m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
25934640cde1SColin Riley     if (var_list.GetSize() == 1)
25944640cde1SColin Riley     {
25954640cde1SColin Riley         auto var = var_list.GetVariableAtIndex(0);
25964640cde1SColin Riley         auto type = var->GetType();
25974640cde1SColin Riley         if(type)
25984640cde1SColin Riley         {
25994640cde1SColin Riley             strm.Printf(" - ");
26004640cde1SColin Riley             type->DumpTypeName(&strm);
26014640cde1SColin Riley         }
26024640cde1SColin Riley         else
26034640cde1SColin Riley         {
26044640cde1SColin Riley             strm.Printf(" - Unknown Type");
26054640cde1SColin Riley         }
26064640cde1SColin Riley     }
26074640cde1SColin Riley     else
26084640cde1SColin Riley     {
26094640cde1SColin Riley         strm.Printf(" - variable identified, but not found in binary");
26104640cde1SColin Riley         const Symbol* s = m_module->m_module->FindFirstSymbolWithNameAndType(m_name, eSymbolTypeData);
26114640cde1SColin Riley         if (s)
26124640cde1SColin Riley         {
26134640cde1SColin Riley             strm.Printf(" (symbol exists) ");
26144640cde1SColin Riley         }
26154640cde1SColin Riley     }
26164640cde1SColin Riley 
26175ec532a9SColin Riley     strm.EOL();
26185ec532a9SColin Riley }
26195ec532a9SColin Riley 
26205ec532a9SColin Riley void
26215ec532a9SColin Riley RSKernelDescriptor::Dump(Stream &strm) const
26225ec532a9SColin Riley {
26235ec532a9SColin Riley     strm.Indent(m_name.AsCString());
26245ec532a9SColin Riley     strm.EOL();
26255ec532a9SColin Riley }
26265ec532a9SColin Riley 
26275ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleProbe : public CommandObjectParsed
26285ec532a9SColin Riley {
26295ec532a9SColin Riley public:
26305ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleProbe(CommandInterpreter &interpreter)
26315ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module probe",
26325ec532a9SColin Riley                               "Initiates a Probe of all loaded modules for kernels and other renderscript objects.",
26335ec532a9SColin Riley                               "renderscript module probe",
2634e87764f2SEnrico Granata                               eCommandRequiresTarget | eCommandRequiresProcess | eCommandProcessMustBeLaunched)
26355ec532a9SColin Riley     {
26365ec532a9SColin Riley     }
26375ec532a9SColin Riley 
2638222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModuleProbe() override = default;
26395ec532a9SColin Riley 
26405ec532a9SColin Riley     bool
2641222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
26425ec532a9SColin Riley     {
26435ec532a9SColin Riley         const size_t argc = command.GetArgumentCount();
26445ec532a9SColin Riley         if (argc == 0)
26455ec532a9SColin Riley         {
26465ec532a9SColin Riley             Target *target = m_exe_ctx.GetTargetPtr();
26475ec532a9SColin Riley             RenderScriptRuntime *runtime =
26485ec532a9SColin Riley                 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
26495ec532a9SColin Riley             auto module_list = target->GetImages();
26505ec532a9SColin Riley             bool new_rs_details = runtime->ProbeModules(module_list);
26515ec532a9SColin Riley             if (new_rs_details)
26525ec532a9SColin Riley             {
26535ec532a9SColin Riley                 result.AppendMessage("New renderscript modules added to runtime model.");
26545ec532a9SColin Riley             }
26555ec532a9SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
26565ec532a9SColin Riley             return true;
26575ec532a9SColin Riley         }
26585ec532a9SColin Riley 
26595ec532a9SColin Riley         result.AppendErrorWithFormat("'%s' takes no arguments", m_cmd_name.c_str());
26605ec532a9SColin Riley         result.SetStatus(eReturnStatusFailed);
26615ec532a9SColin Riley         return false;
26625ec532a9SColin Riley     }
26635ec532a9SColin Riley };
26645ec532a9SColin Riley 
26655ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed
26665ec532a9SColin Riley {
26675ec532a9SColin Riley public:
26685ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
26695ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module dump",
26705ec532a9SColin Riley                               "Dumps renderscript specific information for all modules.", "renderscript module dump",
2671e87764f2SEnrico Granata                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
26725ec532a9SColin Riley     {
26735ec532a9SColin Riley     }
26745ec532a9SColin Riley 
2675222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
26765ec532a9SColin Riley 
26775ec532a9SColin Riley     bool
2678222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
26795ec532a9SColin Riley     {
26805ec532a9SColin Riley         RenderScriptRuntime *runtime =
26815ec532a9SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
26825ec532a9SColin Riley         runtime->DumpModules(result.GetOutputStream());
26835ec532a9SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
26845ec532a9SColin Riley         return true;
26855ec532a9SColin Riley     }
26865ec532a9SColin Riley };
26875ec532a9SColin Riley 
26885ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword
26895ec532a9SColin Riley {
26905ec532a9SColin Riley public:
26915ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
26925ec532a9SColin Riley         : CommandObjectMultiword(interpreter, "renderscript module", "Commands that deal with renderscript modules.",
26935ec532a9SColin Riley                                  NULL)
26945ec532a9SColin Riley     {
26955ec532a9SColin Riley         LoadSubCommand("probe", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleProbe(interpreter)));
26965ec532a9SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(interpreter)));
26975ec532a9SColin Riley     }
26985ec532a9SColin Riley 
2699222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModule() override = default;
27005ec532a9SColin Riley };
27015ec532a9SColin Riley 
27024640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed
27034640cde1SColin Riley {
27044640cde1SColin Riley public:
27054640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
27064640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript kernel list",
27074640cde1SColin Riley                               "Lists renderscript kernel names and associated script resources.", "renderscript kernel list",
27084640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
27094640cde1SColin Riley     {
27104640cde1SColin Riley     }
27114640cde1SColin Riley 
2712222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelList() override = default;
27134640cde1SColin Riley 
27144640cde1SColin Riley     bool
2715222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
27164640cde1SColin Riley     {
27174640cde1SColin Riley         RenderScriptRuntime *runtime =
27184640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
27194640cde1SColin Riley         runtime->DumpKernels(result.GetOutputStream());
27204640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
27214640cde1SColin Riley         return true;
27224640cde1SColin Riley     }
27234640cde1SColin Riley };
27244640cde1SColin Riley 
27257dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointSet : public CommandObjectParsed
27264640cde1SColin Riley {
27274640cde1SColin Riley public:
27287dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointSet(CommandInterpreter &interpreter)
27297dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint set",
2730018f5a7eSEwan Crawford                               "Sets a breakpoint on a renderscript kernel.", "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
2731018f5a7eSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), m_options(interpreter)
27324640cde1SColin Riley     {
27334640cde1SColin Riley     }
27344640cde1SColin Riley 
2735222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
2736222b937cSEugene Zelenko 
2737222b937cSEugene Zelenko     Options*
2738222b937cSEugene Zelenko     GetOptions() override
2739018f5a7eSEwan Crawford     {
2740018f5a7eSEwan Crawford         return &m_options;
2741018f5a7eSEwan Crawford     }
2742018f5a7eSEwan Crawford 
2743018f5a7eSEwan Crawford     class CommandOptions : public Options
2744018f5a7eSEwan Crawford     {
2745018f5a7eSEwan Crawford     public:
2746018f5a7eSEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter)
2747018f5a7eSEwan Crawford         {
2748018f5a7eSEwan Crawford         }
2749018f5a7eSEwan Crawford 
2750222b937cSEugene Zelenko         ~CommandOptions() override = default;
2751018f5a7eSEwan Crawford 
2752222b937cSEugene Zelenko         Error
2753222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
2754018f5a7eSEwan Crawford         {
2755018f5a7eSEwan Crawford             Error error;
2756018f5a7eSEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
2757018f5a7eSEwan Crawford 
2758018f5a7eSEwan Crawford             switch (short_option)
2759018f5a7eSEwan Crawford             {
2760018f5a7eSEwan Crawford                 case 'c':
2761018f5a7eSEwan Crawford                     if (!ParseCoordinate(option_arg))
2762018f5a7eSEwan Crawford                         error.SetErrorStringWithFormat("Couldn't parse coordinate '%s', should be in format 'x,y,z'.", option_arg);
2763018f5a7eSEwan Crawford                     break;
2764018f5a7eSEwan Crawford                 default:
2765018f5a7eSEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
2766018f5a7eSEwan Crawford                     break;
2767018f5a7eSEwan Crawford             }
2768018f5a7eSEwan Crawford             return error;
2769018f5a7eSEwan Crawford         }
2770018f5a7eSEwan Crawford 
2771018f5a7eSEwan Crawford         // -c takes an argument of the form 'num[,num][,num]'.
2772018f5a7eSEwan Crawford         // Where 'id_cstr' is this argument with the whitespace trimmed.
2773018f5a7eSEwan Crawford         // Missing coordinates are defaulted to zero.
2774018f5a7eSEwan Crawford         bool
2775018f5a7eSEwan Crawford         ParseCoordinate(const char* id_cstr)
2776018f5a7eSEwan Crawford         {
2777018f5a7eSEwan Crawford             RegularExpression regex;
2778018f5a7eSEwan Crawford             RegularExpression::Match regex_match(3);
2779018f5a7eSEwan Crawford 
2780018f5a7eSEwan Crawford             bool matched = false;
2781018f5a7eSEwan Crawford             if(regex.Compile("^([0-9]+),([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
2782018f5a7eSEwan Crawford                 matched = true;
2783018f5a7eSEwan Crawford             else if(regex.Compile("^([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
2784018f5a7eSEwan Crawford                 matched = true;
2785018f5a7eSEwan Crawford             else if(regex.Compile("^([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
2786018f5a7eSEwan Crawford                 matched = true;
2787018f5a7eSEwan Crawford             for(uint32_t i = 0; i < 3; i++)
2788018f5a7eSEwan Crawford             {
2789018f5a7eSEwan Crawford                 std::string group;
2790018f5a7eSEwan Crawford                 if(regex_match.GetMatchAtIndex(id_cstr, i + 1, group))
2791018f5a7eSEwan Crawford                     m_coord[i] = (uint32_t)strtoul(group.c_str(), NULL, 0);
2792018f5a7eSEwan Crawford                 else
2793018f5a7eSEwan Crawford                     m_coord[i] = 0;
2794018f5a7eSEwan Crawford             }
2795018f5a7eSEwan Crawford             return matched;
2796018f5a7eSEwan Crawford         }
2797018f5a7eSEwan Crawford 
2798018f5a7eSEwan Crawford         void
2799222b937cSEugene Zelenko         OptionParsingStarting() override
2800018f5a7eSEwan Crawford         {
2801018f5a7eSEwan Crawford             // -1 means the -c option hasn't been set
2802018f5a7eSEwan Crawford             m_coord[0] = -1;
2803018f5a7eSEwan Crawford             m_coord[1] = -1;
2804018f5a7eSEwan Crawford             m_coord[2] = -1;
2805018f5a7eSEwan Crawford         }
2806018f5a7eSEwan Crawford 
2807018f5a7eSEwan Crawford         const OptionDefinition*
2808222b937cSEugene Zelenko         GetDefinitions() override
2809018f5a7eSEwan Crawford         {
2810018f5a7eSEwan Crawford             return g_option_table;
2811018f5a7eSEwan Crawford         }
2812018f5a7eSEwan Crawford 
2813018f5a7eSEwan Crawford         static OptionDefinition g_option_table[];
2814018f5a7eSEwan Crawford         std::array<int,3> m_coord;
2815018f5a7eSEwan Crawford     };
2816018f5a7eSEwan Crawford 
28174640cde1SColin Riley     bool
2818222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
28194640cde1SColin Riley     {
28204640cde1SColin Riley         const size_t argc = command.GetArgumentCount();
2821018f5a7eSEwan Crawford         if (argc < 1)
28224640cde1SColin Riley         {
2823018f5a7eSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of kernel name, and an optional coordinate.", m_cmd_name.c_str());
2824018f5a7eSEwan Crawford             result.SetStatus(eReturnStatusFailed);
2825018f5a7eSEwan Crawford             return false;
2826018f5a7eSEwan Crawford         }
2827018f5a7eSEwan Crawford 
28284640cde1SColin Riley         RenderScriptRuntime *runtime =
28294640cde1SColin Riley                 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
28304640cde1SColin Riley 
28314640cde1SColin Riley         Error error;
2832018f5a7eSEwan Crawford         runtime->PlaceBreakpointOnKernel(result.GetOutputStream(), command.GetArgumentAtIndex(0), m_options.m_coord,
283398156583SEwan Crawford                                          error, m_exe_ctx.GetTargetSP());
28344640cde1SColin Riley 
28354640cde1SColin Riley         if (error.Success())
28364640cde1SColin Riley         {
28374640cde1SColin Riley             result.AppendMessage("Breakpoint(s) created");
28384640cde1SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
28394640cde1SColin Riley             return true;
28404640cde1SColin Riley         }
28414640cde1SColin Riley         result.SetStatus(eReturnStatusFailed);
28424640cde1SColin Riley         result.AppendErrorWithFormat("Error: %s", error.AsCString());
28434640cde1SColin Riley         return false;
28444640cde1SColin Riley     }
28454640cde1SColin Riley 
2846018f5a7eSEwan Crawford private:
2847018f5a7eSEwan Crawford     CommandOptions m_options;
28484640cde1SColin Riley };
28494640cde1SColin Riley 
2850018f5a7eSEwan Crawford OptionDefinition
2851018f5a7eSEwan Crawford CommandObjectRenderScriptRuntimeKernelBreakpointSet::CommandOptions::g_option_table[] =
2852018f5a7eSEwan Crawford {
2853018f5a7eSEwan Crawford     { LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeValue,
2854018f5a7eSEwan Crawford       "Set a breakpoint on a single invocation of the kernel with specified coordinate.\n"
2855018f5a7eSEwan Crawford       "Coordinate takes the form 'x[,y][,z] where x,y,z are positive integers representing kernel dimensions. "
2856018f5a7eSEwan Crawford       "Any unset dimensions will be defaulted to zero."},
2857018f5a7eSEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
2858018f5a7eSEwan Crawford };
2859018f5a7eSEwan Crawford 
28607dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointAll : public CommandObjectParsed
28617dc7771cSEwan Crawford {
28627dc7771cSEwan Crawford public:
28637dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointAll(CommandInterpreter &interpreter)
28647dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint all",
28657dc7771cSEwan Crawford                               "Automatically sets a breakpoint on all renderscript kernels that are or will be loaded.\n"
28667dc7771cSEwan Crawford                               "Disabling option means breakpoints will no longer be set on any kernels loaded in the future, "
28677dc7771cSEwan Crawford                               "but does not remove currently set breakpoints.",
28687dc7771cSEwan Crawford                               "renderscript kernel breakpoint all <enable/disable>",
28697dc7771cSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
28707dc7771cSEwan Crawford     {
28717dc7771cSEwan Crawford     }
28727dc7771cSEwan Crawford 
2873222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
28747dc7771cSEwan Crawford 
28757dc7771cSEwan Crawford     bool
2876222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
28777dc7771cSEwan Crawford     {
28787dc7771cSEwan Crawford         const size_t argc = command.GetArgumentCount();
28797dc7771cSEwan Crawford         if (argc != 1)
28807dc7771cSEwan Crawford         {
28817dc7771cSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
28827dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
28837dc7771cSEwan Crawford             return false;
28847dc7771cSEwan Crawford         }
28857dc7771cSEwan Crawford 
28867dc7771cSEwan Crawford         RenderScriptRuntime *runtime =
28877dc7771cSEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
28887dc7771cSEwan Crawford 
28897dc7771cSEwan Crawford         bool do_break = false;
28907dc7771cSEwan Crawford         const char* argument = command.GetArgumentAtIndex(0);
28917dc7771cSEwan Crawford         if (strcmp(argument, "enable") == 0)
28927dc7771cSEwan Crawford         {
28937dc7771cSEwan Crawford             do_break = true;
28947dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will be set on all kernels.");
28957dc7771cSEwan Crawford         }
28967dc7771cSEwan Crawford         else if (strcmp(argument, "disable") == 0)
28977dc7771cSEwan Crawford         {
28987dc7771cSEwan Crawford             do_break = false;
28997dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will not be set on any new kernels.");
29007dc7771cSEwan Crawford         }
29017dc7771cSEwan Crawford         else
29027dc7771cSEwan Crawford         {
29037dc7771cSEwan Crawford             result.AppendErrorWithFormat("Argument must be either 'enable' or 'disable'");
29047dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
29057dc7771cSEwan Crawford             return false;
29067dc7771cSEwan Crawford         }
29077dc7771cSEwan Crawford 
29087dc7771cSEwan Crawford         runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
29097dc7771cSEwan Crawford 
29107dc7771cSEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
29117dc7771cSEwan Crawford         return true;
29127dc7771cSEwan Crawford     }
29137dc7771cSEwan Crawford };
29147dc7771cSEwan Crawford 
29157dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpoint : public CommandObjectMultiword
29167dc7771cSEwan Crawford {
29177dc7771cSEwan Crawford public:
29187dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpoint(CommandInterpreter &interpreter)
29197dc7771cSEwan Crawford         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that generate breakpoints on renderscript kernels.",
29207dc7771cSEwan Crawford                                  nullptr)
29217dc7771cSEwan Crawford     {
29227dc7771cSEwan Crawford         LoadSubCommand("set", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(interpreter)));
29237dc7771cSEwan Crawford         LoadSubCommand("all", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(interpreter)));
29247dc7771cSEwan Crawford     }
29257dc7771cSEwan Crawford 
2926222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
29277dc7771cSEwan Crawford };
29287dc7771cSEwan Crawford 
29294640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword
29304640cde1SColin Riley {
29314640cde1SColin Riley public:
29324640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
29334640cde1SColin Riley         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that deal with renderscript kernels.",
29344640cde1SColin Riley                                  NULL)
29354640cde1SColin Riley     {
29364640cde1SColin Riley         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(interpreter)));
29374640cde1SColin Riley         LoadSubCommand("breakpoint", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
29384640cde1SColin Riley     }
29394640cde1SColin Riley 
2940222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernel() override = default;
29414640cde1SColin Riley };
29424640cde1SColin Riley 
29434640cde1SColin Riley class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed
29444640cde1SColin Riley {
29454640cde1SColin Riley public:
29464640cde1SColin Riley     CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
29474640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript context dump",
29484640cde1SColin Riley                               "Dumps renderscript context information.", "renderscript context dump",
29494640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
29504640cde1SColin Riley     {
29514640cde1SColin Riley     }
29524640cde1SColin Riley 
2953222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeContextDump() override = default;
29544640cde1SColin Riley 
29554640cde1SColin Riley     bool
2956222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
29574640cde1SColin Riley     {
29584640cde1SColin Riley         RenderScriptRuntime *runtime =
29594640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
29604640cde1SColin Riley         runtime->DumpContexts(result.GetOutputStream());
29614640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
29624640cde1SColin Riley         return true;
29634640cde1SColin Riley     }
29644640cde1SColin Riley };
29654640cde1SColin Riley 
29664640cde1SColin Riley class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword
29674640cde1SColin Riley {
29684640cde1SColin Riley public:
29694640cde1SColin Riley     CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
29704640cde1SColin Riley         : CommandObjectMultiword(interpreter, "renderscript context", "Commands that deal with renderscript contexts.",
29714640cde1SColin Riley                                  NULL)
29724640cde1SColin Riley     {
29734640cde1SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(interpreter)));
29744640cde1SColin Riley     }
29754640cde1SColin Riley 
2976222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeContext() override = default;
29774640cde1SColin Riley };
29784640cde1SColin Riley 
2979a0f08674SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationDump : public CommandObjectParsed
2980a0f08674SEwan Crawford {
2981a0f08674SEwan Crawford public:
2982a0f08674SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationDump(CommandInterpreter &interpreter)
2983a0f08674SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation dump",
2984a0f08674SEwan Crawford                               "Displays the contents of a particular allocation", "renderscript allocation dump <ID>",
2985a0f08674SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter)
2986a0f08674SEwan Crawford     {
2987a0f08674SEwan Crawford     }
2988a0f08674SEwan Crawford 
2989222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
2990222b937cSEugene Zelenko 
2991222b937cSEugene Zelenko     Options*
2992222b937cSEugene Zelenko     GetOptions() override
2993a0f08674SEwan Crawford     {
2994a0f08674SEwan Crawford         return &m_options;
2995a0f08674SEwan Crawford     }
2996a0f08674SEwan Crawford 
2997a0f08674SEwan Crawford     class CommandOptions : public Options
2998a0f08674SEwan Crawford     {
2999a0f08674SEwan Crawford     public:
3000a0f08674SEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter)
3001a0f08674SEwan Crawford         {
3002a0f08674SEwan Crawford         }
3003a0f08674SEwan Crawford 
3004222b937cSEugene Zelenko         ~CommandOptions() override = default;
3005a0f08674SEwan Crawford 
3006222b937cSEugene Zelenko         Error
3007222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
3008a0f08674SEwan Crawford         {
3009a0f08674SEwan Crawford             Error error;
3010a0f08674SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
3011a0f08674SEwan Crawford 
3012a0f08674SEwan Crawford             switch (short_option)
3013a0f08674SEwan Crawford             {
3014a0f08674SEwan Crawford                 case 'f':
3015a0f08674SEwan Crawford                     m_outfile.SetFile(option_arg, true);
3016a0f08674SEwan Crawford                     if (m_outfile.Exists())
3017a0f08674SEwan Crawford                     {
3018a0f08674SEwan Crawford                         m_outfile.Clear();
3019a0f08674SEwan Crawford                         error.SetErrorStringWithFormat("file already exists: '%s'", option_arg);
3020a0f08674SEwan Crawford                     }
3021a0f08674SEwan Crawford                     break;
3022a0f08674SEwan Crawford                 default:
3023a0f08674SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3024a0f08674SEwan Crawford                     break;
3025a0f08674SEwan Crawford             }
3026a0f08674SEwan Crawford             return error;
3027a0f08674SEwan Crawford         }
3028a0f08674SEwan Crawford 
3029a0f08674SEwan Crawford         void
3030222b937cSEugene Zelenko         OptionParsingStarting() override
3031a0f08674SEwan Crawford         {
3032a0f08674SEwan Crawford             m_outfile.Clear();
3033a0f08674SEwan Crawford         }
3034a0f08674SEwan Crawford 
3035a0f08674SEwan Crawford         const OptionDefinition*
3036222b937cSEugene Zelenko         GetDefinitions() override
3037a0f08674SEwan Crawford         {
3038a0f08674SEwan Crawford             return g_option_table;
3039a0f08674SEwan Crawford         }
3040a0f08674SEwan Crawford 
3041a0f08674SEwan Crawford         static OptionDefinition g_option_table[];
3042a0f08674SEwan Crawford         FileSpec m_outfile;
3043a0f08674SEwan Crawford     };
3044a0f08674SEwan Crawford 
3045a0f08674SEwan Crawford     bool
3046222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
3047a0f08674SEwan Crawford     {
3048a0f08674SEwan Crawford         const size_t argc = command.GetArgumentCount();
3049a0f08674SEwan Crawford         if (argc < 1)
3050a0f08674SEwan Crawford         {
3051a0f08674SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. As well as an optional -f argument",
3052a0f08674SEwan Crawford                                          m_cmd_name.c_str());
3053a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3054a0f08674SEwan Crawford             return false;
3055a0f08674SEwan Crawford         }
3056a0f08674SEwan Crawford 
3057a0f08674SEwan Crawford         RenderScriptRuntime *runtime =
3058a0f08674SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
3059a0f08674SEwan Crawford 
3060a0f08674SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
3061a0f08674SEwan Crawford         bool convert_complete = false;
3062a0f08674SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
3063a0f08674SEwan Crawford         if (!convert_complete)
3064a0f08674SEwan Crawford         {
3065a0f08674SEwan Crawford             result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
3066a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3067a0f08674SEwan Crawford             return false;
3068a0f08674SEwan Crawford         }
3069a0f08674SEwan Crawford 
3070a0f08674SEwan Crawford         Stream* output_strm = nullptr;
3071a0f08674SEwan Crawford         StreamFile outfile_stream;
3072a0f08674SEwan Crawford         const FileSpec &outfile_spec = m_options.m_outfile; // Dump allocation to file instead
3073a0f08674SEwan Crawford         if (outfile_spec)
3074a0f08674SEwan Crawford         {
3075a0f08674SEwan Crawford             // Open output file
3076a0f08674SEwan Crawford             char path[256];
3077a0f08674SEwan Crawford             outfile_spec.GetPath(path, sizeof(path));
3078a0f08674SEwan Crawford             if (outfile_stream.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate).Success())
3079a0f08674SEwan Crawford             {
3080a0f08674SEwan Crawford                 output_strm = &outfile_stream;
3081a0f08674SEwan Crawford                 result.GetOutputStream().Printf("Results written to '%s'", path);
3082a0f08674SEwan Crawford                 result.GetOutputStream().EOL();
3083a0f08674SEwan Crawford             }
3084a0f08674SEwan Crawford             else
3085a0f08674SEwan Crawford             {
3086a0f08674SEwan Crawford                 result.AppendErrorWithFormat("Couldn't open file '%s'", path);
3087a0f08674SEwan Crawford                 result.SetStatus(eReturnStatusFailed);
3088a0f08674SEwan Crawford                 return false;
3089a0f08674SEwan Crawford             }
3090a0f08674SEwan Crawford         }
3091a0f08674SEwan Crawford         else
3092a0f08674SEwan Crawford             output_strm = &result.GetOutputStream();
3093a0f08674SEwan Crawford 
3094a0f08674SEwan Crawford         assert(output_strm != nullptr);
3095a0f08674SEwan Crawford         bool success = runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
3096a0f08674SEwan Crawford 
3097a0f08674SEwan Crawford         if (success)
3098a0f08674SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
3099a0f08674SEwan Crawford         else
3100a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3101a0f08674SEwan Crawford 
3102a0f08674SEwan Crawford         return true;
3103a0f08674SEwan Crawford     }
3104a0f08674SEwan Crawford 
3105a0f08674SEwan Crawford private:
3106a0f08674SEwan Crawford     CommandOptions m_options;
3107a0f08674SEwan Crawford };
3108a0f08674SEwan Crawford 
3109a0f08674SEwan Crawford OptionDefinition
3110a0f08674SEwan Crawford CommandObjectRenderScriptRuntimeAllocationDump::CommandOptions::g_option_table[] =
3111a0f08674SEwan Crawford {
3112a0f08674SEwan Crawford     { LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename,
3113a0f08674SEwan Crawford       "Print results to specified file instead of command line."},
3114a0f08674SEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
3115a0f08674SEwan Crawford };
3116a0f08674SEwan Crawford 
311715f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationList : public CommandObjectParsed
311815f2bd95SEwan Crawford {
311915f2bd95SEwan Crawford public:
312015f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationList(CommandInterpreter &interpreter)
312115f2bd95SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation list",
312215f2bd95SEwan Crawford                               "List renderscript allocations and their information.", "renderscript allocation list",
312315f2bd95SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter)
312415f2bd95SEwan Crawford     {
312515f2bd95SEwan Crawford     }
312615f2bd95SEwan Crawford 
3127222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
3128222b937cSEugene Zelenko 
3129222b937cSEugene Zelenko     Options*
3130222b937cSEugene Zelenko     GetOptions() override
313115f2bd95SEwan Crawford     {
313215f2bd95SEwan Crawford         return &m_options;
313315f2bd95SEwan Crawford     }
313415f2bd95SEwan Crawford 
313515f2bd95SEwan Crawford     class CommandOptions : public Options
313615f2bd95SEwan Crawford     {
313715f2bd95SEwan Crawford     public:
313815f2bd95SEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter), m_refresh(false)
313915f2bd95SEwan Crawford         {
314015f2bd95SEwan Crawford         }
314115f2bd95SEwan Crawford 
3142222b937cSEugene Zelenko         ~CommandOptions() override = default;
314315f2bd95SEwan Crawford 
3144222b937cSEugene Zelenko         Error
3145222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
314615f2bd95SEwan Crawford         {
314715f2bd95SEwan Crawford             Error error;
314815f2bd95SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
314915f2bd95SEwan Crawford 
315015f2bd95SEwan Crawford             switch (short_option)
315115f2bd95SEwan Crawford             {
315215f2bd95SEwan Crawford                 case 'r':
315315f2bd95SEwan Crawford                     m_refresh = true;
315415f2bd95SEwan Crawford                     break;
315515f2bd95SEwan Crawford                 default:
315615f2bd95SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
315715f2bd95SEwan Crawford                     break;
315815f2bd95SEwan Crawford             }
315915f2bd95SEwan Crawford             return error;
316015f2bd95SEwan Crawford         }
316115f2bd95SEwan Crawford 
316215f2bd95SEwan Crawford         void
3163222b937cSEugene Zelenko         OptionParsingStarting() override
316415f2bd95SEwan Crawford         {
316515f2bd95SEwan Crawford             m_refresh = false;
316615f2bd95SEwan Crawford         }
316715f2bd95SEwan Crawford 
316815f2bd95SEwan Crawford         const OptionDefinition*
3169222b937cSEugene Zelenko         GetDefinitions() override
317015f2bd95SEwan Crawford         {
317115f2bd95SEwan Crawford             return g_option_table;
317215f2bd95SEwan Crawford         }
317315f2bd95SEwan Crawford 
317415f2bd95SEwan Crawford         static OptionDefinition g_option_table[];
317515f2bd95SEwan Crawford         bool m_refresh;
317615f2bd95SEwan Crawford     };
317715f2bd95SEwan Crawford 
317815f2bd95SEwan Crawford     bool
3179222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
318015f2bd95SEwan Crawford     {
318115f2bd95SEwan Crawford         RenderScriptRuntime *runtime =
318215f2bd95SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
318315f2bd95SEwan Crawford         runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(), m_options.m_refresh);
318415f2bd95SEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
318515f2bd95SEwan Crawford         return true;
318615f2bd95SEwan Crawford     }
318715f2bd95SEwan Crawford 
318815f2bd95SEwan Crawford private:
318915f2bd95SEwan Crawford     CommandOptions m_options;
319015f2bd95SEwan Crawford };
319115f2bd95SEwan Crawford 
319215f2bd95SEwan Crawford OptionDefinition
319315f2bd95SEwan Crawford CommandObjectRenderScriptRuntimeAllocationList::CommandOptions::g_option_table[] =
319415f2bd95SEwan Crawford {
319515f2bd95SEwan Crawford     { LLDB_OPT_SET_1, false, "refresh", 'r', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone,
319615f2bd95SEwan Crawford       "Recompute allocation details."},
319715f2bd95SEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
319815f2bd95SEwan Crawford };
319915f2bd95SEwan Crawford 
320055232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationLoad : public CommandObjectParsed
320155232f09SEwan Crawford {
320255232f09SEwan Crawford public:
320355232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationLoad(CommandInterpreter &interpreter)
320455232f09SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation load",
320555232f09SEwan Crawford                               "Loads renderscript allocation contents from a file.", "renderscript allocation load <ID> <filename>",
320655232f09SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
320755232f09SEwan Crawford     {
320855232f09SEwan Crawford     }
320955232f09SEwan Crawford 
3210222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
321155232f09SEwan Crawford 
321255232f09SEwan Crawford     bool
3213222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
321455232f09SEwan Crawford     {
321555232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
321655232f09SEwan Crawford         if (argc != 2)
321755232f09SEwan Crawford         {
321855232f09SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str());
321955232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
322055232f09SEwan Crawford             return false;
322155232f09SEwan Crawford         }
322255232f09SEwan Crawford 
322355232f09SEwan Crawford         RenderScriptRuntime *runtime =
322455232f09SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
322555232f09SEwan Crawford 
322655232f09SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
322755232f09SEwan Crawford         bool convert_complete = false;
322855232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
322955232f09SEwan Crawford         if (!convert_complete)
323055232f09SEwan Crawford         {
323155232f09SEwan Crawford             result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr);
323255232f09SEwan Crawford             result.SetStatus (eReturnStatusFailed);
323355232f09SEwan Crawford             return false;
323455232f09SEwan Crawford         }
323555232f09SEwan Crawford 
323655232f09SEwan Crawford         const char* filename = command.GetArgumentAtIndex(1);
323755232f09SEwan Crawford         bool success = runtime->LoadAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
323855232f09SEwan Crawford 
323955232f09SEwan Crawford         if (success)
324055232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
324155232f09SEwan Crawford         else
324255232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
324355232f09SEwan Crawford 
324455232f09SEwan Crawford         return true;
324555232f09SEwan Crawford     }
324655232f09SEwan Crawford };
324755232f09SEwan Crawford 
324855232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationSave : public CommandObjectParsed
324955232f09SEwan Crawford {
325055232f09SEwan Crawford public:
325155232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationSave(CommandInterpreter &interpreter)
325255232f09SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation save",
325355232f09SEwan Crawford                               "Write renderscript allocation contents to a file.", "renderscript allocation save <ID> <filename>",
325455232f09SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
325555232f09SEwan Crawford     {
325655232f09SEwan Crawford     }
325755232f09SEwan Crawford 
3258222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
325955232f09SEwan Crawford 
326055232f09SEwan Crawford     bool
3261222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
326255232f09SEwan Crawford     {
326355232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
326455232f09SEwan Crawford         if (argc != 2)
326555232f09SEwan Crawford         {
326655232f09SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str());
326755232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
326855232f09SEwan Crawford             return false;
326955232f09SEwan Crawford         }
327055232f09SEwan Crawford 
327155232f09SEwan Crawford         RenderScriptRuntime *runtime =
327255232f09SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
327355232f09SEwan Crawford 
327455232f09SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
327555232f09SEwan Crawford         bool convert_complete = false;
327655232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
327755232f09SEwan Crawford         if (!convert_complete)
327855232f09SEwan Crawford         {
327955232f09SEwan Crawford             result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr);
328055232f09SEwan Crawford             result.SetStatus (eReturnStatusFailed);
328155232f09SEwan Crawford             return false;
328255232f09SEwan Crawford         }
328355232f09SEwan Crawford 
328455232f09SEwan Crawford         const char* filename = command.GetArgumentAtIndex(1);
328555232f09SEwan Crawford         bool success = runtime->SaveAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
328655232f09SEwan Crawford 
328755232f09SEwan Crawford         if (success)
328855232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
328955232f09SEwan Crawford         else
329055232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
329155232f09SEwan Crawford 
329255232f09SEwan Crawford         return true;
329355232f09SEwan Crawford     }
329455232f09SEwan Crawford };
329555232f09SEwan Crawford 
329615f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocation : public CommandObjectMultiword
329715f2bd95SEwan Crawford {
329815f2bd95SEwan Crawford public:
329915f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
330015f2bd95SEwan Crawford         : CommandObjectMultiword(interpreter, "renderscript allocation", "Commands that deal with renderscript allocations.",
330115f2bd95SEwan Crawford                                  NULL)
330215f2bd95SEwan Crawford     {
330315f2bd95SEwan Crawford         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
3304a0f08674SEwan Crawford         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
330555232f09SEwan Crawford         LoadSubCommand("save", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
330655232f09SEwan Crawford         LoadSubCommand("load", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
330715f2bd95SEwan Crawford     }
330815f2bd95SEwan Crawford 
3309222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocation() override = default;
331015f2bd95SEwan Crawford };
331115f2bd95SEwan Crawford 
33124640cde1SColin Riley class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed
33134640cde1SColin Riley {
33144640cde1SColin Riley public:
33154640cde1SColin Riley     CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
33164640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript status",
33174640cde1SColin Riley                               "Displays current renderscript runtime status.", "renderscript status",
33184640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
33194640cde1SColin Riley     {
33204640cde1SColin Riley     }
33214640cde1SColin Riley 
3322222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeStatus() override = default;
33234640cde1SColin Riley 
33244640cde1SColin Riley     bool
3325222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
33264640cde1SColin Riley     {
33274640cde1SColin Riley         RenderScriptRuntime *runtime =
33284640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
33294640cde1SColin Riley         runtime->Status(result.GetOutputStream());
33304640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
33314640cde1SColin Riley         return true;
33324640cde1SColin Riley     }
33334640cde1SColin Riley };
33344640cde1SColin Riley 
33355ec532a9SColin Riley class CommandObjectRenderScriptRuntime : public CommandObjectMultiword
33365ec532a9SColin Riley {
33375ec532a9SColin Riley public:
33385ec532a9SColin Riley     CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
33395ec532a9SColin Riley         : CommandObjectMultiword(interpreter, "renderscript", "A set of commands for operating on renderscript.",
33405ec532a9SColin Riley                                  "renderscript <subcommand> [<subcommand-options>]")
33415ec532a9SColin Riley     {
33425ec532a9SColin Riley         LoadSubCommand("module", CommandObjectSP(new CommandObjectRenderScriptRuntimeModule(interpreter)));
33434640cde1SColin Riley         LoadSubCommand("status", CommandObjectSP(new CommandObjectRenderScriptRuntimeStatus(interpreter)));
33444640cde1SColin Riley         LoadSubCommand("kernel", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernel(interpreter)));
33454640cde1SColin Riley         LoadSubCommand("context", CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(interpreter)));
334615f2bd95SEwan Crawford         LoadSubCommand("allocation", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
33475ec532a9SColin Riley     }
33485ec532a9SColin Riley 
3349222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntime() override = default;
33505ec532a9SColin Riley };
3351ef20b08fSColin Riley 
3352ef20b08fSColin Riley void
3353ef20b08fSColin Riley RenderScriptRuntime::Initiate()
33545ec532a9SColin Riley {
3355ef20b08fSColin Riley     assert(!m_initiated);
33565ec532a9SColin Riley }
3357ef20b08fSColin Riley 
3358ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
33597dc7771cSEwan Crawford     : lldb_private::CPPLanguageRuntime(process), m_initiated(false), m_debuggerPresentFlagged(false),
33607dc7771cSEwan Crawford       m_breakAllKernels(false)
3361ef20b08fSColin Riley {
33624640cde1SColin Riley     ModulesDidLoad(process->GetTarget().GetImages());
3363ef20b08fSColin Riley }
33644640cde1SColin Riley 
33654640cde1SColin Riley lldb::CommandObjectSP
33664640cde1SColin Riley RenderScriptRuntime::GetCommandObject(lldb_private::CommandInterpreter& interpreter)
33674640cde1SColin Riley {
33684640cde1SColin Riley     static CommandObjectSP command_object;
33694640cde1SColin Riley     if(!command_object)
33704640cde1SColin Riley     {
33714640cde1SColin Riley         command_object.reset(new CommandObjectRenderScriptRuntime(interpreter));
33724640cde1SColin Riley     }
33734640cde1SColin Riley     return command_object;
33744640cde1SColin Riley }
33754640cde1SColin Riley 
337678f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
3377