15ec532a9SColin Riley //===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===//
25ec532a9SColin Riley //
35ec532a9SColin Riley //                     The LLVM Compiler Infrastructure
45ec532a9SColin Riley //
55ec532a9SColin Riley // This file is distributed under the University of Illinois Open Source
65ec532a9SColin Riley // License. See LICENSE.TXT for details.
75ec532a9SColin Riley //
85ec532a9SColin Riley //===----------------------------------------------------------------------===//
95ec532a9SColin Riley 
10222b937cSEugene Zelenko // C Includes
11222b937cSEugene Zelenko // C++ Includes
12222b937cSEugene Zelenko // Other libraries and framework includes
13222b937cSEugene Zelenko // Project includes
145ec532a9SColin Riley #include "RenderScriptRuntime.h"
155ec532a9SColin Riley 
165ec532a9SColin Riley #include "lldb/Core/ConstString.h"
175ec532a9SColin Riley #include "lldb/Core/Debugger.h"
185ec532a9SColin Riley #include "lldb/Core/Error.h"
195ec532a9SColin Riley #include "lldb/Core/Log.h"
205ec532a9SColin Riley #include "lldb/Core/PluginManager.h"
218b244e21SEwan Crawford #include "lldb/Core/ValueObjectVariable.h"
22018f5a7eSEwan Crawford #include "lldb/Core/RegularExpression.h"
238b244e21SEwan Crawford #include "lldb/DataFormatters/DumpValueObjectOptions.h"
24a0f08674SEwan Crawford #include "lldb/Host/StringConvert.h"
255ec532a9SColin Riley #include "lldb/Symbol/Symbol.h"
264640cde1SColin Riley #include "lldb/Symbol/Type.h"
275ec532a9SColin Riley #include "lldb/Target/Process.h"
285ec532a9SColin Riley #include "lldb/Target/Target.h"
29018f5a7eSEwan Crawford #include "lldb/Target/Thread.h"
305ec532a9SColin Riley #include "lldb/Interpreter/Args.h"
315ec532a9SColin Riley #include "lldb/Interpreter/Options.h"
325ec532a9SColin Riley #include "lldb/Interpreter/CommandInterpreter.h"
335ec532a9SColin Riley #include "lldb/Interpreter/CommandReturnObject.h"
345ec532a9SColin Riley #include "lldb/Interpreter/CommandObjectMultiword.h"
354640cde1SColin Riley #include "lldb/Breakpoint/StoppointCallbackContext.h"
364640cde1SColin Riley #include "lldb/Target/RegisterContext.h"
3715f2bd95SEwan Crawford #include "lldb/Expression/UserExpression.h"
384640cde1SColin Riley #include "lldb/Symbol/VariableList.h"
395ec532a9SColin Riley 
405ec532a9SColin Riley using namespace lldb;
415ec532a9SColin Riley using namespace lldb_private;
4298156583SEwan Crawford using namespace lldb_renderscript;
435ec532a9SColin Riley 
4478f339d1SEwan Crawford namespace {
4578f339d1SEwan Crawford 
4678f339d1SEwan Crawford // The empirical_type adds a basic level of validation to arbitrary data
4778f339d1SEwan Crawford // allowing us to track if data has been discovered and stored or not.
4878f339d1SEwan Crawford // An empirical_type will be marked as valid only if it has been explicitly assigned to.
4978f339d1SEwan Crawford template <typename type_t>
5078f339d1SEwan Crawford class empirical_type
5178f339d1SEwan Crawford {
5278f339d1SEwan Crawford public:
5378f339d1SEwan Crawford     // Ctor. Contents is invalid when constructed.
5478f339d1SEwan Crawford     empirical_type()
5578f339d1SEwan Crawford         : valid(false)
5678f339d1SEwan Crawford     {}
5778f339d1SEwan Crawford 
5878f339d1SEwan Crawford     // Return true and copy contents to out if valid, else return false.
5978f339d1SEwan Crawford     bool get(type_t& out) const
6078f339d1SEwan Crawford     {
6178f339d1SEwan Crawford         if (valid)
6278f339d1SEwan Crawford             out = data;
6378f339d1SEwan Crawford         return valid;
6478f339d1SEwan Crawford     }
6578f339d1SEwan Crawford 
6678f339d1SEwan Crawford     // Return a pointer to the contents or nullptr if it was not valid.
6778f339d1SEwan Crawford     const type_t* get() const
6878f339d1SEwan Crawford     {
6978f339d1SEwan Crawford         return valid ? &data : nullptr;
7078f339d1SEwan Crawford     }
7178f339d1SEwan Crawford 
7278f339d1SEwan Crawford     // Assign data explicitly.
7378f339d1SEwan Crawford     void set(const type_t in)
7478f339d1SEwan Crawford     {
7578f339d1SEwan Crawford         data = in;
7678f339d1SEwan Crawford         valid = true;
7778f339d1SEwan Crawford     }
7878f339d1SEwan Crawford 
7978f339d1SEwan Crawford     // Mark contents as invalid.
8078f339d1SEwan Crawford     void invalidate()
8178f339d1SEwan Crawford     {
8278f339d1SEwan Crawford         valid = false;
8378f339d1SEwan Crawford     }
8478f339d1SEwan Crawford 
8578f339d1SEwan Crawford     // Returns true if this type contains valid data.
8678f339d1SEwan Crawford     bool isValid() const
8778f339d1SEwan Crawford     {
8878f339d1SEwan Crawford         return valid;
8978f339d1SEwan Crawford     }
9078f339d1SEwan Crawford 
9178f339d1SEwan Crawford     // Assignment operator.
9278f339d1SEwan Crawford     empirical_type<type_t>& operator = (const type_t in)
9378f339d1SEwan Crawford     {
9478f339d1SEwan Crawford         set(in);
9578f339d1SEwan Crawford         return *this;
9678f339d1SEwan Crawford     }
9778f339d1SEwan Crawford 
9878f339d1SEwan Crawford     // Dereference operator returns contents.
9978f339d1SEwan Crawford     // Warning: Will assert if not valid so use only when you know data is valid.
10078f339d1SEwan Crawford     const type_t& operator * () const
10178f339d1SEwan Crawford     {
10278f339d1SEwan Crawford         assert(valid);
10378f339d1SEwan Crawford         return data;
10478f339d1SEwan Crawford     }
10578f339d1SEwan Crawford 
10678f339d1SEwan Crawford protected:
10778f339d1SEwan Crawford     bool valid;
10878f339d1SEwan Crawford     type_t data;
10978f339d1SEwan Crawford };
11078f339d1SEwan Crawford 
111222b937cSEugene Zelenko } // anonymous namespace
11278f339d1SEwan Crawford 
11378f339d1SEwan Crawford // The ScriptDetails class collects data associated with a single script instance.
11478f339d1SEwan Crawford struct RenderScriptRuntime::ScriptDetails
11578f339d1SEwan Crawford {
116222b937cSEugene Zelenko     ~ScriptDetails() = default;
11778f339d1SEwan Crawford 
11878f339d1SEwan Crawford     enum ScriptType
11978f339d1SEwan Crawford     {
12078f339d1SEwan Crawford         eScript,
12178f339d1SEwan Crawford         eScriptC
12278f339d1SEwan Crawford     };
12378f339d1SEwan Crawford 
12478f339d1SEwan Crawford     // The derived type of the script.
12578f339d1SEwan Crawford     empirical_type<ScriptType> type;
12678f339d1SEwan Crawford     // The name of the original source file.
12778f339d1SEwan Crawford     empirical_type<std::string> resName;
12878f339d1SEwan Crawford     // Path to script .so file on the device.
12978f339d1SEwan Crawford     empirical_type<std::string> scriptDyLib;
13078f339d1SEwan Crawford     // Directory where kernel objects are cached on device.
13178f339d1SEwan Crawford     empirical_type<std::string> cacheDir;
13278f339d1SEwan Crawford     // Pointer to the context which owns this script.
13378f339d1SEwan Crawford     empirical_type<lldb::addr_t> context;
13478f339d1SEwan Crawford     // Pointer to the script object itself.
13578f339d1SEwan Crawford     empirical_type<lldb::addr_t> script;
13678f339d1SEwan Crawford };
13778f339d1SEwan Crawford 
1388b244e21SEwan Crawford // This Element class represents the Element object in RS,
1398b244e21SEwan Crawford // defining the type associated with an Allocation.
1408b244e21SEwan Crawford struct RenderScriptRuntime::Element
14178f339d1SEwan Crawford {
14215f2bd95SEwan Crawford     // Taken from rsDefines.h
14315f2bd95SEwan Crawford     enum DataKind
14415f2bd95SEwan Crawford     {
14515f2bd95SEwan Crawford         RS_KIND_USER,
14615f2bd95SEwan Crawford         RS_KIND_PIXEL_L = 7,
14715f2bd95SEwan Crawford         RS_KIND_PIXEL_A,
14815f2bd95SEwan Crawford         RS_KIND_PIXEL_LA,
14915f2bd95SEwan Crawford         RS_KIND_PIXEL_RGB,
15015f2bd95SEwan Crawford         RS_KIND_PIXEL_RGBA,
15115f2bd95SEwan Crawford         RS_KIND_PIXEL_DEPTH,
15215f2bd95SEwan Crawford         RS_KIND_PIXEL_YUV,
15315f2bd95SEwan Crawford         RS_KIND_INVALID = 100
15415f2bd95SEwan Crawford     };
15578f339d1SEwan Crawford 
15615f2bd95SEwan Crawford     // Taken from rsDefines.h
15778f339d1SEwan Crawford     enum DataType
15878f339d1SEwan Crawford     {
15915f2bd95SEwan Crawford         RS_TYPE_NONE = 0,
16015f2bd95SEwan Crawford         RS_TYPE_FLOAT_16,
16115f2bd95SEwan Crawford         RS_TYPE_FLOAT_32,
16215f2bd95SEwan Crawford         RS_TYPE_FLOAT_64,
16315f2bd95SEwan Crawford         RS_TYPE_SIGNED_8,
16415f2bd95SEwan Crawford         RS_TYPE_SIGNED_16,
16515f2bd95SEwan Crawford         RS_TYPE_SIGNED_32,
16615f2bd95SEwan Crawford         RS_TYPE_SIGNED_64,
16715f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_8,
16815f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_16,
16915f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_32,
17015f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_64,
1712e920715SEwan Crawford         RS_TYPE_BOOLEAN,
1722e920715SEwan Crawford 
1732e920715SEwan Crawford         RS_TYPE_UNSIGNED_5_6_5,
1742e920715SEwan Crawford         RS_TYPE_UNSIGNED_5_5_5_1,
1752e920715SEwan Crawford         RS_TYPE_UNSIGNED_4_4_4_4,
1762e920715SEwan Crawford 
1772e920715SEwan Crawford         RS_TYPE_MATRIX_4X4,
1782e920715SEwan Crawford         RS_TYPE_MATRIX_3X3,
1792e920715SEwan Crawford         RS_TYPE_MATRIX_2X2,
1802e920715SEwan Crawford 
1812e920715SEwan Crawford         RS_TYPE_ELEMENT = 1000,
1822e920715SEwan Crawford         RS_TYPE_TYPE,
1832e920715SEwan Crawford         RS_TYPE_ALLOCATION,
1842e920715SEwan Crawford         RS_TYPE_SAMPLER,
1852e920715SEwan Crawford         RS_TYPE_SCRIPT,
1862e920715SEwan Crawford         RS_TYPE_MESH,
1872e920715SEwan Crawford         RS_TYPE_PROGRAM_FRAGMENT,
1882e920715SEwan Crawford         RS_TYPE_PROGRAM_VERTEX,
1892e920715SEwan Crawford         RS_TYPE_PROGRAM_RASTER,
1902e920715SEwan Crawford         RS_TYPE_PROGRAM_STORE,
1912e920715SEwan Crawford         RS_TYPE_FONT,
1922e920715SEwan Crawford 
1932e920715SEwan Crawford         RS_TYPE_INVALID = 10000
19478f339d1SEwan Crawford     };
19578f339d1SEwan Crawford 
1968b244e21SEwan Crawford     std::vector<Element> children;                       // Child Element fields for structs
1978b244e21SEwan Crawford     empirical_type<lldb::addr_t> element_ptr;            // Pointer to the RS Element of the Type
1988b244e21SEwan Crawford     empirical_type<DataType> type;                       // Type of each data pointer stored by the allocation
1998b244e21SEwan Crawford     empirical_type<DataKind> type_kind;                  // Defines pixel type if Allocation is created from an image
2008b244e21SEwan Crawford     empirical_type<uint32_t> type_vec_size;              // Vector size of each data point, e.g '4' for uchar4
2018b244e21SEwan Crawford     empirical_type<uint32_t> field_count;                // Number of Subelements
2028b244e21SEwan Crawford     empirical_type<uint32_t> datum_size;                 // Size of a single Element with padding
2038b244e21SEwan Crawford     empirical_type<uint32_t> padding;                    // Number of padding bytes
2048b244e21SEwan Crawford     empirical_type<uint32_t> array_size;                 // Number of items in array, only needed for strucrs
2058b244e21SEwan Crawford     ConstString type_name;                               // Name of type, only needed for structs
2068b244e21SEwan Crawford 
207fe06b5adSAdrian McCarthy     static const ConstString &GetFallbackStructName();   // Print this as the type name of a struct Element
2088b244e21SEwan Crawford                                                          // If we can't resolve the actual struct name
2098b59062aSEwan Crawford 
2108b59062aSEwan Crawford     bool shouldRefresh() const
2118b59062aSEwan Crawford     {
2128b59062aSEwan Crawford         const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
2138b59062aSEwan Crawford         const bool valid_type = type.isValid() && type_vec_size.isValid() && type_kind.isValid();
2148b59062aSEwan Crawford         return !valid_ptr || !valid_type || !datum_size.isValid();
2158b59062aSEwan Crawford     }
2168b244e21SEwan Crawford };
2178b244e21SEwan Crawford 
2188b244e21SEwan Crawford // This AllocationDetails class collects data associated with a single
2198b244e21SEwan Crawford // allocation instance.
2208b244e21SEwan Crawford struct RenderScriptRuntime::AllocationDetails
2218b244e21SEwan Crawford {
22215f2bd95SEwan Crawford     struct Dimension
22378f339d1SEwan Crawford     {
22415f2bd95SEwan Crawford         uint32_t dim_1;
22515f2bd95SEwan Crawford         uint32_t dim_2;
22615f2bd95SEwan Crawford         uint32_t dim_3;
22715f2bd95SEwan Crawford         uint32_t cubeMap;
22815f2bd95SEwan Crawford 
22915f2bd95SEwan Crawford         Dimension()
23015f2bd95SEwan Crawford         {
23115f2bd95SEwan Crawford              dim_1 = 0;
23215f2bd95SEwan Crawford              dim_2 = 0;
23315f2bd95SEwan Crawford              dim_3 = 0;
23415f2bd95SEwan Crawford              cubeMap = 0;
23515f2bd95SEwan Crawford         }
23678f339d1SEwan Crawford     };
23778f339d1SEwan Crawford 
23826e52a70SEwan Crawford     // The FileHeader struct specifies the header we use for writing allocations to a binary file.
23926e52a70SEwan Crawford     // Our format begins with the ASCII characters "RSAD", identifying the file as an allocation dump.
24026e52a70SEwan Crawford     // Member variables dims and hdr_size are then written consecutively, immediately followed by an instance of
24126e52a70SEwan Crawford     // the ElementHeader struct. Because Elements can contain subelements, there may be more than one instance
24226e52a70SEwan Crawford     // of the ElementHeader struct. With this first instance being the root element, and the other instances being
24326e52a70SEwan Crawford     // the root's descendants. To identify which instances are an ElementHeader's children, each struct
24426e52a70SEwan Crawford     // is immediately followed by a sequence of consecutive offsets to the start of its child structs.
24526e52a70SEwan Crawford     // These offsets are 4 bytes in size, and the 0 offset signifies no more children.
24655232f09SEwan Crawford     struct FileHeader
24755232f09SEwan Crawford     {
24855232f09SEwan Crawford         uint8_t ident[4];      // ASCII 'RSAD' identifying the file
24926e52a70SEwan Crawford         uint32_t dims[3];      // Dimensions
25026e52a70SEwan Crawford         uint16_t hdr_size;     // Header size in bytes, including all element headers
25126e52a70SEwan Crawford     };
25226e52a70SEwan Crawford 
25326e52a70SEwan Crawford     struct ElementHeader
25426e52a70SEwan Crawford     {
25555232f09SEwan Crawford         uint16_t type;          // DataType enum
25655232f09SEwan Crawford         uint32_t kind;          // DataKind enum
25755232f09SEwan Crawford         uint32_t element_size;  // Size of a single element, including padding
25826e52a70SEwan Crawford         uint16_t vector_size;   // Vector width
25926e52a70SEwan Crawford         uint32_t array_size;    // Number of elements in array
26055232f09SEwan Crawford     };
26155232f09SEwan Crawford 
26215f2bd95SEwan Crawford     // Monotonically increasing from 1
26315f2bd95SEwan Crawford     static unsigned int ID;
26415f2bd95SEwan Crawford 
26515f2bd95SEwan Crawford     // Maps Allocation DataType enum and vector size to printable strings
26615f2bd95SEwan Crawford     // using mapping from RenderScript numerical types summary documentation
26715f2bd95SEwan Crawford     static const char* RsDataTypeToString[][4];
26815f2bd95SEwan Crawford 
26915f2bd95SEwan Crawford     // Maps Allocation DataKind enum to printable strings
27015f2bd95SEwan Crawford     static const char* RsDataKindToString[];
27115f2bd95SEwan Crawford 
272a0f08674SEwan Crawford     // Maps allocation types to format sizes for printing.
273a0f08674SEwan Crawford     static const unsigned int RSTypeToFormat[][3];
274a0f08674SEwan Crawford 
27515f2bd95SEwan Crawford     // Give each allocation an ID as a way
27615f2bd95SEwan Crawford     // for commands to reference it.
27715f2bd95SEwan Crawford     const unsigned int id;
27815f2bd95SEwan Crawford 
2798b244e21SEwan Crawford     RenderScriptRuntime::Element element;     // Allocation Element type
28015f2bd95SEwan Crawford     empirical_type<Dimension> dimension;      // Dimensions of the Allocation
28115f2bd95SEwan Crawford     empirical_type<lldb::addr_t> address;     // Pointer to address of the RS Allocation
28215f2bd95SEwan Crawford     empirical_type<lldb::addr_t> data_ptr;    // Pointer to the data held by the Allocation
28315f2bd95SEwan Crawford     empirical_type<lldb::addr_t> type_ptr;    // Pointer to the RS Type of the Allocation
28415f2bd95SEwan Crawford     empirical_type<lldb::addr_t> context;     // Pointer to the RS Context of the Allocation
285a0f08674SEwan Crawford     empirical_type<uint32_t> size;            // Size of the allocation
286a0f08674SEwan Crawford     empirical_type<uint32_t> stride;          // Stride between rows of the allocation
28715f2bd95SEwan Crawford 
28815f2bd95SEwan Crawford     // Give each allocation an id, so we can reference it in user commands.
28915f2bd95SEwan Crawford     AllocationDetails(): id(ID++)
29015f2bd95SEwan Crawford     {
29115f2bd95SEwan Crawford     }
2928b59062aSEwan Crawford 
2938b59062aSEwan Crawford     bool shouldRefresh() const
2948b59062aSEwan Crawford     {
2958b59062aSEwan Crawford         bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
2968b59062aSEwan Crawford         valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
2978b59062aSEwan Crawford         return !valid_ptrs || !dimension.isValid() || !size.isValid() || element.shouldRefresh();
2988b59062aSEwan Crawford     }
29915f2bd95SEwan Crawford };
30015f2bd95SEwan Crawford 
301fe06b5adSAdrian McCarthy const ConstString &
302fe06b5adSAdrian McCarthy RenderScriptRuntime::Element::GetFallbackStructName()
303fe06b5adSAdrian McCarthy {
304fe06b5adSAdrian McCarthy     static const ConstString FallbackStructName("struct");
305fe06b5adSAdrian McCarthy     return FallbackStructName;
306fe06b5adSAdrian McCarthy }
3078b244e21SEwan Crawford 
30815f2bd95SEwan Crawford unsigned int RenderScriptRuntime::AllocationDetails::ID = 1;
30915f2bd95SEwan Crawford 
31015f2bd95SEwan Crawford const char* RenderScriptRuntime::AllocationDetails::RsDataKindToString[] =
31115f2bd95SEwan Crawford {
31215f2bd95SEwan Crawford    "User",
31315f2bd95SEwan Crawford    "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7
31415f2bd95SEwan Crawford    "Undefined", "Undefined", "Undefined",
31515f2bd95SEwan Crawford    "L Pixel",
31615f2bd95SEwan Crawford    "A Pixel",
31715f2bd95SEwan Crawford    "LA Pixel",
31815f2bd95SEwan Crawford    "RGB Pixel",
31915f2bd95SEwan Crawford    "RGBA Pixel",
32015f2bd95SEwan Crawford    "Pixel Depth",
32115f2bd95SEwan Crawford    "YUV Pixel"
32215f2bd95SEwan Crawford };
32315f2bd95SEwan Crawford 
32415f2bd95SEwan Crawford const char* RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] =
32515f2bd95SEwan Crawford {
32615f2bd95SEwan Crawford     {"None", "None", "None", "None"},
32715f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
32815f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
32915f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
33015f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
33115f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
33215f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
33315f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
33415f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
33515f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
33615f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
33715f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
3382e920715SEwan Crawford     {"bool", "bool2", "bool3", "bool4"},
3392e920715SEwan Crawford     {"packed_565", "packed_565", "packed_565", "packed_565"},
3402e920715SEwan Crawford     {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
3412e920715SEwan Crawford     {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
3422e920715SEwan Crawford     {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
3432e920715SEwan Crawford     {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
3442e920715SEwan Crawford     {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
3452e920715SEwan Crawford 
3462e920715SEwan Crawford     // Handlers
3472e920715SEwan Crawford     {"RS Element", "RS Element", "RS Element", "RS Element"},
3482e920715SEwan Crawford     {"RS Type", "RS Type", "RS Type", "RS Type"},
3492e920715SEwan Crawford     {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
3502e920715SEwan Crawford     {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
3512e920715SEwan Crawford     {"RS Script", "RS Script", "RS Script", "RS Script"},
3522e920715SEwan Crawford 
3532e920715SEwan Crawford     // Deprecated
3542e920715SEwan Crawford     {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
3552e920715SEwan Crawford     {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment", "RS Program Fragment"},
3562e920715SEwan Crawford     {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex", "RS Program Vertex"},
3572e920715SEwan Crawford     {"RS Program Raster", "RS Program Raster", "RS Program Raster", "RS Program Raster"},
3582e920715SEwan Crawford     {"RS Program Store", "RS Program Store", "RS Program Store", "RS Program Store"},
3592e920715SEwan Crawford     {"RS Font", "RS Font", "RS Font", "RS Font"}
36078f339d1SEwan Crawford };
36178f339d1SEwan Crawford 
362a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
363a0f08674SEwan Crawford enum TypeToFormatIndex {
364a0f08674SEwan Crawford    eFormatSingle = 0,
365a0f08674SEwan Crawford    eFormatVector,
366a0f08674SEwan Crawford    eElementSize
367a0f08674SEwan Crawford };
368a0f08674SEwan Crawford 
369a0f08674SEwan Crawford // { format enum of single element, format enum of element vector, size of element}
370a0f08674SEwan Crawford const unsigned int RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] =
371a0f08674SEwan Crawford {
372a0f08674SEwan Crawford     {eFormatHex, eFormatHex, 1}, // RS_TYPE_NONE
373a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat16, 2}, // RS_TYPE_FLOAT_16
374a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)}, // RS_TYPE_FLOAT_32
375a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)}, // RS_TYPE_FLOAT_64
376a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)}, // RS_TYPE_SIGNED_8
377a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)}, // RS_TYPE_SIGNED_16
378a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)}, // RS_TYPE_SIGNED_32
379a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)}, // RS_TYPE_SIGNED_64
380a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)}, // RS_TYPE_UNSIGNED_8
381a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_16
382a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)}, // RS_TYPE_UNSIGNED_32
383a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)}, // RS_TYPE_UNSIGNED_64
3842e920715SEwan Crawford     {eFormatBoolean, eFormatBoolean, 1}, // RS_TYPE_BOOL
3852e920715SEwan Crawford     {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_5_6_5
3862e920715SEwan Crawford     {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_5_5_5_1
3872e920715SEwan Crawford     {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_4_4_4_4
3882e920715SEwan Crawford     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16}, // RS_TYPE_MATRIX_4X4
3892e920715SEwan Crawford     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9}, // RS_TYPE_MATRIX_3X3
3902e920715SEwan Crawford     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4} // RS_TYPE_MATRIX_2X2
391a0f08674SEwan Crawford };
392a0f08674SEwan Crawford 
3935ec532a9SColin Riley //------------------------------------------------------------------
3945ec532a9SColin Riley // Static Functions
3955ec532a9SColin Riley //------------------------------------------------------------------
3965ec532a9SColin Riley LanguageRuntime *
3975ec532a9SColin Riley RenderScriptRuntime::CreateInstance(Process *process, lldb::LanguageType language)
3985ec532a9SColin Riley {
3995ec532a9SColin Riley 
4005ec532a9SColin Riley     if (language == eLanguageTypeExtRenderScript)
4015ec532a9SColin Riley         return new RenderScriptRuntime(process);
4025ec532a9SColin Riley     else
4035ec532a9SColin Riley         return NULL;
4045ec532a9SColin Riley }
4055ec532a9SColin Riley 
40698156583SEwan Crawford // Callback with a module to search for matching symbols.
40798156583SEwan Crawford // We first check that the module contains RS kernels.
40898156583SEwan Crawford // Then look for a symbol which matches our kernel name.
40998156583SEwan Crawford // The breakpoint address is finally set using the address of this symbol.
41098156583SEwan Crawford Searcher::CallbackReturn
41198156583SEwan Crawford RSBreakpointResolver::SearchCallback(SearchFilter &filter,
41298156583SEwan Crawford                                      SymbolContext &context,
41398156583SEwan Crawford                                      Address*,
41498156583SEwan Crawford                                      bool)
41598156583SEwan Crawford {
41698156583SEwan Crawford     ModuleSP module = context.module_sp;
41798156583SEwan Crawford 
41898156583SEwan Crawford     if (!module)
41998156583SEwan Crawford         return Searcher::eCallbackReturnContinue;
42098156583SEwan Crawford 
42198156583SEwan Crawford     // Is this a module containing renderscript kernels?
42298156583SEwan Crawford     if (nullptr == module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData))
42398156583SEwan Crawford         return Searcher::eCallbackReturnContinue;
42498156583SEwan Crawford 
42598156583SEwan Crawford     // Attempt to set a breakpoint on the kernel name symbol within the module library.
42698156583SEwan Crawford     // If it's not found, it's likely debug info is unavailable - try to set a
42798156583SEwan Crawford     // breakpoint on <name>.expand.
42898156583SEwan Crawford 
42998156583SEwan Crawford     const Symbol* kernel_sym = module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
43098156583SEwan Crawford     if (!kernel_sym)
43198156583SEwan Crawford     {
43298156583SEwan Crawford         std::string kernel_name_expanded(m_kernel_name.AsCString());
43398156583SEwan Crawford         kernel_name_expanded.append(".expand");
43498156583SEwan Crawford         kernel_sym = module->FindFirstSymbolWithNameAndType(ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
43598156583SEwan Crawford     }
43698156583SEwan Crawford 
43798156583SEwan Crawford     if (kernel_sym)
43898156583SEwan Crawford     {
43998156583SEwan Crawford         Address bp_addr = kernel_sym->GetAddress();
44098156583SEwan Crawford         if (filter.AddressPasses(bp_addr))
44198156583SEwan Crawford             m_breakpoint->AddLocation(bp_addr);
44298156583SEwan Crawford     }
44398156583SEwan Crawford 
44498156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
44598156583SEwan Crawford }
44698156583SEwan Crawford 
4475ec532a9SColin Riley void
4485ec532a9SColin Riley RenderScriptRuntime::Initialize()
4495ec532a9SColin Riley {
4504640cde1SColin Riley     PluginManager::RegisterPlugin(GetPluginNameStatic(), "RenderScript language support", CreateInstance, GetCommandObject);
4515ec532a9SColin Riley }
4525ec532a9SColin Riley 
4535ec532a9SColin Riley void
4545ec532a9SColin Riley RenderScriptRuntime::Terminate()
4555ec532a9SColin Riley {
4565ec532a9SColin Riley     PluginManager::UnregisterPlugin(CreateInstance);
4575ec532a9SColin Riley }
4585ec532a9SColin Riley 
4595ec532a9SColin Riley lldb_private::ConstString
4605ec532a9SColin Riley RenderScriptRuntime::GetPluginNameStatic()
4615ec532a9SColin Riley {
4625ec532a9SColin Riley     static ConstString g_name("renderscript");
4635ec532a9SColin Riley     return g_name;
4645ec532a9SColin Riley }
4655ec532a9SColin Riley 
466ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
467ef20b08fSColin Riley RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp)
468ef20b08fSColin Riley {
469ef20b08fSColin Riley     if (module_sp)
470ef20b08fSColin Riley     {
471ef20b08fSColin Riley         // Is this a module containing renderscript kernels?
472ef20b08fSColin Riley         const Symbol *info_sym = module_sp->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
473ef20b08fSColin Riley         if (info_sym)
474ef20b08fSColin Riley         {
475ef20b08fSColin Riley             return eModuleKindKernelObj;
476ef20b08fSColin Riley         }
4774640cde1SColin Riley 
4784640cde1SColin Riley         // Is this the main RS runtime library
4794640cde1SColin Riley         const ConstString rs_lib("libRS.so");
4804640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_lib)
4814640cde1SColin Riley         {
4824640cde1SColin Riley             return eModuleKindLibRS;
4834640cde1SColin Riley         }
4844640cde1SColin Riley 
4854640cde1SColin Riley         const ConstString rs_driverlib("libRSDriver.so");
4864640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_driverlib)
4874640cde1SColin Riley         {
4884640cde1SColin Riley             return eModuleKindDriver;
4894640cde1SColin Riley         }
4904640cde1SColin Riley 
49115f2bd95SEwan Crawford         const ConstString rs_cpureflib("libRSCpuRef.so");
4924640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib)
4934640cde1SColin Riley         {
4944640cde1SColin Riley             return eModuleKindImpl;
4954640cde1SColin Riley         }
4964640cde1SColin Riley 
497ef20b08fSColin Riley     }
498ef20b08fSColin Riley     return eModuleKindIgnored;
499ef20b08fSColin Riley }
500ef20b08fSColin Riley 
501ef20b08fSColin Riley bool
502ef20b08fSColin Riley RenderScriptRuntime::IsRenderScriptModule(const lldb::ModuleSP &module_sp)
503ef20b08fSColin Riley {
504ef20b08fSColin Riley     return GetModuleKind(module_sp) != eModuleKindIgnored;
505ef20b08fSColin Riley }
506ef20b08fSColin Riley 
507ef20b08fSColin Riley void
508ef20b08fSColin Riley RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list )
509ef20b08fSColin Riley {
510ef20b08fSColin Riley     Mutex::Locker locker (module_list.GetMutex ());
511ef20b08fSColin Riley 
512ef20b08fSColin Riley     size_t num_modules = module_list.GetSize();
513ef20b08fSColin Riley     for (size_t i = 0; i < num_modules; i++)
514ef20b08fSColin Riley     {
515ef20b08fSColin Riley         auto mod = module_list.GetModuleAtIndex (i);
516ef20b08fSColin Riley         if (IsRenderScriptModule (mod))
517ef20b08fSColin Riley         {
518ef20b08fSColin Riley             LoadModule(mod);
519ef20b08fSColin Riley         }
520ef20b08fSColin Riley     }
521ef20b08fSColin Riley }
522ef20b08fSColin Riley 
5235ec532a9SColin Riley //------------------------------------------------------------------
5245ec532a9SColin Riley // PluginInterface protocol
5255ec532a9SColin Riley //------------------------------------------------------------------
5265ec532a9SColin Riley lldb_private::ConstString
5275ec532a9SColin Riley RenderScriptRuntime::GetPluginName()
5285ec532a9SColin Riley {
5295ec532a9SColin Riley     return GetPluginNameStatic();
5305ec532a9SColin Riley }
5315ec532a9SColin Riley 
5325ec532a9SColin Riley uint32_t
5335ec532a9SColin Riley RenderScriptRuntime::GetPluginVersion()
5345ec532a9SColin Riley {
5355ec532a9SColin Riley     return 1;
5365ec532a9SColin Riley }
5375ec532a9SColin Riley 
5385ec532a9SColin Riley bool
5395ec532a9SColin Riley RenderScriptRuntime::IsVTableName(const char *name)
5405ec532a9SColin Riley {
5415ec532a9SColin Riley     return false;
5425ec532a9SColin Riley }
5435ec532a9SColin Riley 
5445ec532a9SColin Riley bool
5455ec532a9SColin Riley RenderScriptRuntime::GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic,
5460b6003f3SEnrico Granata                                               TypeAndOrName &class_type_or_name, Address &address,
5470b6003f3SEnrico Granata                                               Value::ValueType &value_type)
5485ec532a9SColin Riley {
5495ec532a9SColin Riley     return false;
5505ec532a9SColin Riley }
5515ec532a9SColin Riley 
552c74275bcSEnrico Granata TypeAndOrName
553c74275bcSEnrico Granata RenderScriptRuntime::FixUpDynamicType (const TypeAndOrName& type_and_or_name,
5547eed4877SEnrico Granata                                        ValueObject& static_value)
555c74275bcSEnrico Granata {
556c74275bcSEnrico Granata     return type_and_or_name;
557c74275bcSEnrico Granata }
558c74275bcSEnrico Granata 
5595ec532a9SColin Riley bool
5605ec532a9SColin Riley RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value)
5615ec532a9SColin Riley {
5625ec532a9SColin Riley     return false;
5635ec532a9SColin Riley }
5645ec532a9SColin Riley 
5655ec532a9SColin Riley lldb::BreakpointResolverSP
5665ec532a9SColin Riley RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp, bool throw_bp)
5675ec532a9SColin Riley {
5685ec532a9SColin Riley     BreakpointResolverSP resolver_sp;
5695ec532a9SColin Riley     return resolver_sp;
5705ec532a9SColin Riley }
5715ec532a9SColin Riley 
5724640cde1SColin Riley const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
5734640cde1SColin Riley {
5744640cde1SColin Riley     //rsdScript
57582780287SAidan Dodds     {
57682780287SAidan Dodds         "rsdScriptInit", //name
57782780287SAidan Dodds         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhjj", // symbol name 32 bit
57882780287SAidan Dodds         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhmj", // symbol name 64 bit
57982780287SAidan Dodds         0, // version
58082780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
58182780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureScriptInit1 // handler
58282780287SAidan Dodds     },
58382780287SAidan Dodds     {
58482780287SAidan Dodds         "rsdScriptInvokeForEachMulti", // name
58582780287SAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall", // symbol name 32bit
58682780287SAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall", // symbol name 64bit
58782780287SAidan Dodds         0, // version
58882780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
589*e09c44b6SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti // handler
59082780287SAidan Dodds     },
59182780287SAidan Dodds     {
59282780287SAidan Dodds         "rsdScriptSetGlobalVar", // name
59382780287SAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvj", // symbol name 32bit
59482780287SAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvm", // symbol name 64bit
59582780287SAidan Dodds         0, // version
59682780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
59782780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar1 // handler
59882780287SAidan Dodds     },
5994640cde1SColin Riley 
6004640cde1SColin Riley     //rsdAllocation
60182780287SAidan Dodds     {
60282780287SAidan Dodds         "rsdAllocationInit", // name
60382780287SAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 32bit
60482780287SAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 64bit
60582780287SAidan Dodds         0, // version
60682780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
60782780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureAllocationInit1 // handler
60882780287SAidan Dodds     },
60982780287SAidan Dodds     {
61082780287SAidan Dodds         "rsdAllocationRead2D", //name
61182780287SAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvjj", // symbol name 32bit
61282780287SAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvmm", // symbol name 64bit
61382780287SAidan Dodds         0, // version
61482780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
61582780287SAidan Dodds         nullptr // handler
61682780287SAidan Dodds     },
617e69df382SEwan Crawford     {
618e69df382SEwan Crawford         "rsdAllocationDestroy", // name
619e69df382SEwan Crawford         "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE", // symbol name 32bit
620e69df382SEwan Crawford         "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE", // symbol name 64bit
621e69df382SEwan Crawford         0, // version
622e69df382SEwan Crawford         RenderScriptRuntime::eModuleKindDriver, // type
623e69df382SEwan Crawford         &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy // handler
624e69df382SEwan Crawford     },
6254640cde1SColin Riley };
6264640cde1SColin Riley 
627222b937cSEugene Zelenko const size_t RenderScriptRuntime::s_runtimeHookCount = sizeof(s_runtimeHookDefns)/sizeof(s_runtimeHookDefns[0]);
6284640cde1SColin Riley 
6294640cde1SColin Riley bool
6304640cde1SColin Riley RenderScriptRuntime::HookCallback(void *baton, StoppointCallbackContext *ctx, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
6314640cde1SColin Riley {
6324640cde1SColin Riley     RuntimeHook* hook_info = (RuntimeHook*)baton;
6334640cde1SColin Riley     ExecutionContext context(ctx->exe_ctx_ref);
6344640cde1SColin Riley 
6354640cde1SColin Riley     RenderScriptRuntime *lang_rt = (RenderScriptRuntime *)context.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
6364640cde1SColin Riley 
6374640cde1SColin Riley     lang_rt->HookCallback(hook_info, context);
6384640cde1SColin Riley 
6394640cde1SColin Riley     return false;
6404640cde1SColin Riley }
6414640cde1SColin Riley 
6424640cde1SColin Riley void
6434640cde1SColin Riley RenderScriptRuntime::HookCallback(RuntimeHook* hook_info, ExecutionContext& context)
6444640cde1SColin Riley {
6454640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
6464640cde1SColin Riley 
6474640cde1SColin Riley     if (log)
6484640cde1SColin Riley         log->Printf ("RenderScriptRuntime::HookCallback - '%s' .", hook_info->defn->name);
6494640cde1SColin Riley 
6504640cde1SColin Riley     if (hook_info->defn->grabber)
6514640cde1SColin Riley     {
6524640cde1SColin Riley         (this->*(hook_info->defn->grabber))(hook_info, context);
6534640cde1SColin Riley     }
6544640cde1SColin Riley }
6554640cde1SColin Riley 
6564640cde1SColin Riley bool
65782780287SAidan Dodds RenderScriptRuntime::GetArgSimple(ExecutionContext &context, uint32_t arg, uint64_t *data)
6584640cde1SColin Riley {
659cdfb1485SEwan Crawford     // Get a positional integer argument.
660cdfb1485SEwan Crawford     // Given an ExecutionContext, ``context`` which should be a RenderScript
661cdfb1485SEwan Crawford     // frame, get the value of the positional argument ``arg`` and save its value
662cdfb1485SEwan Crawford     // to the address pointed to by ``data``.
663cdfb1485SEwan Crawford     // returns true on success, false otherwise.
664cdfb1485SEwan Crawford     // If unsuccessful, the value pointed to by ``data`` is undefined. Otherwise,
665cdfb1485SEwan Crawford     // ``data`` will be set to the value of the the given ``arg``.
666cdfb1485SEwan Crawford     // NOTE: only natural width integer arguments for the machine are supported.
667cdfb1485SEwan Crawford     // Behaviour with non primitive arguments is undefined.
668cdfb1485SEwan Crawford 
6694640cde1SColin Riley     if (!data)
6704640cde1SColin Riley         return false;
6714640cde1SColin Riley 
67282780287SAidan Dodds     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
6734640cde1SColin Riley     Error error;
6744640cde1SColin Riley     RegisterContext* reg_ctx = context.GetRegisterContext();
6754640cde1SColin Riley     Process* process = context.GetProcessPtr();
67682780287SAidan Dodds     bool success = false; // return value
6774640cde1SColin Riley 
67882780287SAidan Dodds     if (!context.GetTargetPtr())
67982780287SAidan Dodds     {
68082780287SAidan Dodds         if (log)
68182780287SAidan Dodds             log->Printf("RenderScriptRuntime::GetArgSimple - Invalid target");
68282780287SAidan Dodds 
68382780287SAidan Dodds         return false;
68482780287SAidan Dodds     }
68582780287SAidan Dodds 
68682780287SAidan Dodds     switch (context.GetTargetPtr()->GetArchitecture().GetMachine())
68782780287SAidan Dodds     {
68882780287SAidan Dodds         case llvm::Triple::ArchType::x86:
6894640cde1SColin Riley         {
6904640cde1SColin Riley             uint64_t sp = reg_ctx->GetSP();
6914640cde1SColin Riley             uint32_t offset = (1 + arg) * sizeof(uint32_t);
69282780287SAidan Dodds             uint32_t result = 0;
69382780287SAidan Dodds             process->ReadMemory(sp + offset, &result, sizeof(uint32_t), error);
6944640cde1SColin Riley             if (error.Fail())
6954640cde1SColin Riley             {
6964640cde1SColin Riley                 if (log)
69782780287SAidan Dodds                     log->Printf("RenderScriptRuntime::GetArgSimple - error reading X86 stack: %s.", error.AsCString());
6984640cde1SColin Riley             }
69982780287SAidan Dodds             else
7004640cde1SColin Riley             {
70182780287SAidan Dodds                 *data = result;
70282780287SAidan Dodds                 success = true;
70382780287SAidan Dodds             }
70482780287SAidan Dodds             break;
70582780287SAidan Dodds         }
706cdfb1485SEwan Crawford         case llvm::Triple::ArchType::x86_64:
707cdfb1485SEwan Crawford         {
708cdfb1485SEwan Crawford             // amd64 has 6 integer registers, and 8 XMM registers for parameter passing.
709cdfb1485SEwan Crawford             // Surplus args are spilled onto the stack.
710cdfb1485SEwan Crawford             // rdi, rsi, rdx, rcx, r8, r9, (zmm0 - 7 for vectors)
711cdfb1485SEwan Crawford             // ref: AMD64 ABI Draft 0.99.6 – October 7, 2013 – 10:35; Figure 3.4. Retrieved from
712cdfb1485SEwan Crawford             // http://www.x86-64.org/documentation/abi.pdf
713cdfb1485SEwan Crawford             if (arg > 5)
714cdfb1485SEwan Crawford             {
715cdfb1485SEwan Crawford                 if (log)
716cdfb1485SEwan Crawford                     log->Warning("X86_64 register spill is not supported.");
717cdfb1485SEwan Crawford                 break;
718cdfb1485SEwan Crawford             }
719cdfb1485SEwan Crawford             const char * regnames[] = {"rdi", "rsi", "rdx", "rcx", "r8", "r9"};
720cdfb1485SEwan Crawford             assert((sizeof(regnames) / sizeof(const char *)) > arg);
721cdfb1485SEwan Crawford             const RegisterInfo *rArg = reg_ctx->GetRegisterInfoByName(regnames[arg]);
722cdfb1485SEwan Crawford             RegisterValue rVal;
723cdfb1485SEwan Crawford             success = reg_ctx->ReadRegister(rArg, rVal);
724cdfb1485SEwan Crawford             if (success)
725cdfb1485SEwan Crawford             {
726cdfb1485SEwan Crawford                 *data = rVal.GetAsUInt64(0u, &success);
727cdfb1485SEwan Crawford             }
728cdfb1485SEwan Crawford             else
729cdfb1485SEwan Crawford             {
730cdfb1485SEwan Crawford                 if (log)
731cdfb1485SEwan Crawford                     log->Printf("RenderScriptRuntime::GetArgSimple - error reading x86_64 register: %d.", arg);
732cdfb1485SEwan Crawford             }
733cdfb1485SEwan Crawford             break;
734cdfb1485SEwan Crawford         }
73582780287SAidan Dodds         case llvm::Triple::ArchType::arm:
73682780287SAidan Dodds         {
73782780287SAidan Dodds             // arm 32 bit
73835e7b1adSAidan Dodds             // first 4 arguments are passed via registers
7394640cde1SColin Riley             if (arg < 4)
7404640cde1SColin Riley             {
7414640cde1SColin Riley                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg);
7424640cde1SColin Riley                 RegisterValue rVal;
74302f1c5d1SEwan Crawford                 success = reg_ctx->ReadRegister(rArg, rVal);
74402f1c5d1SEwan Crawford                 if (success)
74502f1c5d1SEwan Crawford                 {
746cdfb1485SEwan Crawford                     (*data) = rVal.GetAsUInt32(0u, &success);
74702f1c5d1SEwan Crawford                 }
74802f1c5d1SEwan Crawford                 else
74902f1c5d1SEwan Crawford                 {
75002f1c5d1SEwan Crawford                     if (log)
75102f1c5d1SEwan Crawford                         log->Printf("RenderScriptRuntime::GetArgSimple - error reading ARM register: %d.", arg);
75202f1c5d1SEwan Crawford                 }
7534640cde1SColin Riley             }
7544640cde1SColin Riley             else
7554640cde1SColin Riley             {
7564640cde1SColin Riley                 uint64_t sp = reg_ctx->GetSP();
7574640cde1SColin Riley                 uint32_t offset = (arg-4) * sizeof(uint32_t);
75835e7b1adSAidan Dodds                 uint32_t value = 0;
75935e7b1adSAidan Dodds                 size_t bytes_read = process->ReadMemory(sp + offset, &value, sizeof(value), error);
76035e7b1adSAidan Dodds                 if (error.Fail() || bytes_read != sizeof(value))
7614640cde1SColin Riley                 {
7624640cde1SColin Riley                     if (log)
76382780287SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple - error reading ARM stack: %s.", error.AsCString());
76482780287SAidan Dodds                 }
76582780287SAidan Dodds                 else
76682780287SAidan Dodds                 {
76735e7b1adSAidan Dodds                     *data = value;
76882780287SAidan Dodds                     success = true;
7694640cde1SColin Riley                 }
7704640cde1SColin Riley             }
77182780287SAidan Dodds             break;
7724640cde1SColin Riley         }
77382780287SAidan Dodds         case llvm::Triple::ArchType::aarch64:
77482780287SAidan Dodds         {
77582780287SAidan Dodds             // arm 64 bit
77682780287SAidan Dodds             // first 8 arguments are in the registers
77782780287SAidan Dodds             if (arg < 8)
77882780287SAidan Dodds             {
77982780287SAidan Dodds                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg);
78082780287SAidan Dodds                 RegisterValue rVal;
78182780287SAidan Dodds                 success = reg_ctx->ReadRegister(rArg, rVal);
78282780287SAidan Dodds                 if (success)
78382780287SAidan Dodds                 {
784cdfb1485SEwan Crawford                     *data = rVal.GetAsUInt64(0u, &success);
78582780287SAidan Dodds                 }
78682780287SAidan Dodds                 else
78782780287SAidan Dodds                 {
78882780287SAidan Dodds                     if (log)
78982780287SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple() - AARCH64 - Error while reading the argument #%d", arg);
79082780287SAidan Dodds                 }
79182780287SAidan Dodds             }
79282780287SAidan Dodds             else
79382780287SAidan Dodds             {
79482780287SAidan Dodds                 // @TODO: need to find the argument in the stack
79582780287SAidan Dodds                 if (log)
79682780287SAidan Dodds                     log->Printf("RenderScriptRuntime::GetArgSimple - AARCH64 - FOR #ARG >= 8 NOT IMPLEMENTED YET. Argument number: %d", arg);
79782780287SAidan Dodds             }
79882780287SAidan Dodds             break;
79982780287SAidan Dodds         }
80074b396d9SAidan Dodds         case llvm::Triple::ArchType::mipsel:
80174b396d9SAidan Dodds         {
80274b396d9SAidan Dodds             // read from the registers
80335e7b1adSAidan Dodds             // first 4 arguments are passed in registers
80474b396d9SAidan Dodds             if (arg < 4){
80574b396d9SAidan Dodds                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg + 4);
80674b396d9SAidan Dodds                 RegisterValue rVal;
80774b396d9SAidan Dodds                 success = reg_ctx->ReadRegister(rArg, rVal);
80874b396d9SAidan Dodds                 if (success)
80974b396d9SAidan Dodds                 {
810cdfb1485SEwan Crawford                     *data = rVal.GetAsUInt64(0u, &success);
81174b396d9SAidan Dodds                 }
81274b396d9SAidan Dodds                 else
81374b396d9SAidan Dodds                 {
81474b396d9SAidan Dodds                     if (log)
81574b396d9SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple() - Mips - Error while reading the argument #%d", arg);
81674b396d9SAidan Dodds                 }
81774b396d9SAidan Dodds             }
81835e7b1adSAidan Dodds             // arguments > 4 are read from the stack
81974b396d9SAidan Dodds             else
82074b396d9SAidan Dodds             {
82174b396d9SAidan Dodds                 uint64_t sp = reg_ctx->GetSP();
82274b396d9SAidan Dodds                 uint32_t offset = arg * sizeof(uint32_t);
82335e7b1adSAidan Dodds                 uint32_t value = 0;
82435e7b1adSAidan Dodds                 size_t bytes_read = process->ReadMemory(sp + offset, &value, sizeof(value), error);
82535e7b1adSAidan Dodds                 if (error.Fail() || bytes_read != sizeof(value))
82674b396d9SAidan Dodds                 {
82774b396d9SAidan Dodds                     if (log)
82874b396d9SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple - error reading Mips stack: %s.", error.AsCString());
82974b396d9SAidan Dodds                 }
83074b396d9SAidan Dodds                 else
83174b396d9SAidan Dodds                 {
83235e7b1adSAidan Dodds                     *data = value;
83374b396d9SAidan Dodds                     success = true;
83474b396d9SAidan Dodds                 }
83574b396d9SAidan Dodds             }
83674b396d9SAidan Dodds             break;
83774b396d9SAidan Dodds         }
83802f1c5d1SEwan Crawford         case llvm::Triple::ArchType::mips64el:
83902f1c5d1SEwan Crawford         {
84002f1c5d1SEwan Crawford             // read from the registers
84102f1c5d1SEwan Crawford             if (arg < 8)
84202f1c5d1SEwan Crawford             {
84302f1c5d1SEwan Crawford                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg + 4);
84402f1c5d1SEwan Crawford                 RegisterValue rVal;
84502f1c5d1SEwan Crawford                 success = reg_ctx->ReadRegister(rArg, rVal);
84602f1c5d1SEwan Crawford                 if (success)
84702f1c5d1SEwan Crawford                 {
848cdfb1485SEwan Crawford                     (*data) = rVal.GetAsUInt64(0u, &success);
84902f1c5d1SEwan Crawford                 }
85002f1c5d1SEwan Crawford                 else
85102f1c5d1SEwan Crawford                 {
85202f1c5d1SEwan Crawford                     if (log)
85302f1c5d1SEwan Crawford                         log->Printf("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading the argument #%d", arg);
85402f1c5d1SEwan Crawford                 }
85502f1c5d1SEwan Crawford             }
85635e7b1adSAidan Dodds             // arguments > 8 are read from the stack
85702f1c5d1SEwan Crawford             else
85802f1c5d1SEwan Crawford             {
85902f1c5d1SEwan Crawford                 uint64_t sp = reg_ctx->GetSP();
86002f1c5d1SEwan Crawford                 uint32_t offset = (arg - 8) * sizeof(uint64_t);
86135e7b1adSAidan Dodds                 uint64_t value = 0;
86235e7b1adSAidan Dodds                 size_t bytes_read = process->ReadMemory(sp + offset, &value, sizeof(value), error);
86335e7b1adSAidan Dodds                 if (error.Fail() || bytes_read != sizeof(value))
86402f1c5d1SEwan Crawford                 {
86502f1c5d1SEwan Crawford                     if (log)
86602f1c5d1SEwan Crawford                         log->Printf("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading Mips64 stack: %s.", error.AsCString());
86702f1c5d1SEwan Crawford                 }
86802f1c5d1SEwan Crawford                 else
86902f1c5d1SEwan Crawford                 {
87035e7b1adSAidan Dodds                     *data = value;
87102f1c5d1SEwan Crawford                     success = true;
87202f1c5d1SEwan Crawford                 }
87302f1c5d1SEwan Crawford             }
87402f1c5d1SEwan Crawford             break;
87502f1c5d1SEwan Crawford         }
87682780287SAidan Dodds         default:
87782780287SAidan Dodds         {
87882780287SAidan Dodds             // invalid architecture
87982780287SAidan Dodds             if (log)
88082780287SAidan Dodds                 log->Printf("RenderScriptRuntime::GetArgSimple - Architecture not supported");
88182780287SAidan Dodds         }
88282780287SAidan Dodds     }
88382780287SAidan Dodds 
884cdfb1485SEwan Crawford     if (!success)
885cdfb1485SEwan Crawford     {
886cdfb1485SEwan Crawford         if (log)
887cdfb1485SEwan Crawford             log->Printf("RenderScriptRuntime::GetArgSimple - failed to get argument at index %" PRIu32, arg);
888cdfb1485SEwan Crawford     }
88982780287SAidan Dodds     return success;
8904640cde1SColin Riley }
8914640cde1SColin Riley 
8924640cde1SColin Riley void
893*e09c44b6SAidan Dodds RenderScriptRuntime::CaptureScriptInvokeForEachMulti(RuntimeHook* hook_info,
894*e09c44b6SAidan Dodds                                                      ExecutionContext& context)
895*e09c44b6SAidan Dodds {
896*e09c44b6SAidan Dodds     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
897*e09c44b6SAidan Dodds 
898*e09c44b6SAidan Dodds     struct args_t
899*e09c44b6SAidan Dodds     {
900*e09c44b6SAidan Dodds         uint64_t context;   // const Context       *rsc
901*e09c44b6SAidan Dodds         uint64_t script;    // Script              *s
902*e09c44b6SAidan Dodds         uint64_t slot;      // uint32_t             slot
903*e09c44b6SAidan Dodds         uint64_t aIns;      // const Allocation   **aIns
904*e09c44b6SAidan Dodds         uint64_t inLen;     // size_t               inLen
905*e09c44b6SAidan Dodds         uint64_t aOut;      // Allocation          *aout
906*e09c44b6SAidan Dodds         uint64_t usr;       // const void          *usr
907*e09c44b6SAidan Dodds         uint64_t usrLen;    // size_t               usrLen
908*e09c44b6SAidan Dodds         uint64_t sc;        // const RsScriptCall  *sc
909*e09c44b6SAidan Dodds     }
910*e09c44b6SAidan Dodds     args;
911*e09c44b6SAidan Dodds 
912*e09c44b6SAidan Dodds     bool success =
913*e09c44b6SAidan Dodds         GetArgSimple(context, 0, &args.context) &&
914*e09c44b6SAidan Dodds         GetArgSimple(context, 1, &args.script) &&
915*e09c44b6SAidan Dodds         GetArgSimple(context, 2, &args.slot) &&
916*e09c44b6SAidan Dodds         GetArgSimple(context, 3, &args.aIns) &&
917*e09c44b6SAidan Dodds         GetArgSimple(context, 4, &args.inLen) &&
918*e09c44b6SAidan Dodds         GetArgSimple(context, 5, &args.aOut) &&
919*e09c44b6SAidan Dodds         GetArgSimple(context, 6, &args.usr) &&
920*e09c44b6SAidan Dodds         GetArgSimple(context, 7, &args.usrLen) &&
921*e09c44b6SAidan Dodds         GetArgSimple(context, 8, &args.sc);
922*e09c44b6SAidan Dodds 
923*e09c44b6SAidan Dodds     if (!success)
924*e09c44b6SAidan Dodds     {
925*e09c44b6SAidan Dodds         if (log)
926*e09c44b6SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureScriptInvokeForEachMulti()"
927*e09c44b6SAidan Dodds                         " - Error while reading the function parameters");
928*e09c44b6SAidan Dodds         return;
929*e09c44b6SAidan Dodds     }
930*e09c44b6SAidan Dodds 
931*e09c44b6SAidan Dodds     const uint32_t target_ptr_size = m_process->GetAddressByteSize();
932*e09c44b6SAidan Dodds     Error error;
933*e09c44b6SAidan Dodds     std::vector<uint64_t> allocs;
934*e09c44b6SAidan Dodds 
935*e09c44b6SAidan Dodds     // traverse allocation list
936*e09c44b6SAidan Dodds     for (uint64_t i = 0; i < args.inLen; ++i)
937*e09c44b6SAidan Dodds     {
938*e09c44b6SAidan Dodds         // calculate offest to allocation pointer
939*e09c44b6SAidan Dodds         const lldb::addr_t addr = args.aIns + i * target_ptr_size;
940*e09c44b6SAidan Dodds 
941*e09c44b6SAidan Dodds         // Note: due to little endian layout, reading 32bits or 64bits into res64 will
942*e09c44b6SAidan Dodds         //       give the correct results.
943*e09c44b6SAidan Dodds 
944*e09c44b6SAidan Dodds         uint64_t res64 = 0;
945*e09c44b6SAidan Dodds         size_t read = m_process->ReadMemory(addr, &res64, target_ptr_size, error);
946*e09c44b6SAidan Dodds         if (read != target_ptr_size || !error.Success())
947*e09c44b6SAidan Dodds         {
948*e09c44b6SAidan Dodds             if (log)
949*e09c44b6SAidan Dodds                 log->Printf("RenderScriptRuntime::CaptureScriptInvokeForEachMulti()"
950*e09c44b6SAidan Dodds                             " - Error while reading allocation list argument %" PRId64, i);
951*e09c44b6SAidan Dodds         }
952*e09c44b6SAidan Dodds         else
953*e09c44b6SAidan Dodds         {
954*e09c44b6SAidan Dodds             allocs.push_back(res64);
955*e09c44b6SAidan Dodds         }
956*e09c44b6SAidan Dodds     }
957*e09c44b6SAidan Dodds 
958*e09c44b6SAidan Dodds     // if there is an output allocation track it
959*e09c44b6SAidan Dodds     if (args.aOut)
960*e09c44b6SAidan Dodds     {
961*e09c44b6SAidan Dodds         allocs.push_back(args.aOut);
962*e09c44b6SAidan Dodds     }
963*e09c44b6SAidan Dodds 
964*e09c44b6SAidan Dodds     // for all allocations we have found
965*e09c44b6SAidan Dodds     for (const uint64_t alloc_addr : allocs)
966*e09c44b6SAidan Dodds     {
967*e09c44b6SAidan Dodds         AllocationDetails* alloc = LookUpAllocation(alloc_addr, true);
968*e09c44b6SAidan Dodds         if (alloc)
969*e09c44b6SAidan Dodds         {
970*e09c44b6SAidan Dodds             // save the allocation address
971*e09c44b6SAidan Dodds             if (alloc->address.isValid())
972*e09c44b6SAidan Dodds             {
973*e09c44b6SAidan Dodds                 // check the allocation address we already have matches
974*e09c44b6SAidan Dodds                 assert(*alloc->address.get() == alloc_addr);
975*e09c44b6SAidan Dodds             }
976*e09c44b6SAidan Dodds             else
977*e09c44b6SAidan Dodds             {
978*e09c44b6SAidan Dodds                 alloc->address = alloc_addr;
979*e09c44b6SAidan Dodds             }
980*e09c44b6SAidan Dodds 
981*e09c44b6SAidan Dodds             // save the context
982*e09c44b6SAidan Dodds             if (log)
983*e09c44b6SAidan Dodds             {
984*e09c44b6SAidan Dodds                 if (alloc->context.isValid() && *alloc->context.get() != args.context)
985*e09c44b6SAidan Dodds                     log->Printf("RenderScriptRuntime::CaptureScriptInvokeForEachMulti"
986*e09c44b6SAidan Dodds                                 " - Allocation used by multiple contexts");
987*e09c44b6SAidan Dodds             }
988*e09c44b6SAidan Dodds             alloc->context = args.context;
989*e09c44b6SAidan Dodds         }
990*e09c44b6SAidan Dodds     }
991*e09c44b6SAidan Dodds 
992*e09c44b6SAidan Dodds     // make sure we track this script object
993*e09c44b6SAidan Dodds     if (lldb_private::RenderScriptRuntime::ScriptDetails * script = LookUpScript(args.script, true))
994*e09c44b6SAidan Dodds     {
995*e09c44b6SAidan Dodds         if (log)
996*e09c44b6SAidan Dodds         {
997*e09c44b6SAidan Dodds             if (script->context.isValid() && *script->context.get() != args.context)
998*e09c44b6SAidan Dodds                 log->Printf("RenderScriptRuntime::CaptureScriptInvokeForEachMulti"
999*e09c44b6SAidan Dodds                             " - Script used by multiple contexts");
1000*e09c44b6SAidan Dodds         }
1001*e09c44b6SAidan Dodds         script->context = args.context;
1002*e09c44b6SAidan Dodds     }
1003*e09c44b6SAidan Dodds }
1004*e09c44b6SAidan Dodds 
1005*e09c44b6SAidan Dodds void
10064640cde1SColin Riley RenderScriptRuntime::CaptureSetGlobalVar1(RuntimeHook* hook_info, ExecutionContext& context)
10074640cde1SColin Riley {
10084640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
10094640cde1SColin Riley 
10104640cde1SColin Riley     //Context, Script, int, data, length
10114640cde1SColin Riley 
101282780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
101382780287SAidan Dodds     uint64_t rs_script_u64 = 0U;
101482780287SAidan Dodds     uint64_t rs_id_u64 = 0U;
101582780287SAidan Dodds     uint64_t rs_data_u64 = 0U;
101682780287SAidan Dodds     uint64_t rs_length_u64 = 0U;
10174640cde1SColin Riley 
101882780287SAidan Dodds     bool success =
101982780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
102082780287SAidan Dodds         GetArgSimple(context, 1, &rs_script_u64) &&
102182780287SAidan Dodds         GetArgSimple(context, 2, &rs_id_u64) &&
102282780287SAidan Dodds         GetArgSimple(context, 3, &rs_data_u64) &&
102382780287SAidan Dodds         GetArgSimple(context, 4, &rs_length_u64);
10244640cde1SColin Riley 
102582780287SAidan Dodds     if (!success)
102682780287SAidan Dodds     {
102782780287SAidan Dodds         if (log)
102882780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureSetGlobalVar1 - Error while reading the function parameters");
102982780287SAidan Dodds         return;
103082780287SAidan Dodds     }
10314640cde1SColin Riley 
10324640cde1SColin Riley     if (log)
10334640cde1SColin Riley     {
10344640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64 ":%" PRIu64 "bytes.",
103582780287SAidan Dodds                         rs_context_u64, rs_script_u64, rs_id_u64, rs_data_u64, rs_length_u64);
10364640cde1SColin Riley 
103782780287SAidan Dodds         addr_t script_addr =  (addr_t)rs_script_u64;
10384640cde1SColin Riley         if (m_scriptMappings.find( script_addr ) != m_scriptMappings.end())
10394640cde1SColin Riley         {
10404640cde1SColin Riley             auto rsm = m_scriptMappings[script_addr];
104182780287SAidan Dodds             if (rs_id_u64 < rsm->m_globals.size())
10424640cde1SColin Riley             {
104382780287SAidan Dodds                 auto rsg = rsm->m_globals[rs_id_u64];
10444640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - Setting of '%s' within '%s' inferred", rsg.m_name.AsCString(),
10454640cde1SColin Riley                                 rsm->m_module->GetFileSpec().GetFilename().AsCString());
10464640cde1SColin Riley             }
10474640cde1SColin Riley         }
10484640cde1SColin Riley     }
10494640cde1SColin Riley }
10504640cde1SColin Riley 
10514640cde1SColin Riley void
10524640cde1SColin Riley RenderScriptRuntime::CaptureAllocationInit1(RuntimeHook* hook_info, ExecutionContext& context)
10534640cde1SColin Riley {
10544640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
10554640cde1SColin Riley 
10564640cde1SColin Riley     //Context, Alloc, bool
10574640cde1SColin Riley 
105882780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
105982780287SAidan Dodds     uint64_t rs_alloc_u64 = 0U;
106082780287SAidan Dodds     uint64_t rs_forceZero_u64 = 0U;
10614640cde1SColin Riley 
106282780287SAidan Dodds     bool success =
106382780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
106482780287SAidan Dodds         GetArgSimple(context, 1, &rs_alloc_u64) &&
106582780287SAidan Dodds         GetArgSimple(context, 2, &rs_forceZero_u64);
106682780287SAidan Dodds     if (!success) // error case
106782780287SAidan Dodds     {
106882780287SAidan Dodds         if (log)
106982780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureAllocationInit1 - Error while reading the function parameters");
107082780287SAidan Dodds         return; // abort
107182780287SAidan Dodds     }
10724640cde1SColin Riley 
10734640cde1SColin Riley     if (log)
10744640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureAllocationInit1 - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
107582780287SAidan Dodds                         rs_context_u64, rs_alloc_u64, rs_forceZero_u64);
107678f339d1SEwan Crawford 
107778f339d1SEwan Crawford     AllocationDetails* alloc = LookUpAllocation(rs_alloc_u64, true);
107878f339d1SEwan Crawford     if (alloc)
107978f339d1SEwan Crawford         alloc->context = rs_context_u64;
10804640cde1SColin Riley }
10814640cde1SColin Riley 
10824640cde1SColin Riley void
1083e69df382SEwan Crawford RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook* hook_info, ExecutionContext& context)
1084e69df382SEwan Crawford {
1085e69df382SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1086e69df382SEwan Crawford 
1087e69df382SEwan Crawford     // Context, Alloc
1088e69df382SEwan Crawford     uint64_t rs_context_u64 = 0U;
1089e69df382SEwan Crawford     uint64_t rs_alloc_u64 = 0U;
1090e69df382SEwan Crawford 
1091e69df382SEwan Crawford     bool success = GetArgSimple(context, 0, &rs_context_u64) && GetArgSimple(context, 1, &rs_alloc_u64);
1092e69df382SEwan Crawford     if (!success) // error case
1093e69df382SEwan Crawford     {
1094e69df382SEwan Crawford         if (log)
1095e69df382SEwan Crawford             log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - Error while reading the function parameters");
1096e69df382SEwan Crawford         return; // abort
1097e69df382SEwan Crawford     }
1098e69df382SEwan Crawford 
1099e69df382SEwan Crawford     if (log)
1100e69df382SEwan Crawford         log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - 0x%" PRIx64 ", 0x%" PRIx64 ".",
1101e69df382SEwan Crawford                     rs_context_u64, rs_alloc_u64);
1102e69df382SEwan Crawford 
1103e69df382SEwan Crawford     for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter)
1104e69df382SEwan Crawford     {
1105e69df382SEwan Crawford         auto& allocation_ap = *iter; // get the unique pointer
1106e69df382SEwan Crawford         if (allocation_ap->address.isValid() && *allocation_ap->address.get() == rs_alloc_u64)
1107e69df382SEwan Crawford         {
1108e69df382SEwan Crawford             m_allocations.erase(iter);
1109e69df382SEwan Crawford             if (log)
1110e69df382SEwan Crawford                 log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - Deleted allocation entry");
1111e69df382SEwan Crawford             return;
1112e69df382SEwan Crawford         }
1113e69df382SEwan Crawford     }
1114e69df382SEwan Crawford 
1115e69df382SEwan Crawford     if (log)
1116e69df382SEwan Crawford         log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - Couldn't find destroyed allocation");
1117e69df382SEwan Crawford }
1118e69df382SEwan Crawford 
1119e69df382SEwan Crawford void
11204640cde1SColin Riley RenderScriptRuntime::CaptureScriptInit1(RuntimeHook* hook_info, ExecutionContext& context)
11214640cde1SColin Riley {
11224640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11234640cde1SColin Riley 
11244640cde1SColin Riley     //Context, Script, resname Str, cachedir Str
11254640cde1SColin Riley     Error error;
11264640cde1SColin Riley     Process* process = context.GetProcessPtr();
11274640cde1SColin Riley 
112882780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
112982780287SAidan Dodds     uint64_t rs_script_u64 = 0U;
113082780287SAidan Dodds     uint64_t rs_resnameptr_u64 = 0U;
113182780287SAidan Dodds     uint64_t rs_cachedirptr_u64 = 0U;
11324640cde1SColin Riley 
11334640cde1SColin Riley     std::string resname;
11344640cde1SColin Riley     std::string cachedir;
11354640cde1SColin Riley 
113682780287SAidan Dodds     // read the function parameters
113782780287SAidan Dodds     bool success =
113882780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
113982780287SAidan Dodds         GetArgSimple(context, 1, &rs_script_u64) &&
114082780287SAidan Dodds         GetArgSimple(context, 2, &rs_resnameptr_u64) &&
114182780287SAidan Dodds         GetArgSimple(context, 3, &rs_cachedirptr_u64);
11424640cde1SColin Riley 
114382780287SAidan Dodds     if (!success)
114482780287SAidan Dodds     {
114582780287SAidan Dodds         if (log)
114682780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureScriptInit1 - Error while reading the function parameters");
114782780287SAidan Dodds         return;
114882780287SAidan Dodds     }
114982780287SAidan Dodds 
115082780287SAidan Dodds     process->ReadCStringFromMemory((lldb::addr_t)rs_resnameptr_u64, resname, error);
11514640cde1SColin Riley     if (error.Fail())
11524640cde1SColin Riley     {
11534640cde1SColin Riley         if (log)
11544640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading resname: %s.", error.AsCString());
11554640cde1SColin Riley 
11564640cde1SColin Riley     }
11574640cde1SColin Riley 
115882780287SAidan Dodds     process->ReadCStringFromMemory((lldb::addr_t)rs_cachedirptr_u64, cachedir, error);
11594640cde1SColin Riley     if (error.Fail())
11604640cde1SColin Riley     {
11614640cde1SColin Riley         if (log)
11624640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading cachedir: %s.", error.AsCString());
11634640cde1SColin Riley     }
11644640cde1SColin Riley 
11654640cde1SColin Riley     if (log)
11664640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
116782780287SAidan Dodds                      rs_context_u64, rs_script_u64, resname.c_str(), cachedir.c_str());
11684640cde1SColin Riley 
11694640cde1SColin Riley     if (resname.size() > 0)
11704640cde1SColin Riley     {
11714640cde1SColin Riley         StreamString strm;
11724640cde1SColin Riley         strm.Printf("librs.%s.so", resname.c_str());
11734640cde1SColin Riley 
117478f339d1SEwan Crawford         ScriptDetails* script = LookUpScript(rs_script_u64, true);
117578f339d1SEwan Crawford         if (script)
117678f339d1SEwan Crawford         {
117778f339d1SEwan Crawford             script->type = ScriptDetails::eScriptC;
117878f339d1SEwan Crawford             script->cacheDir = cachedir;
117978f339d1SEwan Crawford             script->resName = resname;
118078f339d1SEwan Crawford             script->scriptDyLib = strm.GetData();
118178f339d1SEwan Crawford             script->context = addr_t(rs_context_u64);
118278f339d1SEwan Crawford         }
11834640cde1SColin Riley 
11844640cde1SColin Riley         if (log)
11854640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - '%s' tagged with context 0x%" PRIx64 " and script 0x%" PRIx64 ".",
118682780287SAidan Dodds                          strm.GetData(), rs_context_u64, rs_script_u64);
11874640cde1SColin Riley     }
11884640cde1SColin Riley     else if (log)
11894640cde1SColin Riley     {
11904640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - resource name invalid, Script not tagged");
11914640cde1SColin Riley     }
11924640cde1SColin Riley }
11934640cde1SColin Riley 
11944640cde1SColin Riley void
11954640cde1SColin Riley RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind)
11964640cde1SColin Riley {
11974640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11984640cde1SColin Riley 
11994640cde1SColin Riley     if (!module)
12004640cde1SColin Riley     {
12014640cde1SColin Riley         return;
12024640cde1SColin Riley     }
12034640cde1SColin Riley 
120482780287SAidan Dodds     Target &target = GetProcess()->GetTarget();
120582780287SAidan Dodds     llvm::Triple::ArchType targetArchType = target.GetArchitecture().GetMachine();
120682780287SAidan Dodds 
120782780287SAidan Dodds     if (targetArchType != llvm::Triple::ArchType::x86
120882780287SAidan Dodds         && targetArchType != llvm::Triple::ArchType::arm
120902f1c5d1SEwan Crawford         && targetArchType != llvm::Triple::ArchType::aarch64
121074b396d9SAidan Dodds         && targetArchType != llvm::Triple::ArchType::mipsel
121102f1c5d1SEwan Crawford         && targetArchType != llvm::Triple::ArchType::mips64el
1212cdfb1485SEwan Crawford         && targetArchType != llvm::Triple::ArchType::x86_64
121302f1c5d1SEwan Crawford     )
12144640cde1SColin Riley     {
12154640cde1SColin Riley         if (log)
121674b396d9SAidan Dodds             log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to hook runtime. Only X86, ARM, Mips supported currently.");
12174640cde1SColin Riley 
12184640cde1SColin Riley         return;
12194640cde1SColin Riley     }
12204640cde1SColin Riley 
122182780287SAidan Dodds     uint32_t archByteSize = target.GetArchitecture().GetAddressByteSize();
12224640cde1SColin Riley 
12234640cde1SColin Riley     for (size_t idx = 0; idx < s_runtimeHookCount; idx++)
12244640cde1SColin Riley     {
12254640cde1SColin Riley         const HookDefn* hook_defn = &s_runtimeHookDefns[idx];
12264640cde1SColin Riley         if (hook_defn->kind != kind) {
12274640cde1SColin Riley             continue;
12284640cde1SColin Riley         }
12294640cde1SColin Riley 
123082780287SAidan Dodds         const char* symbol_name = (archByteSize == 4) ? hook_defn->symbol_name_m32 : hook_defn->symbol_name_m64;
123182780287SAidan Dodds 
123282780287SAidan Dodds         const Symbol *sym = module->FindFirstSymbolWithNameAndType(ConstString(symbol_name), eSymbolTypeCode);
123382780287SAidan Dodds         if (!sym){
123482780287SAidan Dodds             if (log){
123582780287SAidan Dodds                 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - ERROR: Symbol '%s' related to the function %s not found", symbol_name, hook_defn->name);
123682780287SAidan Dodds             }
123782780287SAidan Dodds             continue;
123882780287SAidan Dodds         }
12394640cde1SColin Riley 
1240358cf1eaSGreg Clayton         addr_t addr = sym->GetLoadAddress(&target);
12414640cde1SColin Riley         if (addr == LLDB_INVALID_ADDRESS)
12424640cde1SColin Riley         {
12434640cde1SColin Riley             if (log)
12444640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to resolve the address of hook function '%s' with symbol '%s'.",
124582780287SAidan Dodds                              hook_defn->name, symbol_name);
12464640cde1SColin Riley             continue;
12474640cde1SColin Riley         }
124882780287SAidan Dodds         else
124982780287SAidan Dodds         {
125082780287SAidan Dodds             if (log)
125182780287SAidan Dodds                 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - Function %s, address resolved at 0x%" PRIx64, hook_defn->name, addr);
125282780287SAidan Dodds         }
12534640cde1SColin Riley 
12544640cde1SColin Riley         RuntimeHookSP hook(new RuntimeHook());
12554640cde1SColin Riley         hook->address = addr;
12564640cde1SColin Riley         hook->defn = hook_defn;
12574640cde1SColin Riley         hook->bp_sp = target.CreateBreakpoint(addr, true, false);
12584640cde1SColin Riley         hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
12594640cde1SColin Riley         m_runtimeHooks[addr] = hook;
12604640cde1SColin Riley         if (log)
12614640cde1SColin Riley         {
12624640cde1SColin Riley             log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Successfully hooked '%s' in '%s' version %" PRIu64 " at 0x%" PRIx64 ".",
12634640cde1SColin Riley                 hook_defn->name, module->GetFileSpec().GetFilename().AsCString(), (uint64_t)hook_defn->version, (uint64_t)addr);
12644640cde1SColin Riley         }
12654640cde1SColin Riley     }
12664640cde1SColin Riley }
12674640cde1SColin Riley 
12684640cde1SColin Riley void
12694640cde1SColin Riley RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp)
12704640cde1SColin Riley {
12714640cde1SColin Riley     if (!rsmodule_sp)
12724640cde1SColin Riley         return;
12734640cde1SColin Riley 
12744640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
12754640cde1SColin Riley 
12764640cde1SColin Riley     const ModuleSP module = rsmodule_sp->m_module;
12774640cde1SColin Riley     const FileSpec& file = module->GetPlatformFileSpec();
12784640cde1SColin Riley 
127978f339d1SEwan Crawford     // Iterate over all of the scripts that we currently know of.
128078f339d1SEwan Crawford     // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
12814640cde1SColin Riley     for (const auto & rs_script : m_scripts)
12824640cde1SColin Riley     {
128378f339d1SEwan Crawford         // Extract the expected .so file path for this script.
128478f339d1SEwan Crawford         std::string dylib;
128578f339d1SEwan Crawford         if (!rs_script->scriptDyLib.get(dylib))
128678f339d1SEwan Crawford             continue;
128778f339d1SEwan Crawford 
128878f339d1SEwan Crawford         // Only proceed if the module that has loaded corresponds to this script.
128978f339d1SEwan Crawford         if (file.GetFilename() != ConstString(dylib.c_str()))
129078f339d1SEwan Crawford             continue;
129178f339d1SEwan Crawford 
129278f339d1SEwan Crawford         // Obtain the script address which we use as a key.
129378f339d1SEwan Crawford         lldb::addr_t script;
129478f339d1SEwan Crawford         if (!rs_script->script.get(script))
129578f339d1SEwan Crawford             continue;
129678f339d1SEwan Crawford 
129778f339d1SEwan Crawford         // If we have a script mapping for the current script.
129878f339d1SEwan Crawford         if (m_scriptMappings.find(script) != m_scriptMappings.end())
12994640cde1SColin Riley         {
130078f339d1SEwan Crawford             // if the module we have stored is different to the one we just received.
130178f339d1SEwan Crawford             if (m_scriptMappings[script] != rsmodule_sp)
13024640cde1SColin Riley             {
13034640cde1SColin Riley                 if (log)
13044640cde1SColin Riley                     log->Printf ("RenderScriptRuntime::FixupScriptDetails - Error: script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
130578f339d1SEwan Crawford                                     (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
13064640cde1SColin Riley             }
13074640cde1SColin Riley         }
130878f339d1SEwan Crawford         // We don't have a script mapping for the current script.
13094640cde1SColin Riley         else
13104640cde1SColin Riley         {
131178f339d1SEwan Crawford             // Obtain the script resource name.
131278f339d1SEwan Crawford             std::string resName;
131378f339d1SEwan Crawford             if (rs_script->resName.get(resName))
131478f339d1SEwan Crawford                 // Set the modules resource name.
131578f339d1SEwan Crawford                 rsmodule_sp->m_resname = resName;
131678f339d1SEwan Crawford             // Add Script/Module pair to map.
131778f339d1SEwan Crawford             m_scriptMappings[script] = rsmodule_sp;
13184640cde1SColin Riley             if (log)
13194640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::FixupScriptDetails - script %" PRIx64 " associated with rsmodule '%s'.",
132078f339d1SEwan Crawford                                 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
13214640cde1SColin Riley         }
13224640cde1SColin Riley     }
13234640cde1SColin Riley }
13244640cde1SColin Riley 
132515f2bd95SEwan Crawford // Uses the Target API to evaluate the expression passed as a parameter to the function
132615f2bd95SEwan Crawford // The result of that expression is returned an unsigned 64 bit int, via the result* paramter.
132715f2bd95SEwan Crawford // Function returns true on success, and false on failure
132815f2bd95SEwan Crawford bool
132915f2bd95SEwan Crawford RenderScriptRuntime::EvalRSExpression(const char* expression, StackFrame* frame_ptr, uint64_t* result)
133015f2bd95SEwan Crawford {
133115f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
133215f2bd95SEwan Crawford     if (log)
133315f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::EvalRSExpression(%s)", expression);
133415f2bd95SEwan Crawford 
133515f2bd95SEwan Crawford     ValueObjectSP expr_result;
133615f2bd95SEwan Crawford     // Perform the actual expression evaluation
133715f2bd95SEwan Crawford     GetProcess()->GetTarget().EvaluateExpression(expression, frame_ptr, expr_result);
133815f2bd95SEwan Crawford 
133915f2bd95SEwan Crawford     if (!expr_result)
134015f2bd95SEwan Crawford     {
134115f2bd95SEwan Crawford        if (log)
134215f2bd95SEwan Crawford            log->Printf("RenderScriptRuntime::EvalRSExpression -  Error: Couldn't evaluate expression");
134315f2bd95SEwan Crawford        return false;
134415f2bd95SEwan Crawford     }
134515f2bd95SEwan Crawford 
134615f2bd95SEwan Crawford     // The result of the expression is invalid
134715f2bd95SEwan Crawford     if (!expr_result->GetError().Success())
134815f2bd95SEwan Crawford     {
134915f2bd95SEwan Crawford         Error err = expr_result->GetError();
135015f2bd95SEwan Crawford         if (err.GetError() == UserExpression::kNoResult) // Expression returned void, so this is actually a success
135115f2bd95SEwan Crawford         {
135215f2bd95SEwan Crawford             if (log)
135315f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::EvalRSExpression - Expression returned void");
135415f2bd95SEwan Crawford 
135515f2bd95SEwan Crawford             result = nullptr;
135615f2bd95SEwan Crawford             return true;
135715f2bd95SEwan Crawford         }
135815f2bd95SEwan Crawford 
135915f2bd95SEwan Crawford         if (log)
136015f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::EvalRSExpression - Error evaluating expression result: %s", err.AsCString());
136115f2bd95SEwan Crawford         return false;
136215f2bd95SEwan Crawford     }
136315f2bd95SEwan Crawford 
136415f2bd95SEwan Crawford     bool success = false;
136515f2bd95SEwan Crawford     *result = expr_result->GetValueAsUnsigned(0, &success); // We only read the result as an unsigned int.
136615f2bd95SEwan Crawford 
136715f2bd95SEwan Crawford     if (!success)
136815f2bd95SEwan Crawford     {
136915f2bd95SEwan Crawford        if (log)
137015f2bd95SEwan Crawford            log->Printf("RenderScriptRuntime::EvalRSExpression -  Error: Couldn't convert expression result to unsigned int");
137115f2bd95SEwan Crawford        return false;
137215f2bd95SEwan Crawford     }
137315f2bd95SEwan Crawford 
137415f2bd95SEwan Crawford     return true;
137515f2bd95SEwan Crawford }
137615f2bd95SEwan Crawford 
1377b1651b8dSEwan Crawford namespace // anonymous
137815f2bd95SEwan Crawford {
1379b1651b8dSEwan Crawford     // max length of an expanded expression
1380b1651b8dSEwan Crawford     const int jit_max_expr_size = 768;
138115f2bd95SEwan Crawford 
138215f2bd95SEwan Crawford     // Format strings containing the expressions we may need to evaluate.
138315f2bd95SEwan Crawford     const char runtimeExpressions[][256] =
138415f2bd95SEwan Crawford     {
138515f2bd95SEwan Crawford      // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
138615f2bd95SEwan Crawford      "(int*)_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace(0x%lx, %u, %u, %u, 0, 0)",
138715f2bd95SEwan Crawford 
138815f2bd95SEwan Crawford      // Type* rsaAllocationGetType(Context*, Allocation*)
138915f2bd95SEwan Crawford      "(void*)rsaAllocationGetType(0x%lx, 0x%lx)",
139015f2bd95SEwan Crawford 
139115f2bd95SEwan Crawford      // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
139215f2bd95SEwan Crawford      // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ;
139315f2bd95SEwan Crawford      // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
139415f2bd95SEwan Crawford      // Need to specify 32 or 64 bit for uint_t since this differs between devices
139515f2bd95SEwan Crawford      "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[0]", // X dim
139615f2bd95SEwan Crawford      "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[1]", // Y dim
139715f2bd95SEwan Crawford      "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[2]", // Z dim
139815f2bd95SEwan Crawford      "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[5]", // Element ptr
139915f2bd95SEwan Crawford 
140015f2bd95SEwan Crawford      // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
140115f2bd95SEwan Crawford      // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData
14028b244e21SEwan Crawford      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[0]", // Type
14038b244e21SEwan Crawford      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[1]", // Kind
14048b244e21SEwan Crawford      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[3]", // Vector Size
14058b244e21SEwan Crawford      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[4]", // Field Count
14068b244e21SEwan Crawford 
14078b244e21SEwan Crawford       // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t *ids, const char **names,
14088b244e21SEwan Crawford       // size_t *arraySizes, uint32_t dataSize)
14098b244e21SEwan Crawford       // Needed for Allocations of structs to gather details about fields/Subelements
14108b244e21SEwan Crawford      "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
14118b244e21SEwan Crawford      "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); ids[%u]",     // Element* of field
14128b244e21SEwan Crawford 
14138b244e21SEwan Crawford      "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
14148b244e21SEwan Crawford      "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); names[%u]",   // Name of field
14158b244e21SEwan Crawford 
14168b244e21SEwan Crawford      "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
14178b244e21SEwan Crawford      "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); arr_size[%u]" // Array size of field
141815f2bd95SEwan Crawford     };
141915f2bd95SEwan Crawford 
1420b1651b8dSEwan Crawford 
1421b1651b8dSEwan Crawford     // Temporary workaround for MIPS, until the compiler emits the JAL instruction when invoking directly the function.
1422b1651b8dSEwan Crawford     // At the moment, when evaluating an expression involving a function call, the LLVM codegen for Mips  emits a JAL
1423b1651b8dSEwan Crawford     // instruction, which is able to jump in the range +/- 128MB with respect to the current program counter ($pc). If
1424b1651b8dSEwan Crawford     // the requested function happens to reside outside the above region, the function address will be truncated and the
1425b1651b8dSEwan Crawford     // function invocation will fail. This is a problem in the RS plugin as we rely on the RS API to probe the number and
1426b1651b8dSEwan Crawford     // the nature of allocations. A proper solution in the MIPS compiler is currently being investigated. As temporary
1427b1651b8dSEwan Crawford     // work around for this context, we'll invoke the RS API through function pointers, which cause the compiler to emit a
1428b1651b8dSEwan Crawford     // register based JALR instruction.
1429b1651b8dSEwan Crawford     const char runtimeExpressions_mips[][512] =
1430b1651b8dSEwan Crawford     {
1431b1651b8dSEwan Crawford     // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1432b1651b8dSEwan Crawford     "int* (*f) (void*, int, int, int, int, int) = (int* (*) (void*, int, int, int, int, int)) "
1433b1651b8dSEwan Crawford         "_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace; "
1434b1651b8dSEwan Crawford         "(int*) f((void*) 0x%lx, %u, %u, %u, 0, 0)",
1435b1651b8dSEwan Crawford 
1436b1651b8dSEwan Crawford     // Type* rsaAllocationGetType(Context*, Allocation*)
1437b1651b8dSEwan Crawford     "void* (*f) (void*, void*) = (void* (*) (void*, void*)) rsaAllocationGetType; (void*) f((void*) 0x%lx, (void*) 0x%lx)",
1438b1651b8dSEwan Crawford 
1439b1651b8dSEwan Crawford     // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
1440b1651b8dSEwan Crawford     // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ;
1441b1651b8dSEwan Crawford     // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
1442b1651b8dSEwan Crawford     // Need to specify 32 or 64 bit for uint_t since this differs between devices
1443b1651b8dSEwan Crawford     "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) "
1444b1651b8dSEwan Crawford         "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[0]",
1445b1651b8dSEwan Crawford     "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) "
1446b1651b8dSEwan Crawford         "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[1]",
1447b1651b8dSEwan Crawford     "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) "
1448b1651b8dSEwan Crawford         "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[2]",
1449b1651b8dSEwan Crawford     "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) "
1450b1651b8dSEwan Crawford         "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[5]",
1451b1651b8dSEwan Crawford 
1452b1651b8dSEwan Crawford     // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1453b1651b8dSEwan Crawford     // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData
1454b1651b8dSEwan Crawford     "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) "
1455b1651b8dSEwan Crawford         "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[0]", // Type
1456b1651b8dSEwan Crawford     "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) "
1457b1651b8dSEwan Crawford         "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[1]", // Kind
1458b1651b8dSEwan Crawford     "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) "
1459b1651b8dSEwan Crawford         "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[3]", // Vector size
1460b1651b8dSEwan Crawford     "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) "
1461b1651b8dSEwan Crawford         "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[4]", // Field count
1462b1651b8dSEwan Crawford 
1463b1651b8dSEwan Crawford     // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t *ids, const char **names,
1464b1651b8dSEwan Crawford     // size_t *arraySizes, uint32_t dataSize)
1465b1651b8dSEwan Crawford     // Needed for Allocations of structs to gather details about fields/Subelements
1466b1651b8dSEwan Crawford    "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
1467b1651b8dSEwan Crawford         "void* (*f) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t) = "
1468b1651b8dSEwan Crawford         "(void* (*) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t)) rsaElementGetSubElements;"
1469b1651b8dSEwan Crawford         "(void*) f((void*) 0x%lx, (void*) 0x%lx, (uintptr_t*) ids, names, arr_size, (uint32_t) %u);"
1470b1651b8dSEwan Crawford         "ids[%u]", // Element* of field
1471b1651b8dSEwan Crawford    "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
1472b1651b8dSEwan Crawford         "void* (*f) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t) = "
1473b1651b8dSEwan Crawford         "(void* (*) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t)) rsaElementGetSubElements;"
1474b1651b8dSEwan Crawford         "(void*) f((void*) 0x%lx, (void*) 0x%lx, (uintptr_t*) ids, names, arr_size, (uint32_t) %u);"
1475b1651b8dSEwan Crawford         "names[%u]", // Name of field
1476b1651b8dSEwan Crawford    "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
1477b1651b8dSEwan Crawford         "void* (*f) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t) = "
1478b1651b8dSEwan Crawford         "(void* (*) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t)) rsaElementGetSubElements;"
1479b1651b8dSEwan Crawford         "(void*) f((void*) 0x%lx, (void*) 0x%lx, (uintptr_t*) ids, names, arr_size, (uint32_t) %u);"
1480b1651b8dSEwan Crawford         "arr_size[%u]" // Array size of field
1481b1651b8dSEwan Crawford     };
1482b1651b8dSEwan Crawford 
1483b1651b8dSEwan Crawford } // end of the anonymous namespace
1484b1651b8dSEwan Crawford 
1485b1651b8dSEwan Crawford 
1486b1651b8dSEwan Crawford // Retrieve the string to JIT for the given expression
1487b1651b8dSEwan Crawford const char*
1488b1651b8dSEwan Crawford RenderScriptRuntime::JITTemplate(ExpressionStrings e)
1489b1651b8dSEwan Crawford {
1490b1651b8dSEwan Crawford     // be nice to your Mips friend when adding new expression strings
1491b1651b8dSEwan Crawford     static_assert(sizeof(runtimeExpressions)/sizeof(runtimeExpressions[0]) ==
1492b1651b8dSEwan Crawford             sizeof(runtimeExpressions_mips)/sizeof(runtimeExpressions_mips[0]),
1493b1651b8dSEwan Crawford             "#runtimeExpressions != #runtimeExpressions_mips");
1494b1651b8dSEwan Crawford 
1495b1651b8dSEwan Crawford     assert((e >= eExprGetOffsetPtr && e <= eExprSubelementsArrSize) &&
1496b1651b8dSEwan Crawford            "Expression string out of bounds");
1497b1651b8dSEwan Crawford 
1498b1651b8dSEwan Crawford     llvm::Triple::ArchType arch = GetTargetRef().GetArchitecture().GetMachine();
1499b1651b8dSEwan Crawford 
1500b1651b8dSEwan Crawford     // mips JAL workaround
1501b1651b8dSEwan Crawford     if(arch == llvm::Triple::ArchType::mips64el || arch == llvm::Triple::ArchType::mipsel)
1502b1651b8dSEwan Crawford         return runtimeExpressions_mips[e];
1503b1651b8dSEwan Crawford     else
1504b1651b8dSEwan Crawford         return runtimeExpressions[e];
1505b1651b8dSEwan Crawford }
1506b1651b8dSEwan Crawford 
1507b1651b8dSEwan Crawford 
150815f2bd95SEwan Crawford // JITs the RS runtime for the internal data pointer of an allocation.
150915f2bd95SEwan Crawford // Is passed x,y,z coordinates for the pointer to a specific element.
151015f2bd95SEwan Crawford // Then sets the data_ptr member in Allocation with the result.
151115f2bd95SEwan Crawford // Returns true on success, false otherwise
151215f2bd95SEwan Crawford bool
151315f2bd95SEwan Crawford RenderScriptRuntime::JITDataPointer(AllocationDetails* allocation, StackFrame* frame_ptr,
151415f2bd95SEwan Crawford                                     unsigned int x, unsigned int y, unsigned int z)
151515f2bd95SEwan Crawford {
151615f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
151715f2bd95SEwan Crawford 
151815f2bd95SEwan Crawford     if (!allocation->address.isValid())
151915f2bd95SEwan Crawford     {
152015f2bd95SEwan Crawford         if (log)
152115f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Failed to find allocation details");
152215f2bd95SEwan Crawford         return false;
152315f2bd95SEwan Crawford     }
152415f2bd95SEwan Crawford 
1525b1651b8dSEwan Crawford     const char* expr_cstr = JITTemplate(eExprGetOffsetPtr);
1526b1651b8dSEwan Crawford     char buffer[jit_max_expr_size];
152715f2bd95SEwan Crawford 
1528b1651b8dSEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), x, y, z);
152915f2bd95SEwan Crawford     if (chars_written < 0)
153015f2bd95SEwan Crawford     {
153115f2bd95SEwan Crawford         if (log)
153215f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
153315f2bd95SEwan Crawford         return false;
153415f2bd95SEwan Crawford     }
1535b1651b8dSEwan Crawford     else if (chars_written >= jit_max_expr_size)
153615f2bd95SEwan Crawford     {
153715f2bd95SEwan Crawford         if (log)
153815f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Expression too long");
153915f2bd95SEwan Crawford         return false;
154015f2bd95SEwan Crawford     }
154115f2bd95SEwan Crawford 
154215f2bd95SEwan Crawford     uint64_t result = 0;
154315f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
154415f2bd95SEwan Crawford         return false;
154515f2bd95SEwan Crawford 
154615f2bd95SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
154715f2bd95SEwan Crawford     allocation->data_ptr = mem_ptr;
154815f2bd95SEwan Crawford 
154915f2bd95SEwan Crawford     return true;
155015f2bd95SEwan Crawford }
155115f2bd95SEwan Crawford 
155215f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
155315f2bd95SEwan Crawford // Then sets the type_ptr member in Allocation with the result.
155415f2bd95SEwan Crawford // Returns true on success, false otherwise
155515f2bd95SEwan Crawford bool
155615f2bd95SEwan Crawford RenderScriptRuntime::JITTypePointer(AllocationDetails* allocation, StackFrame* frame_ptr)
155715f2bd95SEwan Crawford {
155815f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
155915f2bd95SEwan Crawford 
156015f2bd95SEwan Crawford     if (!allocation->address.isValid() || !allocation->context.isValid())
156115f2bd95SEwan Crawford     {
156215f2bd95SEwan Crawford         if (log)
156315f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePointer - Failed to find allocation details");
156415f2bd95SEwan Crawford         return false;
156515f2bd95SEwan Crawford     }
156615f2bd95SEwan Crawford 
1567b1651b8dSEwan Crawford     const char* expr_cstr = JITTemplate(eExprAllocGetType);
1568b1651b8dSEwan Crawford     char buffer[jit_max_expr_size];
156915f2bd95SEwan Crawford 
1570b1651b8dSEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->context.get(), *allocation->address.get());
157115f2bd95SEwan Crawford     if (chars_written < 0)
157215f2bd95SEwan Crawford     {
157315f2bd95SEwan Crawford         if (log)
157415f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
157515f2bd95SEwan Crawford         return false;
157615f2bd95SEwan Crawford     }
1577b1651b8dSEwan Crawford     else if (chars_written >= jit_max_expr_size)
157815f2bd95SEwan Crawford     {
157915f2bd95SEwan Crawford         if (log)
158015f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePointer - Expression too long");
158115f2bd95SEwan Crawford         return false;
158215f2bd95SEwan Crawford     }
158315f2bd95SEwan Crawford 
158415f2bd95SEwan Crawford     uint64_t result = 0;
158515f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
158615f2bd95SEwan Crawford         return false;
158715f2bd95SEwan Crawford 
158815f2bd95SEwan Crawford     addr_t type_ptr = static_cast<lldb::addr_t>(result);
158915f2bd95SEwan Crawford     allocation->type_ptr = type_ptr;
159015f2bd95SEwan Crawford 
159115f2bd95SEwan Crawford     return true;
159215f2bd95SEwan Crawford }
159315f2bd95SEwan Crawford 
159415f2bd95SEwan Crawford // JITs the RS runtime for information about the dimensions and type of an allocation
159515f2bd95SEwan Crawford // Then sets dimension and element_ptr members in Allocation with the result.
159615f2bd95SEwan Crawford // Returns true on success, false otherwise
159715f2bd95SEwan Crawford bool
159815f2bd95SEwan Crawford RenderScriptRuntime::JITTypePacked(AllocationDetails* allocation, StackFrame* frame_ptr)
159915f2bd95SEwan Crawford {
160015f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
160115f2bd95SEwan Crawford 
160215f2bd95SEwan Crawford     if (!allocation->type_ptr.isValid() || !allocation->context.isValid())
160315f2bd95SEwan Crawford     {
160415f2bd95SEwan Crawford         if (log)
160515f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePacked - Failed to find allocation details");
160615f2bd95SEwan Crawford         return false;
160715f2bd95SEwan Crawford     }
160815f2bd95SEwan Crawford 
160915f2bd95SEwan Crawford     // Expression is different depending on if device is 32 or 64 bit
161015f2bd95SEwan Crawford     uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
161115f2bd95SEwan Crawford     const unsigned int bits = archByteSize == 4 ? 32 : 64;
161215f2bd95SEwan Crawford 
161315f2bd95SEwan Crawford     // We want 4 elements from packed data
161415f2bd95SEwan Crawford     const unsigned int num_exprs = 4;
161515f2bd95SEwan Crawford     assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) && "Invalid number of expressions");
161615f2bd95SEwan Crawford 
1617b1651b8dSEwan Crawford     char buffer[num_exprs][jit_max_expr_size];
161815f2bd95SEwan Crawford     uint64_t results[num_exprs];
161915f2bd95SEwan Crawford 
162015f2bd95SEwan Crawford     for (unsigned int i = 0; i < num_exprs; ++i)
162115f2bd95SEwan Crawford     {
1622b1651b8dSEwan Crawford         const char* expr_cstr = JITTemplate((ExpressionStrings) (eExprTypeDimX + i));
1623b1651b8dSEwan Crawford         int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, bits,
162415f2bd95SEwan Crawford                                      *allocation->context.get(), *allocation->type_ptr.get());
162515f2bd95SEwan Crawford         if (chars_written < 0)
162615f2bd95SEwan Crawford         {
162715f2bd95SEwan Crawford             if (log)
162815f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
162915f2bd95SEwan Crawford             return false;
163015f2bd95SEwan Crawford         }
1631b1651b8dSEwan Crawford         else if (chars_written >= jit_max_expr_size)
163215f2bd95SEwan Crawford         {
163315f2bd95SEwan Crawford             if (log)
163415f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITTypePacked - Expression too long");
163515f2bd95SEwan Crawford             return false;
163615f2bd95SEwan Crawford         }
163715f2bd95SEwan Crawford 
163815f2bd95SEwan Crawford         // Perform expression evaluation
163915f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
164015f2bd95SEwan Crawford             return false;
164115f2bd95SEwan Crawford     }
164215f2bd95SEwan Crawford 
164315f2bd95SEwan Crawford     // Assign results to allocation members
164415f2bd95SEwan Crawford     AllocationDetails::Dimension dims;
164515f2bd95SEwan Crawford     dims.dim_1 = static_cast<uint32_t>(results[0]);
164615f2bd95SEwan Crawford     dims.dim_2 = static_cast<uint32_t>(results[1]);
164715f2bd95SEwan Crawford     dims.dim_3 = static_cast<uint32_t>(results[2]);
164815f2bd95SEwan Crawford     allocation->dimension = dims;
164915f2bd95SEwan Crawford 
165015f2bd95SEwan Crawford     addr_t elem_ptr = static_cast<lldb::addr_t>(results[3]);
16518b244e21SEwan Crawford     allocation->element.element_ptr = elem_ptr;
165215f2bd95SEwan Crawford 
165315f2bd95SEwan Crawford     if (log)
165415f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::JITTypePacked - dims (%u, %u, %u) Element*: 0x%" PRIx64,
165515f2bd95SEwan Crawford                     dims.dim_1, dims.dim_2, dims.dim_3, elem_ptr);
165615f2bd95SEwan Crawford 
165715f2bd95SEwan Crawford     return true;
165815f2bd95SEwan Crawford }
165915f2bd95SEwan Crawford 
166015f2bd95SEwan Crawford // JITs the RS runtime for information about the Element of an allocation
16618b244e21SEwan Crawford // Then sets type, type_vec_size, field_count and type_kind members in Element with the result.
166215f2bd95SEwan Crawford // Returns true on success, false otherwise
166315f2bd95SEwan Crawford bool
16648b244e21SEwan Crawford RenderScriptRuntime::JITElementPacked(Element& elem, const lldb::addr_t context, StackFrame* frame_ptr)
166515f2bd95SEwan Crawford {
166615f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
166715f2bd95SEwan Crawford 
16688b244e21SEwan Crawford     if (!elem.element_ptr.isValid())
166915f2bd95SEwan Crawford     {
167015f2bd95SEwan Crawford         if (log)
167115f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITElementPacked - Failed to find allocation details");
167215f2bd95SEwan Crawford         return false;
167315f2bd95SEwan Crawford     }
167415f2bd95SEwan Crawford 
16758b244e21SEwan Crawford     // We want 4 elements from packed data
16768b244e21SEwan Crawford     const unsigned int num_exprs = 4;
16778b244e21SEwan Crawford     assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) && "Invalid number of expressions");
167815f2bd95SEwan Crawford 
1679b1651b8dSEwan Crawford     char buffer[num_exprs][jit_max_expr_size];
168015f2bd95SEwan Crawford     uint64_t results[num_exprs];
168115f2bd95SEwan Crawford 
168215f2bd95SEwan Crawford     for (unsigned int i = 0; i < num_exprs; i++)
168315f2bd95SEwan Crawford     {
1684b1651b8dSEwan Crawford         const char* expr_cstr = JITTemplate((ExpressionStrings) (eExprElementType + i));
1685b1651b8dSEwan Crawford         int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, context, *elem.element_ptr.get());
168615f2bd95SEwan Crawford         if (chars_written < 0)
168715f2bd95SEwan Crawford         {
168815f2bd95SEwan Crawford             if (log)
16898b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::JITElementPacked - Encoding error in snprintf()");
169015f2bd95SEwan Crawford             return false;
169115f2bd95SEwan Crawford         }
1692b1651b8dSEwan Crawford         else if (chars_written >= jit_max_expr_size)
169315f2bd95SEwan Crawford         {
169415f2bd95SEwan Crawford             if (log)
169515f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITElementPacked - Expression too long");
169615f2bd95SEwan Crawford             return false;
169715f2bd95SEwan Crawford         }
169815f2bd95SEwan Crawford 
169915f2bd95SEwan Crawford         // Perform expression evaluation
170015f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
170115f2bd95SEwan Crawford             return false;
170215f2bd95SEwan Crawford     }
170315f2bd95SEwan Crawford 
170415f2bd95SEwan Crawford     // Assign results to allocation members
17058b244e21SEwan Crawford     elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
17068b244e21SEwan Crawford     elem.type_kind = static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
17078b244e21SEwan Crawford     elem.type_vec_size = static_cast<uint32_t>(results[2]);
17088b244e21SEwan Crawford     elem.field_count = static_cast<uint32_t>(results[3]);
170915f2bd95SEwan Crawford 
171015f2bd95SEwan Crawford     if (log)
17118b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::JITElementPacked - data type %u, pixel type %u, vector size %u, field count %u",
17128b244e21SEwan Crawford                     *elem.type.get(), *elem.type_kind.get(), *elem.type_vec_size.get(), *elem.field_count.get());
17138b244e21SEwan Crawford 
17148b244e21SEwan Crawford     // If this Element has subelements then JIT rsaElementGetSubElements() for details about its fields
17158b244e21SEwan Crawford     if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
17168b244e21SEwan Crawford         return false;
17178b244e21SEwan Crawford 
17188b244e21SEwan Crawford     return true;
17198b244e21SEwan Crawford }
17208b244e21SEwan Crawford 
17218b244e21SEwan Crawford // JITs the RS runtime for information about the subelements/fields of a struct allocation
17228b244e21SEwan Crawford // This is necessary for infering the struct type so we can pretty print the allocation's contents.
17238b244e21SEwan Crawford // Returns true on success, false otherwise
17248b244e21SEwan Crawford bool
17258b244e21SEwan Crawford RenderScriptRuntime::JITSubelements(Element& elem, const lldb::addr_t context, StackFrame* frame_ptr)
17268b244e21SEwan Crawford {
17278b244e21SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
17288b244e21SEwan Crawford 
17298b244e21SEwan Crawford     if (!elem.element_ptr.isValid() || !elem.field_count.isValid())
17308b244e21SEwan Crawford     {
17318b244e21SEwan Crawford         if (log)
17328b244e21SEwan Crawford             log->Printf("RenderScriptRuntime::JITSubelements - Failed to find allocation details");
17338b244e21SEwan Crawford         return false;
17348b244e21SEwan Crawford     }
17358b244e21SEwan Crawford 
17368b244e21SEwan Crawford     const short num_exprs = 3;
17378b244e21SEwan Crawford     assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) && "Invalid number of expressions");
17388b244e21SEwan Crawford 
1739b1651b8dSEwan Crawford     char expr_buffer[jit_max_expr_size];
17408b244e21SEwan Crawford     uint64_t results;
17418b244e21SEwan Crawford 
17428b244e21SEwan Crawford     // Iterate over struct fields.
17438b244e21SEwan Crawford     const uint32_t field_count = *elem.field_count.get();
17448b244e21SEwan Crawford     for (unsigned int field_index = 0; field_index < field_count; ++field_index)
17458b244e21SEwan Crawford     {
17468b244e21SEwan Crawford         Element child;
17478b244e21SEwan Crawford         for (unsigned int expr_index = 0; expr_index < num_exprs; ++expr_index)
17488b244e21SEwan Crawford         {
1749b1651b8dSEwan Crawford             const char* expr_cstr = JITTemplate((ExpressionStrings) (eExprSubelementsId + expr_index));
1750b1651b8dSEwan Crawford             int chars_written = snprintf(expr_buffer, jit_max_expr_size, expr_cstr,
17518b244e21SEwan Crawford                                          field_count, field_count, field_count,
17528b244e21SEwan Crawford                                          context, *elem.element_ptr.get(), field_count, field_index);
17538b244e21SEwan Crawford             if (chars_written < 0)
17548b244e21SEwan Crawford             {
17558b244e21SEwan Crawford                 if (log)
17568b244e21SEwan Crawford                     log->Printf("RenderScriptRuntime::JITSubelements - Encoding error in snprintf()");
17578b244e21SEwan Crawford                 return false;
17588b244e21SEwan Crawford             }
1759b1651b8dSEwan Crawford             else if (chars_written >= jit_max_expr_size)
17608b244e21SEwan Crawford             {
17618b244e21SEwan Crawford                 if (log)
17628b244e21SEwan Crawford                     log->Printf("RenderScriptRuntime::JITSubelements - Expression too long");
17638b244e21SEwan Crawford                 return false;
17648b244e21SEwan Crawford             }
17658b244e21SEwan Crawford 
17668b244e21SEwan Crawford             // Perform expression evaluation
17678b244e21SEwan Crawford             if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
17688b244e21SEwan Crawford                 return false;
17698b244e21SEwan Crawford 
17708b244e21SEwan Crawford             if (log)
17718b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::JITSubelements - Expr result 0x%" PRIx64, results);
17728b244e21SEwan Crawford 
17738b244e21SEwan Crawford             switch(expr_index)
17748b244e21SEwan Crawford             {
17758b244e21SEwan Crawford                 case 0: // Element* of child
17768b244e21SEwan Crawford                     child.element_ptr = static_cast<addr_t>(results);
17778b244e21SEwan Crawford                     break;
17788b244e21SEwan Crawford                 case 1: // Name of child
17798b244e21SEwan Crawford                 {
17808b244e21SEwan Crawford                     lldb::addr_t address = static_cast<addr_t>(results);
17818b244e21SEwan Crawford                     Error err;
17828b244e21SEwan Crawford                     std::string name;
17838b244e21SEwan Crawford                     GetProcess()->ReadCStringFromMemory(address, name, err);
17848b244e21SEwan Crawford                     if (!err.Fail())
17858b244e21SEwan Crawford                         child.type_name = ConstString(name);
17868b244e21SEwan Crawford                     else
17878b244e21SEwan Crawford                     {
17888b244e21SEwan Crawford                         if (log)
17898b244e21SEwan Crawford                             log->Printf("RenderScriptRuntime::JITSubelements - Warning: Couldn't read field name");
17908b244e21SEwan Crawford                     }
17918b244e21SEwan Crawford                     break;
17928b244e21SEwan Crawford                 }
17938b244e21SEwan Crawford                 case 2: // Array size of child
17948b244e21SEwan Crawford                     child.array_size = static_cast<uint32_t>(results);
17958b244e21SEwan Crawford                     break;
17968b244e21SEwan Crawford             }
17978b244e21SEwan Crawford         }
17988b244e21SEwan Crawford 
17998b244e21SEwan Crawford         // We need to recursively JIT each Element field of the struct since
18008b244e21SEwan Crawford         // structs can be nested inside structs.
18018b244e21SEwan Crawford         if (!JITElementPacked(child, context, frame_ptr))
18028b244e21SEwan Crawford             return false;
18038b244e21SEwan Crawford         elem.children.push_back(child);
18048b244e21SEwan Crawford     }
18058b244e21SEwan Crawford 
18068b244e21SEwan Crawford     // Try to infer the name of the struct type so we can pretty print the allocation contents.
18078b244e21SEwan Crawford     FindStructTypeName(elem, frame_ptr);
180815f2bd95SEwan Crawford 
180915f2bd95SEwan Crawford     return true;
181015f2bd95SEwan Crawford }
181115f2bd95SEwan Crawford 
1812a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
1813a0f08674SEwan Crawford // The `elem_size` paramter represents the size of a single element, including padding.
1814a0f08674SEwan Crawford // Which is needed as an offset from the last element pointer.
1815a0f08674SEwan Crawford // Using this offset minus the starting address we can calculate the size of the allocation.
1816a0f08674SEwan Crawford // Returns true on success, false otherwise
1817a0f08674SEwan Crawford bool
18188b244e21SEwan Crawford RenderScriptRuntime::JITAllocationSize(AllocationDetails* allocation, StackFrame* frame_ptr)
1819a0f08674SEwan Crawford {
1820a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1821a0f08674SEwan Crawford 
1822a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->dimension.isValid()
18238b244e21SEwan Crawford         || !allocation->data_ptr.isValid() || !allocation->element.datum_size.isValid())
1824a0f08674SEwan Crawford     {
1825a0f08674SEwan Crawford         if (log)
1826a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Failed to find allocation details");
1827a0f08674SEwan Crawford         return false;
1828a0f08674SEwan Crawford     }
1829a0f08674SEwan Crawford 
1830a0f08674SEwan Crawford     // Find dimensions
1831a0f08674SEwan Crawford     unsigned int dim_x = allocation->dimension.get()->dim_1;
1832a0f08674SEwan Crawford     unsigned int dim_y = allocation->dimension.get()->dim_2;
1833a0f08674SEwan Crawford     unsigned int dim_z = allocation->dimension.get()->dim_3;
1834a0f08674SEwan Crawford 
18358b244e21SEwan Crawford     // Our plan of jitting the last element address doesn't seem to work for struct Allocations
18368b244e21SEwan Crawford     // Instead try to infer the size ourselves without any inter element padding.
18378b244e21SEwan Crawford     if (allocation->element.children.size() > 0)
18388b244e21SEwan Crawford     {
18398b244e21SEwan Crawford         if (dim_x == 0) dim_x = 1;
18408b244e21SEwan Crawford         if (dim_y == 0) dim_y = 1;
18418b244e21SEwan Crawford         if (dim_z == 0) dim_z = 1;
18428b244e21SEwan Crawford 
18438b244e21SEwan Crawford         allocation->size = dim_x * dim_y * dim_z * *allocation->element.datum_size.get();
18448b244e21SEwan Crawford 
18458b244e21SEwan Crawford         if (log)
18468b244e21SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Infered size of struct allocation %u", *allocation->size.get());
18478b244e21SEwan Crawford 
18488b244e21SEwan Crawford         return true;
18498b244e21SEwan Crawford     }
18508b244e21SEwan Crawford 
1851b1651b8dSEwan Crawford     const char* expr_cstr = JITTemplate(eExprGetOffsetPtr);
1852b1651b8dSEwan Crawford     char buffer[jit_max_expr_size];
18538b244e21SEwan Crawford 
1854a0f08674SEwan Crawford     // Calculate last element
1855a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 0 : dim_x - 1;
1856a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 0 : dim_y - 1;
1857a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 0 : dim_z - 1;
1858a0f08674SEwan Crawford 
1859b1651b8dSEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(),
1860a0f08674SEwan Crawford                                  dim_x, dim_y, dim_z);
1861a0f08674SEwan Crawford     if (chars_written < 0)
1862a0f08674SEwan Crawford     {
1863a0f08674SEwan Crawford         if (log)
1864a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Encoding error in snprintf()");
1865a0f08674SEwan Crawford         return false;
1866a0f08674SEwan Crawford     }
1867b1651b8dSEwan Crawford     else if (chars_written >= jit_max_expr_size)
1868a0f08674SEwan Crawford     {
1869a0f08674SEwan Crawford         if (log)
1870a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Expression too long");
1871a0f08674SEwan Crawford         return false;
1872a0f08674SEwan Crawford     }
1873a0f08674SEwan Crawford 
1874a0f08674SEwan Crawford     uint64_t result = 0;
1875a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1876a0f08674SEwan Crawford         return false;
1877a0f08674SEwan Crawford 
1878a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1879a0f08674SEwan Crawford     // Find pointer to last element and add on size of an element
18808b244e21SEwan Crawford     allocation->size = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()) + *allocation->element.datum_size.get();
1881a0f08674SEwan Crawford 
1882a0f08674SEwan Crawford     return true;
1883a0f08674SEwan Crawford }
1884a0f08674SEwan Crawford 
1885a0f08674SEwan Crawford // JITs the RS runtime for information about the stride between rows in the allocation.
1886a0f08674SEwan Crawford // This is done to detect padding, since allocated memory is 16-byte aligned.
1887a0f08674SEwan Crawford // Returns true on success, false otherwise
1888a0f08674SEwan Crawford bool
1889a0f08674SEwan Crawford RenderScriptRuntime::JITAllocationStride(AllocationDetails* allocation, StackFrame* frame_ptr)
1890a0f08674SEwan Crawford {
1891a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1892a0f08674SEwan Crawford 
1893a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->data_ptr.isValid())
1894a0f08674SEwan Crawford     {
1895a0f08674SEwan Crawford         if (log)
1896a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Failed to find allocation details");
1897a0f08674SEwan Crawford         return false;
1898a0f08674SEwan Crawford     }
1899a0f08674SEwan Crawford 
1900b1651b8dSEwan Crawford     const char* expr_cstr = JITTemplate(eExprGetOffsetPtr);
1901b1651b8dSEwan Crawford     char buffer[jit_max_expr_size];
1902a0f08674SEwan Crawford 
1903b1651b8dSEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(),
1904a0f08674SEwan Crawford                                  0, 1, 0);
1905a0f08674SEwan Crawford     if (chars_written < 0)
1906a0f08674SEwan Crawford     {
1907a0f08674SEwan Crawford         if (log)
1908a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Encoding error in snprintf()");
1909a0f08674SEwan Crawford         return false;
1910a0f08674SEwan Crawford     }
1911b1651b8dSEwan Crawford     else if (chars_written >= jit_max_expr_size)
1912a0f08674SEwan Crawford     {
1913a0f08674SEwan Crawford         if (log)
1914a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Expression too long");
1915a0f08674SEwan Crawford         return false;
1916a0f08674SEwan Crawford     }
1917a0f08674SEwan Crawford 
1918a0f08674SEwan Crawford     uint64_t result = 0;
1919a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1920a0f08674SEwan Crawford         return false;
1921a0f08674SEwan Crawford 
1922a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1923a0f08674SEwan Crawford     allocation->stride = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get());
1924a0f08674SEwan Crawford 
1925a0f08674SEwan Crawford     return true;
1926a0f08674SEwan Crawford }
1927a0f08674SEwan Crawford 
192815f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
192915f2bd95SEwan Crawford bool
193015f2bd95SEwan Crawford RenderScriptRuntime::RefreshAllocation(AllocationDetails* allocation, StackFrame* frame_ptr)
193115f2bd95SEwan Crawford {
193215f2bd95SEwan Crawford     // GetOffsetPointer()
193315f2bd95SEwan Crawford     if (!JITDataPointer(allocation, frame_ptr))
193415f2bd95SEwan Crawford         return false;
193515f2bd95SEwan Crawford 
193615f2bd95SEwan Crawford     // rsaAllocationGetType()
193715f2bd95SEwan Crawford     if (!JITTypePointer(allocation, frame_ptr))
193815f2bd95SEwan Crawford         return false;
193915f2bd95SEwan Crawford 
194015f2bd95SEwan Crawford     // rsaTypeGetNativeData()
194115f2bd95SEwan Crawford     if (!JITTypePacked(allocation, frame_ptr))
194215f2bd95SEwan Crawford         return false;
194315f2bd95SEwan Crawford 
194415f2bd95SEwan Crawford     // rsaElementGetNativeData()
19458b244e21SEwan Crawford     if (!JITElementPacked(allocation->element, *allocation->context.get(), frame_ptr))
194615f2bd95SEwan Crawford         return false;
194715f2bd95SEwan Crawford 
19488b244e21SEwan Crawford     // Sets the datum_size member in Element
19498b244e21SEwan Crawford     SetElementSize(allocation->element);
19508b244e21SEwan Crawford 
195155232f09SEwan Crawford     // Use GetOffsetPointer() to infer size of the allocation
19528b244e21SEwan Crawford     if (!JITAllocationSize(allocation, frame_ptr))
195355232f09SEwan Crawford         return false;
195455232f09SEwan Crawford 
195555232f09SEwan Crawford     return true;
195655232f09SEwan Crawford }
195755232f09SEwan Crawford 
19588b244e21SEwan Crawford // Function attempts to set the type_name member of the paramaterised Element object.
19598b244e21SEwan Crawford // This string should be the name of the struct type the Element represents.
19608b244e21SEwan Crawford // We need this string for pretty printing the Element to users.
19618b244e21SEwan Crawford void
19628b244e21SEwan Crawford RenderScriptRuntime::FindStructTypeName(Element& elem, StackFrame* frame_ptr)
196355232f09SEwan Crawford {
19648b244e21SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
19658b244e21SEwan Crawford 
19668b244e21SEwan Crawford     if (!elem.type_name.IsEmpty()) // Name already set
19678b244e21SEwan Crawford         return;
19688b244e21SEwan Crawford     else
1969fe06b5adSAdrian McCarthy         elem.type_name = Element::GetFallbackStructName(); // Default type name if we don't succeed
19708b244e21SEwan Crawford 
19718b244e21SEwan Crawford     // Find all the global variables from the script rs modules
19728b244e21SEwan Crawford     VariableList variable_list;
19738b244e21SEwan Crawford     for (auto module_sp : m_rsmodules)
19748b244e21SEwan Crawford         module_sp->m_module->FindGlobalVariables(RegularExpression("."), true, UINT32_MAX, variable_list);
19758b244e21SEwan Crawford 
19768b244e21SEwan Crawford     // Iterate over all the global variables looking for one with a matching type to the Element.
19778b244e21SEwan Crawford     // We make the assumption a match exists since there needs to be a global variable to reflect the
19788b244e21SEwan Crawford     // struct type back into java host code.
19798b244e21SEwan Crawford     for (uint32_t var_index = 0; var_index < variable_list.GetSize(); ++var_index)
19808b244e21SEwan Crawford     {
19818b244e21SEwan Crawford         const VariableSP var_sp(variable_list.GetVariableAtIndex(var_index));
19828b244e21SEwan Crawford         if (!var_sp)
19838b244e21SEwan Crawford            continue;
19848b244e21SEwan Crawford 
19858b244e21SEwan Crawford         ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
19868b244e21SEwan Crawford         if (!valobj_sp)
19878b244e21SEwan Crawford             continue;
19888b244e21SEwan Crawford 
19898b244e21SEwan Crawford         // Find the number of variable fields.
19908b244e21SEwan Crawford         // If it has no fields, or more fields than our Element, then it can't be the struct we're looking for.
19918b244e21SEwan Crawford         // Don't check for equality since RS can add extra struct members for padding.
19928b244e21SEwan Crawford         size_t num_children = valobj_sp->GetNumChildren();
19938b244e21SEwan Crawford         if (num_children > elem.children.size() || num_children == 0)
19948b244e21SEwan Crawford             continue;
19958b244e21SEwan Crawford 
19968b244e21SEwan Crawford         // Iterate over children looking for members with matching field names.
19978b244e21SEwan Crawford         // If all the field names match, this is likely the struct we want.
19988b244e21SEwan Crawford         //
19998b244e21SEwan Crawford         //   TODO: This could be made more robust by also checking children data sizes, or array size
20008b244e21SEwan Crawford         bool found = true;
20018b244e21SEwan Crawford         for (size_t child_index = 0; child_index < num_children; ++child_index)
20028b244e21SEwan Crawford         {
20038b244e21SEwan Crawford             ValueObjectSP child = valobj_sp->GetChildAtIndex(child_index, true);
20048b244e21SEwan Crawford             if (!child || (child->GetName() != elem.children[child_index].type_name))
20058b244e21SEwan Crawford             {
20068b244e21SEwan Crawford                 found = false;
20078b244e21SEwan Crawford                 break;
20088b244e21SEwan Crawford             }
20098b244e21SEwan Crawford         }
20108b244e21SEwan Crawford 
20118b244e21SEwan Crawford         // RS can add extra struct members for padding in the format '#rs_padding_[0-9]+'
20128b244e21SEwan Crawford         if (found && num_children < elem.children.size())
20138b244e21SEwan Crawford         {
20148b244e21SEwan Crawford             const unsigned int size_diff = elem.children.size() - num_children;
20158b244e21SEwan Crawford             if (log)
20168b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::FindStructTypeName - %u padding struct entries", size_diff);
20178b244e21SEwan Crawford 
20188b244e21SEwan Crawford             for (unsigned int padding_index = 0; padding_index < size_diff; ++padding_index)
20198b244e21SEwan Crawford             {
20208b244e21SEwan Crawford                 const ConstString& name = elem.children[num_children + padding_index].type_name;
20218b244e21SEwan Crawford                 if (strcmp(name.AsCString(), "#rs_padding") < 0)
20228b244e21SEwan Crawford                     found = false;
20238b244e21SEwan Crawford             }
20248b244e21SEwan Crawford         }
20258b244e21SEwan Crawford 
20268b244e21SEwan Crawford         // We've found a global var with matching type
20278b244e21SEwan Crawford         if (found)
20288b244e21SEwan Crawford         {
20298b244e21SEwan Crawford             // Dereference since our Element type isn't a pointer.
20308b244e21SEwan Crawford             if (valobj_sp->IsPointerType())
20318b244e21SEwan Crawford             {
20328b244e21SEwan Crawford                 Error err;
20338b244e21SEwan Crawford                 ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
20348b244e21SEwan Crawford                 if (!err.Fail())
20358b244e21SEwan Crawford                     valobj_sp = deref_valobj;
20368b244e21SEwan Crawford             }
20378b244e21SEwan Crawford 
20388b244e21SEwan Crawford             // Save name of variable in Element.
20398b244e21SEwan Crawford             elem.type_name = valobj_sp->GetTypeName();
20408b244e21SEwan Crawford             if (log)
20418b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::FindStructTypeName - Element name set to %s", elem.type_name.AsCString());
20428b244e21SEwan Crawford 
20438b244e21SEwan Crawford             return;
20448b244e21SEwan Crawford         }
20458b244e21SEwan Crawford     }
20468b244e21SEwan Crawford }
20478b244e21SEwan Crawford 
20488b244e21SEwan Crawford // Function sets the datum_size member of Element. Representing the size of a single instance including padding.
20498b244e21SEwan Crawford // Assumes the relevant allocation information has already been jitted.
20508b244e21SEwan Crawford void
20518b244e21SEwan Crawford RenderScriptRuntime::SetElementSize(Element& elem)
20528b244e21SEwan Crawford {
20538b244e21SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
20548b244e21SEwan Crawford     const Element::DataType type = *elem.type.get();
20552e920715SEwan Crawford     assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT
205655232f09SEwan Crawford                                                    && "Invalid allocation type");
205755232f09SEwan Crawford 
20588b244e21SEwan Crawford     const unsigned int vec_size = *elem.type_vec_size.get();
20598b244e21SEwan Crawford     unsigned int data_size = 0;
20602e920715SEwan Crawford     unsigned int padding = 0;
206155232f09SEwan Crawford 
20628b244e21SEwan Crawford     // Element is of a struct type, calculate size recursively.
20638b244e21SEwan Crawford     if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0))
20648b244e21SEwan Crawford     {
20658b244e21SEwan Crawford         for (Element& child : elem.children)
20668b244e21SEwan Crawford         {
20678b244e21SEwan Crawford             SetElementSize(child);
20688b244e21SEwan Crawford             const unsigned int array_size = child.array_size.isValid() ? *child.array_size.get() : 1;
20698b244e21SEwan Crawford             data_size += *child.datum_size.get() * array_size;
20708b244e21SEwan Crawford         }
20718b244e21SEwan Crawford     }
20722e920715SEwan Crawford     else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 || type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
20732e920715SEwan Crawford              type == Element::RS_TYPE_UNSIGNED_4_4_4_4) // These have been packed already
20742e920715SEwan Crawford     {
20752e920715SEwan Crawford         data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
20762e920715SEwan Crawford     }
20772e920715SEwan Crawford     else if (type < Element::RS_TYPE_ELEMENT)
20782e920715SEwan Crawford     {
20798b244e21SEwan Crawford         data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
20802e920715SEwan Crawford         if (vec_size == 3)
20812e920715SEwan Crawford             padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
20822e920715SEwan Crawford     }
20832e920715SEwan Crawford     else
20842e920715SEwan Crawford         data_size = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
20858b244e21SEwan Crawford 
20868b244e21SEwan Crawford     elem.padding = padding;
20878b244e21SEwan Crawford     elem.datum_size = data_size + padding;
20888b244e21SEwan Crawford     if (log)
20898b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::SetElementSize - element size set to %u", data_size + padding);
209055232f09SEwan Crawford }
209155232f09SEwan Crawford 
209255232f09SEwan Crawford // Given an allocation, this function copies the allocation contents from device into a buffer on the heap.
209355232f09SEwan Crawford // Returning a shared pointer to the buffer containing the data.
209455232f09SEwan Crawford std::shared_ptr<uint8_t>
209555232f09SEwan Crawford RenderScriptRuntime::GetAllocationData(AllocationDetails* allocation, StackFrame* frame_ptr)
209655232f09SEwan Crawford {
209755232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
209855232f09SEwan Crawford 
209955232f09SEwan Crawford     // JIT all the allocation details
21008b59062aSEwan Crawford     if (allocation->shouldRefresh())
210155232f09SEwan Crawford     {
210255232f09SEwan Crawford         if (log)
210355232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - Allocation details not calculated yet, jitting info");
210455232f09SEwan Crawford 
210555232f09SEwan Crawford         if (!RefreshAllocation(allocation, frame_ptr))
210655232f09SEwan Crawford         {
210755232f09SEwan Crawford             if (log)
210855232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't JIT allocation details");
210955232f09SEwan Crawford             return nullptr;
211055232f09SEwan Crawford         }
211155232f09SEwan Crawford     }
211255232f09SEwan Crawford 
21138b244e21SEwan Crawford     assert(allocation->data_ptr.isValid() && allocation->element.type.isValid() && allocation->element.type_vec_size.isValid()
211455232f09SEwan Crawford            && allocation->size.isValid() && "Allocation information not available");
211555232f09SEwan Crawford 
211655232f09SEwan Crawford     // Allocate a buffer to copy data into
211755232f09SEwan Crawford     const unsigned int size = *allocation->size.get();
211855232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
211955232f09SEwan Crawford     if (!buffer)
212055232f09SEwan Crawford     {
212155232f09SEwan Crawford         if (log)
212255232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't allocate a %u byte buffer", size);
212355232f09SEwan Crawford         return nullptr;
212455232f09SEwan Crawford     }
212555232f09SEwan Crawford 
212655232f09SEwan Crawford     // Read the inferior memory
212755232f09SEwan Crawford     Error error;
212855232f09SEwan Crawford     lldb::addr_t data_ptr = *allocation->data_ptr.get();
212955232f09SEwan Crawford     GetProcess()->ReadMemory(data_ptr, buffer.get(), size, error);
213055232f09SEwan Crawford     if (error.Fail())
213155232f09SEwan Crawford     {
213255232f09SEwan Crawford         if (log)
213355232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - '%s' Couldn't read %u bytes of allocation data from 0x%" PRIx64,
213455232f09SEwan Crawford                         error.AsCString(), size, data_ptr);
213555232f09SEwan Crawford         return nullptr;
213655232f09SEwan Crawford     }
213755232f09SEwan Crawford 
213855232f09SEwan Crawford     return buffer;
213955232f09SEwan Crawford }
214055232f09SEwan Crawford 
214155232f09SEwan Crawford // Function copies data from a binary file into an allocation.
214255232f09SEwan Crawford // There is a header at the start of the file, FileHeader, before the data content itself.
214355232f09SEwan Crawford // Information from this header is used to display warnings to the user about incompatabilities
214455232f09SEwan Crawford bool
214555232f09SEwan Crawford RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr)
214655232f09SEwan Crawford {
214755232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
214855232f09SEwan Crawford 
214955232f09SEwan Crawford     // Find allocation with the given id
215055232f09SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, alloc_id);
215155232f09SEwan Crawford     if (!alloc)
215255232f09SEwan Crawford         return false;
215355232f09SEwan Crawford 
215455232f09SEwan Crawford     if (log)
215555232f09SEwan Crawford         log->Printf("RenderScriptRuntime::LoadAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
215655232f09SEwan Crawford 
215755232f09SEwan Crawford     // JIT all the allocation details
21588b59062aSEwan Crawford     if (alloc->shouldRefresh())
215955232f09SEwan Crawford     {
216055232f09SEwan Crawford         if (log)
216155232f09SEwan Crawford             log->Printf("RenderScriptRuntime::LoadAllocation - Allocation details not calculated yet, jitting info");
216255232f09SEwan Crawford 
216355232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
216455232f09SEwan Crawford         {
216555232f09SEwan Crawford             if (log)
216655232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::LoadAllocation - Couldn't JIT allocation details");
21674cfc9198SSylvestre Ledru             return false;
216855232f09SEwan Crawford         }
216955232f09SEwan Crawford     }
217055232f09SEwan Crawford 
21718b244e21SEwan Crawford     assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid()
21728b244e21SEwan Crawford            && alloc->size.isValid() && alloc->element.datum_size.isValid() && "Allocation information not available");
217355232f09SEwan Crawford 
217455232f09SEwan Crawford     // Check we can read from file
217555232f09SEwan Crawford     FileSpec file(filename, true);
217655232f09SEwan Crawford     if (!file.Exists())
217755232f09SEwan Crawford     {
217855232f09SEwan Crawford         strm.Printf("Error: File %s does not exist", filename);
217955232f09SEwan Crawford         strm.EOL();
218055232f09SEwan Crawford         return false;
218155232f09SEwan Crawford     }
218255232f09SEwan Crawford 
218355232f09SEwan Crawford     if (!file.Readable())
218455232f09SEwan Crawford     {
218555232f09SEwan Crawford         strm.Printf("Error: File %s does not have readable permissions", filename);
218655232f09SEwan Crawford         strm.EOL();
218755232f09SEwan Crawford         return false;
218855232f09SEwan Crawford     }
218955232f09SEwan Crawford 
219055232f09SEwan Crawford     // Read file into data buffer
219155232f09SEwan Crawford     DataBufferSP data_sp(file.ReadFileContents());
219255232f09SEwan Crawford 
219355232f09SEwan Crawford     // Cast start of buffer to FileHeader and use pointer to read metadata
219455232f09SEwan Crawford     void* file_buffer = data_sp->GetBytes();
219526e52a70SEwan Crawford     if (file_buffer == NULL || data_sp->GetByteSize() <
219626e52a70SEwan Crawford         (sizeof(AllocationDetails::FileHeader) + sizeof(AllocationDetails::ElementHeader)))
219726e52a70SEwan Crawford     {
219826e52a70SEwan Crawford         strm.Printf("Error: File %s does not contain enough data for header", filename);
219926e52a70SEwan Crawford         strm.EOL();
220026e52a70SEwan Crawford         return false;
220126e52a70SEwan Crawford     }
220226e52a70SEwan Crawford     const AllocationDetails::FileHeader* file_header = static_cast<AllocationDetails::FileHeader*>(file_buffer);
220355232f09SEwan Crawford 
220426e52a70SEwan Crawford     // Check file starts with ascii characters "RSAD"
220526e52a70SEwan Crawford     if (file_header->ident[0] != 'R' || file_header->ident[1] != 'S' || file_header->ident[2] != 'A'
220626e52a70SEwan Crawford         || file_header->ident[3] != 'D')
220726e52a70SEwan Crawford     {
220826e52a70SEwan Crawford         strm.Printf("Error: File doesn't contain identifier for an RS allocation dump. Are you sure this is the correct file?");
220926e52a70SEwan Crawford         strm.EOL();
221026e52a70SEwan Crawford         return false;
221126e52a70SEwan Crawford     }
221226e52a70SEwan Crawford 
221326e52a70SEwan Crawford     // Look at the type of the root element in the header
221426e52a70SEwan Crawford     AllocationDetails::ElementHeader root_element_header;
221526e52a70SEwan Crawford     memcpy(&root_element_header, static_cast<uint8_t*>(file_buffer) + sizeof(AllocationDetails::FileHeader),
221626e52a70SEwan Crawford            sizeof(AllocationDetails::ElementHeader));
221755232f09SEwan Crawford 
221855232f09SEwan Crawford     if (log)
221955232f09SEwan Crawford         log->Printf("RenderScriptRuntime::LoadAllocation - header type %u, element size %u",
222026e52a70SEwan Crawford                     root_element_header.type, root_element_header.element_size);
222155232f09SEwan Crawford 
222255232f09SEwan Crawford     // Check if the target allocation and file both have the same number of bytes for an Element
222326e52a70SEwan Crawford     if (*alloc->element.datum_size.get() != root_element_header.element_size)
222455232f09SEwan Crawford     {
222555232f09SEwan Crawford         strm.Printf("Warning: Mismatched Element sizes - file %u bytes, allocation %u bytes",
222626e52a70SEwan Crawford                     root_element_header.element_size, *alloc->element.datum_size.get());
222755232f09SEwan Crawford         strm.EOL();
222855232f09SEwan Crawford     }
222955232f09SEwan Crawford 
223026e52a70SEwan Crawford     // Check if the target allocation and file both have the same type
223126e52a70SEwan Crawford     const unsigned int alloc_type = static_cast<unsigned int>(*alloc->element.type.get());
223226e52a70SEwan Crawford     const unsigned int file_type = root_element_header.type;
223326e52a70SEwan Crawford 
223426e52a70SEwan Crawford     if (file_type > Element::RS_TYPE_FONT)
223526e52a70SEwan Crawford     {
223626e52a70SEwan Crawford         strm.Printf("Warning: File has unknown allocation type");
223726e52a70SEwan Crawford         strm.EOL();
223826e52a70SEwan Crawford     }
223926e52a70SEwan Crawford     else if (alloc_type != file_type)
224055232f09SEwan Crawford     {
22412e920715SEwan Crawford         // Enum value isn't monotonous, so doesn't always index RsDataTypeToString array
224226e52a70SEwan Crawford         unsigned int printable_target_type_index = alloc_type;
224326e52a70SEwan Crawford         unsigned int printable_head_type_index = file_type;
224426e52a70SEwan Crawford         if (alloc_type >= Element::RS_TYPE_ELEMENT && alloc_type <= Element::RS_TYPE_FONT)
22452e920715SEwan Crawford             printable_target_type_index = static_cast<Element::DataType>(
224626e52a70SEwan Crawford                                          (alloc_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 + 1);
22472e920715SEwan Crawford 
224826e52a70SEwan Crawford         if (file_type >= Element::RS_TYPE_ELEMENT && file_type <= Element::RS_TYPE_FONT)
22492e920715SEwan Crawford             printable_head_type_index = static_cast<Element::DataType>(
225026e52a70SEwan Crawford                                         (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 + 1);
22512e920715SEwan Crawford 
22522e920715SEwan Crawford         const char* file_type_cstr = AllocationDetails::RsDataTypeToString[printable_head_type_index][0];
22532e920715SEwan Crawford         const char* target_type_cstr = AllocationDetails::RsDataTypeToString[printable_target_type_index][0];
225455232f09SEwan Crawford 
225555232f09SEwan Crawford         strm.Printf("Warning: Mismatched Types - file '%s' type, allocation '%s' type",
22562e920715SEwan Crawford                     file_type_cstr, target_type_cstr);
225755232f09SEwan Crawford         strm.EOL();
225855232f09SEwan Crawford     }
225955232f09SEwan Crawford 
226026e52a70SEwan Crawford     // Advance buffer past header
226126e52a70SEwan Crawford     file_buffer = static_cast<uint8_t*>(file_buffer) + file_header->hdr_size;
226226e52a70SEwan Crawford 
226355232f09SEwan Crawford     // Calculate size of allocation data in file
226426e52a70SEwan Crawford     size_t length = data_sp->GetByteSize() - file_header->hdr_size;
226555232f09SEwan Crawford 
226655232f09SEwan Crawford     // Check if the target allocation and file both have the same total data size.
226755232f09SEwan Crawford     const unsigned int alloc_size = *alloc->size.get();
226855232f09SEwan Crawford     if (alloc_size != length)
226955232f09SEwan Crawford     {
227055232f09SEwan Crawford         strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64 " bytes, allocation 0x%x bytes",
2271eba832beSJason Molenda                     (uint64_t) length, alloc_size);
227255232f09SEwan Crawford         strm.EOL();
227355232f09SEwan Crawford         length = alloc_size < length ? alloc_size : length; // Set length to copy to minimum
227455232f09SEwan Crawford     }
227555232f09SEwan Crawford 
227655232f09SEwan Crawford     // Copy file data from our buffer into the target allocation.
227755232f09SEwan Crawford     lldb::addr_t alloc_data = *alloc->data_ptr.get();
227855232f09SEwan Crawford     Error error;
227955232f09SEwan Crawford     size_t bytes_written = GetProcess()->WriteMemory(alloc_data, file_buffer, length, error);
228055232f09SEwan Crawford     if (!error.Success() || bytes_written != length)
228155232f09SEwan Crawford     {
228255232f09SEwan Crawford         strm.Printf("Error: Couldn't write data to allocation %s", error.AsCString());
228355232f09SEwan Crawford         strm.EOL();
228455232f09SEwan Crawford         return false;
228555232f09SEwan Crawford     }
228655232f09SEwan Crawford 
228755232f09SEwan Crawford     strm.Printf("Contents of file '%s' read into allocation %u", filename, alloc->id);
228855232f09SEwan Crawford     strm.EOL();
228955232f09SEwan Crawford 
229055232f09SEwan Crawford     return true;
229155232f09SEwan Crawford }
229255232f09SEwan Crawford 
229326e52a70SEwan Crawford // Function takes as parameters a byte buffer, which will eventually be written to file as the element header,
229426e52a70SEwan Crawford // an offset into that buffer, and an Element that will be saved into the buffer at the parametrised offset.
229526e52a70SEwan Crawford // Return value is the new offset after writing the element into the buffer.
229626e52a70SEwan Crawford // Elements are saved to the file as the ElementHeader struct followed by offsets to the structs of all the element's children.
229726e52a70SEwan Crawford size_t
229826e52a70SEwan Crawford RenderScriptRuntime::PopulateElementHeaders(const std::shared_ptr<uint8_t> header_buffer, size_t offset, const Element& elem)
229926e52a70SEwan Crawford {
230026e52a70SEwan Crawford     // File struct for an element header with all the relevant details copied from elem.
230126e52a70SEwan Crawford     // We assume members are valid already.
230226e52a70SEwan Crawford     AllocationDetails::ElementHeader elem_header;
230326e52a70SEwan Crawford     elem_header.type = *elem.type.get();
230426e52a70SEwan Crawford     elem_header.kind = *elem.type_kind.get();
230526e52a70SEwan Crawford     elem_header.element_size = *elem.datum_size.get();
230626e52a70SEwan Crawford     elem_header.vector_size = *elem.type_vec_size.get();
230726e52a70SEwan Crawford     elem_header.array_size = elem.array_size.isValid() ? *elem.array_size.get() : 0;
230826e52a70SEwan Crawford     const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
230926e52a70SEwan Crawford 
231026e52a70SEwan Crawford     // Copy struct into buffer and advance offset
231126e52a70SEwan Crawford     // We assume that header_buffer has been checked for NULL before this method is called
231226e52a70SEwan Crawford     memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
231326e52a70SEwan Crawford     offset += elem_header_size;
231426e52a70SEwan Crawford 
231526e52a70SEwan Crawford     // Starting offset of child ElementHeader struct
231626e52a70SEwan Crawford     size_t child_offset = offset + ((elem.children.size() + 1) * sizeof(uint32_t));
231726e52a70SEwan Crawford     for (const RenderScriptRuntime::Element& child : elem.children)
231826e52a70SEwan Crawford     {
231926e52a70SEwan Crawford         // Recursively populate the buffer with the element header structs of children.
232026e52a70SEwan Crawford         // Then save the offsets where they were set after the parent element header.
232126e52a70SEwan Crawford         memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
232226e52a70SEwan Crawford         offset += sizeof(uint32_t);
232326e52a70SEwan Crawford 
232426e52a70SEwan Crawford         child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
232526e52a70SEwan Crawford     }
232626e52a70SEwan Crawford 
232726e52a70SEwan Crawford     // Zero indicates no more children
232826e52a70SEwan Crawford     memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
232926e52a70SEwan Crawford 
233026e52a70SEwan Crawford     return child_offset;
233126e52a70SEwan Crawford }
233226e52a70SEwan Crawford 
233326e52a70SEwan Crawford // Given an Element object this function returns the total size needed in the file header to store the element's details.
233426e52a70SEwan Crawford // Taking into account the size of the element header struct, plus the offsets to all the element's children.
233526e52a70SEwan Crawford // Function is recursive so that the size of all ancestors is taken into account.
233626e52a70SEwan Crawford size_t
233726e52a70SEwan Crawford RenderScriptRuntime::CalculateElementHeaderSize(const Element& elem)
233826e52a70SEwan Crawford {
233926e52a70SEwan Crawford     size_t size = (elem.children.size() + 1) * sizeof(uint32_t); // Offsets to children plus zero terminator
234026e52a70SEwan Crawford     size += sizeof(AllocationDetails::ElementHeader); // Size of header struct with type details
234126e52a70SEwan Crawford 
234226e52a70SEwan Crawford     // Calculate recursively for all descendants
234326e52a70SEwan Crawford     for (const Element& child : elem.children)
234426e52a70SEwan Crawford         size += CalculateElementHeaderSize(child);
234526e52a70SEwan Crawford 
234626e52a70SEwan Crawford     return size;
234726e52a70SEwan Crawford }
234826e52a70SEwan Crawford 
234955232f09SEwan Crawford // Function copies allocation contents into a binary file.
235055232f09SEwan Crawford // This file can then be loaded later into a different allocation.
235155232f09SEwan Crawford // There is a header, FileHeader, before the allocation data containing meta-data.
235255232f09SEwan Crawford bool
235355232f09SEwan Crawford RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr)
235455232f09SEwan Crawford {
235555232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
235655232f09SEwan Crawford 
235755232f09SEwan Crawford     // Find allocation with the given id
235855232f09SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, alloc_id);
235955232f09SEwan Crawford     if (!alloc)
236055232f09SEwan Crawford         return false;
236155232f09SEwan Crawford 
236255232f09SEwan Crawford     if (log)
236355232f09SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
236455232f09SEwan Crawford 
236555232f09SEwan Crawford      // JIT all the allocation details
23668b59062aSEwan Crawford     if (alloc->shouldRefresh())
236755232f09SEwan Crawford     {
236855232f09SEwan Crawford         if (log)
236955232f09SEwan Crawford             log->Printf("RenderScriptRuntime::SaveAllocation - Allocation details not calculated yet, jitting info");
237055232f09SEwan Crawford 
237155232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
237255232f09SEwan Crawford         {
237355232f09SEwan Crawford             if (log)
237455232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::SaveAllocation - Couldn't JIT allocation details");
23754cfc9198SSylvestre Ledru             return false;
237655232f09SEwan Crawford         }
237755232f09SEwan Crawford     }
237855232f09SEwan Crawford 
23798b244e21SEwan Crawford     assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid() && alloc->element.datum_size.get()
23808b244e21SEwan Crawford            && alloc->element.type_kind.isValid() && alloc->dimension.isValid() && "Allocation information not available");
238155232f09SEwan Crawford 
238255232f09SEwan Crawford     // Check we can create writable file
238355232f09SEwan Crawford     FileSpec file_spec(filename, true);
238455232f09SEwan Crawford     File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionTruncate);
238555232f09SEwan Crawford     if (!file)
238655232f09SEwan Crawford     {
238755232f09SEwan Crawford         strm.Printf("Error: Failed to open '%s' for writing", filename);
238855232f09SEwan Crawford         strm.EOL();
238955232f09SEwan Crawford         return false;
239055232f09SEwan Crawford     }
239155232f09SEwan Crawford 
239255232f09SEwan Crawford     // Read allocation into buffer of heap memory
239355232f09SEwan Crawford     const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
239455232f09SEwan Crawford     if (!buffer)
239555232f09SEwan Crawford     {
239655232f09SEwan Crawford         strm.Printf("Error: Couldn't read allocation data into buffer");
239755232f09SEwan Crawford         strm.EOL();
239855232f09SEwan Crawford         return false;
239955232f09SEwan Crawford     }
240055232f09SEwan Crawford 
240155232f09SEwan Crawford     // Create the file header
240255232f09SEwan Crawford     AllocationDetails::FileHeader head;
240355232f09SEwan Crawford     head.ident[0] = 'R'; head.ident[1] = 'S'; head.ident[2] = 'A'; head.ident[3] = 'D';
24042d62328aSEwan Crawford     head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
24052d62328aSEwan Crawford     head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
24062d62328aSEwan Crawford     head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
240726e52a70SEwan Crawford 
240826e52a70SEwan Crawford     const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
240926e52a70SEwan Crawford     assert((sizeof(AllocationDetails::FileHeader) + element_header_size) < UINT16_MAX && "Element header too large");
241026e52a70SEwan Crawford     head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) + element_header_size);
241155232f09SEwan Crawford 
241255232f09SEwan Crawford     // Write the file header
241355232f09SEwan Crawford     size_t num_bytes = sizeof(AllocationDetails::FileHeader);
241426e52a70SEwan Crawford     if (log)
241526e52a70SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Writing File Header, 0x%zX bytes", num_bytes);
241626e52a70SEwan Crawford 
241726e52a70SEwan Crawford     Error err = file.Write(&head, num_bytes);
241826e52a70SEwan Crawford     if (!err.Success())
241926e52a70SEwan Crawford     {
242026e52a70SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
242126e52a70SEwan Crawford         strm.EOL();
242226e52a70SEwan Crawford         return false;
242326e52a70SEwan Crawford     }
242426e52a70SEwan Crawford 
242526e52a70SEwan Crawford     // Create the headers describing the element type of the allocation.
242626e52a70SEwan Crawford     std::shared_ptr<uint8_t> element_header_buffer(new uint8_t[element_header_size]);
242726e52a70SEwan Crawford     if (element_header_buffer == nullptr)
242826e52a70SEwan Crawford     {
242926e52a70SEwan Crawford         strm.Printf("Internal Error: Couldn't allocate %zu bytes on the heap", element_header_size);
243026e52a70SEwan Crawford         strm.EOL();
243126e52a70SEwan Crawford         return false;
243226e52a70SEwan Crawford     }
243326e52a70SEwan Crawford 
243426e52a70SEwan Crawford     PopulateElementHeaders(element_header_buffer, 0, alloc->element);
243526e52a70SEwan Crawford 
243626e52a70SEwan Crawford     // Write headers for allocation element type to file
243726e52a70SEwan Crawford     num_bytes = element_header_size;
243826e52a70SEwan Crawford     if (log)
243926e52a70SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Writing Element Headers, 0x%zX bytes", num_bytes);
244026e52a70SEwan Crawford 
244126e52a70SEwan Crawford     err = file.Write(element_header_buffer.get(), num_bytes);
244255232f09SEwan Crawford     if (!err.Success())
244355232f09SEwan Crawford     {
244455232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
244555232f09SEwan Crawford         strm.EOL();
244655232f09SEwan Crawford         return false;
244755232f09SEwan Crawford     }
244855232f09SEwan Crawford 
244955232f09SEwan Crawford     // Write allocation data to file
245055232f09SEwan Crawford     num_bytes = static_cast<size_t>(*alloc->size.get());
245155232f09SEwan Crawford     if (log)
245226e52a70SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Writing 0x%zX bytes", num_bytes);
245355232f09SEwan Crawford 
245455232f09SEwan Crawford     err = file.Write(buffer.get(), num_bytes);
245555232f09SEwan Crawford     if (!err.Success())
245655232f09SEwan Crawford     {
245755232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
245855232f09SEwan Crawford         strm.EOL();
245955232f09SEwan Crawford         return false;
246055232f09SEwan Crawford     }
246155232f09SEwan Crawford 
246255232f09SEwan Crawford     strm.Printf("Allocation written to file '%s'", filename);
246355232f09SEwan Crawford     strm.EOL();
246415f2bd95SEwan Crawford     return true;
246515f2bd95SEwan Crawford }
246615f2bd95SEwan Crawford 
24675ec532a9SColin Riley bool
24685ec532a9SColin Riley RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp)
24695ec532a9SColin Riley {
24704640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
24714640cde1SColin Riley 
24725ec532a9SColin Riley     if (module_sp)
24735ec532a9SColin Riley     {
24745ec532a9SColin Riley         for (const auto &rs_module : m_rsmodules)
24755ec532a9SColin Riley         {
24764640cde1SColin Riley             if (rs_module->m_module == module_sp)
24777dc7771cSEwan Crawford             {
24787dc7771cSEwan Crawford                 // Check if the user has enabled automatically breaking on
24797dc7771cSEwan Crawford                 // all RS kernels.
24807dc7771cSEwan Crawford                 if (m_breakAllKernels)
24817dc7771cSEwan Crawford                     BreakOnModuleKernels(rs_module);
24827dc7771cSEwan Crawford 
24835ec532a9SColin Riley                 return false;
24845ec532a9SColin Riley             }
24857dc7771cSEwan Crawford         }
2486ef20b08fSColin Riley         bool module_loaded = false;
2487ef20b08fSColin Riley         switch (GetModuleKind(module_sp))
2488ef20b08fSColin Riley         {
2489ef20b08fSColin Riley             case eModuleKindKernelObj:
2490ef20b08fSColin Riley             {
24914640cde1SColin Riley                 RSModuleDescriptorSP module_desc;
24924640cde1SColin Riley                 module_desc.reset(new RSModuleDescriptor(module_sp));
24934640cde1SColin Riley                 if (module_desc->ParseRSInfo())
24945ec532a9SColin Riley                 {
24955ec532a9SColin Riley                     m_rsmodules.push_back(module_desc);
2496ef20b08fSColin Riley                     module_loaded = true;
24975ec532a9SColin Riley                 }
24984640cde1SColin Riley                 if (module_loaded)
24994640cde1SColin Riley                 {
25004640cde1SColin Riley                     FixupScriptDetails(module_desc);
25014640cde1SColin Riley                 }
2502ef20b08fSColin Riley                 break;
2503ef20b08fSColin Riley             }
2504ef20b08fSColin Riley             case eModuleKindDriver:
25054640cde1SColin Riley             {
25064640cde1SColin Riley                 if (!m_libRSDriver)
25074640cde1SColin Riley                 {
25084640cde1SColin Riley                     m_libRSDriver = module_sp;
25094640cde1SColin Riley                     LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
25104640cde1SColin Riley                 }
25114640cde1SColin Riley                 break;
25124640cde1SColin Riley             }
2513ef20b08fSColin Riley             case eModuleKindImpl:
25144640cde1SColin Riley             {
25154640cde1SColin Riley                 m_libRSCpuRef = module_sp;
25164640cde1SColin Riley                 break;
25174640cde1SColin Riley             }
2518ef20b08fSColin Riley             case eModuleKindLibRS:
25194640cde1SColin Riley             {
25204640cde1SColin Riley                 if (!m_libRS)
25214640cde1SColin Riley                 {
25224640cde1SColin Riley                     m_libRS = module_sp;
25234640cde1SColin Riley                     static ConstString gDbgPresentStr("gDebuggerPresent");
25244640cde1SColin Riley                     const Symbol* debug_present = m_libRS->FindFirstSymbolWithNameAndType(gDbgPresentStr, eSymbolTypeData);
25254640cde1SColin Riley                     if (debug_present)
25264640cde1SColin Riley                     {
25274640cde1SColin Riley                         Error error;
25284640cde1SColin Riley                         uint32_t flag = 0x00000001U;
25294640cde1SColin Riley                         Target &target = GetProcess()->GetTarget();
2530358cf1eaSGreg Clayton                         addr_t addr = debug_present->GetLoadAddress(&target);
25314640cde1SColin Riley                         GetProcess()->WriteMemory(addr, &flag, sizeof(flag), error);
25324640cde1SColin Riley                         if(error.Success())
25334640cde1SColin Riley                         {
25344640cde1SColin Riley                             if (log)
25354640cde1SColin Riley                                 log->Printf ("RenderScriptRuntime::LoadModule - Debugger present flag set on debugee");
25364640cde1SColin Riley 
25374640cde1SColin Riley                             m_debuggerPresentFlagged = true;
25384640cde1SColin Riley                         }
25394640cde1SColin Riley                         else if (log)
25404640cde1SColin Riley                         {
25414640cde1SColin Riley                             log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags '%s' ", error.AsCString());
25424640cde1SColin Riley                         }
25434640cde1SColin Riley                     }
25444640cde1SColin Riley                     else if (log)
25454640cde1SColin Riley                     {
25464640cde1SColin Riley                         log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags - symbol not found");
25474640cde1SColin Riley                     }
25484640cde1SColin Riley                 }
25494640cde1SColin Riley                 break;
25504640cde1SColin Riley             }
2551ef20b08fSColin Riley             default:
2552ef20b08fSColin Riley                 break;
2553ef20b08fSColin Riley         }
2554ef20b08fSColin Riley         if (module_loaded)
2555ef20b08fSColin Riley             Update();
2556ef20b08fSColin Riley         return module_loaded;
25575ec532a9SColin Riley     }
25585ec532a9SColin Riley     return false;
25595ec532a9SColin Riley }
25605ec532a9SColin Riley 
2561ef20b08fSColin Riley void
2562ef20b08fSColin Riley RenderScriptRuntime::Update()
2563ef20b08fSColin Riley {
2564ef20b08fSColin Riley     if (m_rsmodules.size() > 0)
2565ef20b08fSColin Riley     {
2566ef20b08fSColin Riley         if (!m_initiated)
2567ef20b08fSColin Riley         {
2568ef20b08fSColin Riley             Initiate();
2569ef20b08fSColin Riley         }
2570ef20b08fSColin Riley     }
2571ef20b08fSColin Riley }
2572ef20b08fSColin Riley 
25735ec532a9SColin Riley // The maximum line length of an .rs.info packet
25745ec532a9SColin Riley #define MAXLINE 500
25755ec532a9SColin Riley 
25765ec532a9SColin Riley // The .rs.info symbol in renderscript modules contains a string which needs to be parsed.
25775ec532a9SColin Riley // The string is basic and is parsed on a line by line basis.
25785ec532a9SColin Riley bool
25795ec532a9SColin Riley RSModuleDescriptor::ParseRSInfo()
25805ec532a9SColin Riley {
25815ec532a9SColin Riley     const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
25825ec532a9SColin Riley     if (info_sym)
25835ec532a9SColin Riley     {
2584358cf1eaSGreg Clayton         const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
25855ec532a9SColin Riley         const addr_t size = info_sym->GetByteSize();
25865ec532a9SColin Riley         const FileSpec fs = m_module->GetFileSpec();
25875ec532a9SColin Riley 
25885ec532a9SColin Riley         DataBufferSP buffer = fs.ReadFileContents(addr, size);
25895ec532a9SColin Riley 
25905ec532a9SColin Riley         if (!buffer)
25915ec532a9SColin Riley             return false;
25925ec532a9SColin Riley 
25935ec532a9SColin Riley         std::string info((const char *)buffer->GetBytes());
25945ec532a9SColin Riley 
25955ec532a9SColin Riley         std::vector<std::string> info_lines;
2596e8433cc1SBruce Mitchener         size_t lpos = info.find('\n');
25975ec532a9SColin Riley         while (lpos != std::string::npos)
25985ec532a9SColin Riley         {
25995ec532a9SColin Riley             info_lines.push_back(info.substr(0, lpos));
26005ec532a9SColin Riley             info = info.substr(lpos + 1);
2601e8433cc1SBruce Mitchener             lpos = info.find('\n');
26025ec532a9SColin Riley         }
26035ec532a9SColin Riley         size_t offset = 0;
26045ec532a9SColin Riley         while (offset < info_lines.size())
26055ec532a9SColin Riley         {
26065ec532a9SColin Riley             std::string line = info_lines[offset];
26075ec532a9SColin Riley             // Parse directives
26085ec532a9SColin Riley             uint32_t numDefns = 0;
26095ec532a9SColin Riley             if (sscanf(line.c_str(), "exportVarCount: %u", &numDefns) == 1)
26105ec532a9SColin Riley             {
26115ec532a9SColin Riley                 while (numDefns--)
26124640cde1SColin Riley                     m_globals.push_back(RSGlobalDescriptor(this, info_lines[++offset].c_str()));
26135ec532a9SColin Riley             }
26145ec532a9SColin Riley             else if (sscanf(line.c_str(), "exportFuncCount: %u", &numDefns) == 1)
26155ec532a9SColin Riley             {
26165ec532a9SColin Riley             }
26175ec532a9SColin Riley             else if (sscanf(line.c_str(), "exportForEachCount: %u", &numDefns) == 1)
26185ec532a9SColin Riley             {
26195ec532a9SColin Riley                 char name[MAXLINE];
26205ec532a9SColin Riley                 while (numDefns--)
26215ec532a9SColin Riley                 {
26225ec532a9SColin Riley                     uint32_t slot = 0;
26235ec532a9SColin Riley                     name[0] = '\0';
26245ec532a9SColin Riley                     if (sscanf(info_lines[++offset].c_str(), "%u - %s", &slot, &name[0]) == 2)
26255ec532a9SColin Riley                     {
26264640cde1SColin Riley                         m_kernels.push_back(RSKernelDescriptor(this, name, slot));
26274640cde1SColin Riley                     }
26284640cde1SColin Riley                 }
26294640cde1SColin Riley             }
26304640cde1SColin Riley             else if (sscanf(line.c_str(), "pragmaCount: %u", &numDefns) == 1)
26314640cde1SColin Riley             {
26324640cde1SColin Riley                 char name[MAXLINE];
26334640cde1SColin Riley                 char value[MAXLINE];
26344640cde1SColin Riley                 while (numDefns--)
26354640cde1SColin Riley                 {
26364640cde1SColin Riley                     name[0] = '\0';
26374640cde1SColin Riley                     value[0] = '\0';
26384640cde1SColin Riley                     if (sscanf(info_lines[++offset].c_str(), "%s - %s", &name[0], &value[0]) != 0
26394640cde1SColin Riley                         && (name[0] != '\0'))
26404640cde1SColin Riley                     {
26414640cde1SColin Riley                         m_pragmas[std::string(name)] = value;
26425ec532a9SColin Riley                     }
26435ec532a9SColin Riley                 }
26445ec532a9SColin Riley             }
26455ec532a9SColin Riley             else if (sscanf(line.c_str(), "objectSlotCount: %u", &numDefns) == 1)
26465ec532a9SColin Riley             {
26475ec532a9SColin Riley             }
26485ec532a9SColin Riley 
26495ec532a9SColin Riley             offset++;
26505ec532a9SColin Riley         }
26515ec532a9SColin Riley         return m_kernels.size() > 0;
26525ec532a9SColin Riley     }
26535ec532a9SColin Riley     return false;
26545ec532a9SColin Riley }
26555ec532a9SColin Riley 
26565ec532a9SColin Riley bool
26575ec532a9SColin Riley RenderScriptRuntime::ProbeModules(const ModuleList module_list)
26585ec532a9SColin Riley {
26595ec532a9SColin Riley     bool rs_found = false;
26605ec532a9SColin Riley     size_t num_modules = module_list.GetSize();
26615ec532a9SColin Riley     for (size_t i = 0; i < num_modules; i++)
26625ec532a9SColin Riley     {
26635ec532a9SColin Riley         auto module = module_list.GetModuleAtIndex(i);
26645ec532a9SColin Riley         rs_found |= LoadModule(module);
26655ec532a9SColin Riley     }
26665ec532a9SColin Riley     return rs_found;
26675ec532a9SColin Riley }
26685ec532a9SColin Riley 
26695ec532a9SColin Riley void
26704640cde1SColin Riley RenderScriptRuntime::Status(Stream &strm) const
26714640cde1SColin Riley {
26724640cde1SColin Riley     if (m_libRS)
26734640cde1SColin Riley     {
26744640cde1SColin Riley         strm.Printf("Runtime Library discovered.");
26754640cde1SColin Riley         strm.EOL();
26764640cde1SColin Riley     }
26774640cde1SColin Riley     if (m_libRSDriver)
26784640cde1SColin Riley     {
26794640cde1SColin Riley         strm.Printf("Runtime Driver discovered.");
26804640cde1SColin Riley         strm.EOL();
26814640cde1SColin Riley     }
26824640cde1SColin Riley     if (m_libRSCpuRef)
26834640cde1SColin Riley     {
26844640cde1SColin Riley         strm.Printf("CPU Reference Implementation discovered.");
26854640cde1SColin Riley         strm.EOL();
26864640cde1SColin Riley     }
26874640cde1SColin Riley 
26884640cde1SColin Riley     if (m_runtimeHooks.size())
26894640cde1SColin Riley     {
26904640cde1SColin Riley         strm.Printf("Runtime functions hooked:");
26914640cde1SColin Riley         strm.EOL();
26924640cde1SColin Riley         for (auto b : m_runtimeHooks)
26934640cde1SColin Riley         {
26944640cde1SColin Riley             strm.Indent(b.second->defn->name);
26954640cde1SColin Riley             strm.EOL();
26964640cde1SColin Riley         }
26974640cde1SColin Riley     }
26984640cde1SColin Riley     else
26994640cde1SColin Riley     {
27004640cde1SColin Riley         strm.Printf("Runtime is not hooked.");
27014640cde1SColin Riley         strm.EOL();
27024640cde1SColin Riley     }
27034640cde1SColin Riley }
27044640cde1SColin Riley 
27054640cde1SColin Riley void
27064640cde1SColin Riley RenderScriptRuntime::DumpContexts(Stream &strm) const
27074640cde1SColin Riley {
27084640cde1SColin Riley     strm.Printf("Inferred RenderScript Contexts:");
27094640cde1SColin Riley     strm.EOL();
27104640cde1SColin Riley     strm.IndentMore();
27114640cde1SColin Riley 
27124640cde1SColin Riley     std::map<addr_t, uint64_t> contextReferences;
27134640cde1SColin Riley 
271478f339d1SEwan Crawford     // Iterate over all of the currently discovered scripts.
271578f339d1SEwan Crawford     // Note: We cant push or pop from m_scripts inside this loop or it may invalidate script.
27164640cde1SColin Riley     for (const auto & script : m_scripts)
27174640cde1SColin Riley     {
271878f339d1SEwan Crawford         if (!script->context.isValid())
271978f339d1SEwan Crawford             continue;
272078f339d1SEwan Crawford         lldb::addr_t context = *script->context;
272178f339d1SEwan Crawford 
272278f339d1SEwan Crawford         if (contextReferences.find(context) != contextReferences.end())
27234640cde1SColin Riley         {
272478f339d1SEwan Crawford             contextReferences[context]++;
27254640cde1SColin Riley         }
27264640cde1SColin Riley         else
27274640cde1SColin Riley         {
272878f339d1SEwan Crawford             contextReferences[context] = 1;
27294640cde1SColin Riley         }
27304640cde1SColin Riley     }
27314640cde1SColin Riley 
27324640cde1SColin Riley     for (const auto& cRef : contextReferences)
27334640cde1SColin Riley     {
27344640cde1SColin Riley         strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances", cRef.first, cRef.second);
27354640cde1SColin Riley         strm.EOL();
27364640cde1SColin Riley     }
27374640cde1SColin Riley     strm.IndentLess();
27384640cde1SColin Riley }
27394640cde1SColin Riley 
27404640cde1SColin Riley void
27414640cde1SColin Riley RenderScriptRuntime::DumpKernels(Stream &strm) const
27424640cde1SColin Riley {
27434640cde1SColin Riley     strm.Printf("RenderScript Kernels:");
27444640cde1SColin Riley     strm.EOL();
27454640cde1SColin Riley     strm.IndentMore();
27464640cde1SColin Riley     for (const auto &module : m_rsmodules)
27474640cde1SColin Riley     {
27484640cde1SColin Riley         strm.Printf("Resource '%s':",module->m_resname.c_str());
27494640cde1SColin Riley         strm.EOL();
27504640cde1SColin Riley         for (const auto &kernel : module->m_kernels)
27514640cde1SColin Riley         {
27524640cde1SColin Riley             strm.Indent(kernel.m_name.AsCString());
27534640cde1SColin Riley             strm.EOL();
27544640cde1SColin Riley         }
27554640cde1SColin Riley     }
27564640cde1SColin Riley     strm.IndentLess();
27574640cde1SColin Riley }
27584640cde1SColin Riley 
2759a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails*
2760a0f08674SEwan Crawford RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id)
2761a0f08674SEwan Crawford {
2762a0f08674SEwan Crawford     AllocationDetails* alloc = nullptr;
2763a0f08674SEwan Crawford 
2764a0f08674SEwan Crawford     // See if we can find allocation using id as an index;
2765a0f08674SEwan Crawford     if (alloc_id <= m_allocations.size() && alloc_id != 0
2766a0f08674SEwan Crawford         && m_allocations[alloc_id-1]->id == alloc_id)
2767a0f08674SEwan Crawford     {
2768a0f08674SEwan Crawford         alloc = m_allocations[alloc_id-1].get();
2769a0f08674SEwan Crawford         return alloc;
2770a0f08674SEwan Crawford     }
2771a0f08674SEwan Crawford 
2772a0f08674SEwan Crawford     // Fallback to searching
2773a0f08674SEwan Crawford     for (const auto & a : m_allocations)
2774a0f08674SEwan Crawford     {
2775a0f08674SEwan Crawford        if (a->id == alloc_id)
2776a0f08674SEwan Crawford        {
2777a0f08674SEwan Crawford            alloc = a.get();
2778a0f08674SEwan Crawford            break;
2779a0f08674SEwan Crawford        }
2780a0f08674SEwan Crawford     }
2781a0f08674SEwan Crawford 
2782a0f08674SEwan Crawford     if (alloc == nullptr)
2783a0f08674SEwan Crawford     {
2784a0f08674SEwan Crawford         strm.Printf("Error: Couldn't find allocation with id matching %u", alloc_id);
2785a0f08674SEwan Crawford         strm.EOL();
2786a0f08674SEwan Crawford     }
2787a0f08674SEwan Crawford 
2788a0f08674SEwan Crawford     return alloc;
2789a0f08674SEwan Crawford }
2790a0f08674SEwan Crawford 
2791a0f08674SEwan Crawford // Prints the contents of an allocation to the output stream, which may be a file
2792a0f08674SEwan Crawford bool
2793a0f08674SEwan Crawford RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame* frame_ptr, const uint32_t id)
2794a0f08674SEwan Crawford {
2795a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2796a0f08674SEwan Crawford 
2797a0f08674SEwan Crawford     // Check we can find the desired allocation
2798a0f08674SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, id);
2799a0f08674SEwan Crawford     if (!alloc)
2800a0f08674SEwan Crawford         return false; // FindAllocByID() will print error message for us here
2801a0f08674SEwan Crawford 
2802a0f08674SEwan Crawford     if (log)
2803a0f08674SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
2804a0f08674SEwan Crawford 
2805a0f08674SEwan Crawford     // Check we have information about the allocation, if not calculate it
28068b59062aSEwan Crawford     if (alloc->shouldRefresh())
2807a0f08674SEwan Crawford     {
2808a0f08674SEwan Crawford         if (log)
2809a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::DumpAllocation - Allocation details not calculated yet, jitting info");
2810a0f08674SEwan Crawford 
2811a0f08674SEwan Crawford         // JIT all the allocation information
2812a0f08674SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
2813a0f08674SEwan Crawford         {
2814a0f08674SEwan Crawford             strm.Printf("Error: Couldn't JIT allocation details");
2815a0f08674SEwan Crawford             strm.EOL();
2816a0f08674SEwan Crawford             return false;
2817a0f08674SEwan Crawford         }
2818a0f08674SEwan Crawford     }
2819a0f08674SEwan Crawford 
2820a0f08674SEwan Crawford     // Establish format and size of each data element
28218b244e21SEwan Crawford     const unsigned int vec_size = *alloc->element.type_vec_size.get();
28228b244e21SEwan Crawford     const Element::DataType type = *alloc->element.type.get();
2823a0f08674SEwan Crawford 
28242e920715SEwan Crawford     assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT
2825a0f08674SEwan Crawford                                                    && "Invalid allocation type");
2826a0f08674SEwan Crawford 
28272e920715SEwan Crawford     lldb::Format format;
28282e920715SEwan Crawford     if (type >= Element::RS_TYPE_ELEMENT)
28292e920715SEwan Crawford         format = eFormatHex;
28302e920715SEwan Crawford     else
28312e920715SEwan Crawford         format = vec_size == 1 ? static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatSingle])
2832a0f08674SEwan Crawford                                : static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatVector]);
2833a0f08674SEwan Crawford 
28348b244e21SEwan Crawford     const unsigned int data_size = *alloc->element.datum_size.get();
2835a0f08674SEwan Crawford 
2836a0f08674SEwan Crawford     if (log)
28378b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - Element size %u bytes, including padding", data_size);
2838a0f08674SEwan Crawford 
283955232f09SEwan Crawford     // Allocate a buffer to copy data into
284055232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
284155232f09SEwan Crawford     if (!buffer)
284255232f09SEwan Crawford     {
28432e920715SEwan Crawford         strm.Printf("Error: Couldn't read allocation data");
284455232f09SEwan Crawford         strm.EOL();
284555232f09SEwan Crawford         return false;
284655232f09SEwan Crawford     }
284755232f09SEwan Crawford 
2848a0f08674SEwan Crawford     // Calculate stride between rows as there may be padding at end of rows since
2849a0f08674SEwan Crawford     // allocated memory is 16-byte aligned
2850a0f08674SEwan Crawford     if (!alloc->stride.isValid())
2851a0f08674SEwan Crawford     {
2852a0f08674SEwan Crawford         if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
2853a0f08674SEwan Crawford             alloc->stride = 0;
2854a0f08674SEwan Crawford         else if (!JITAllocationStride(alloc, frame_ptr))
2855a0f08674SEwan Crawford         {
2856a0f08674SEwan Crawford             strm.Printf("Error: Couldn't calculate allocation row stride");
2857a0f08674SEwan Crawford             strm.EOL();
2858a0f08674SEwan Crawford             return false;
2859a0f08674SEwan Crawford         }
2860a0f08674SEwan Crawford     }
2861a0f08674SEwan Crawford     const unsigned int stride = *alloc->stride.get();
28628b244e21SEwan Crawford     const unsigned int size = *alloc->size.get(); // Size of whole allocation
28638b244e21SEwan Crawford     const unsigned int padding = alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
2864a0f08674SEwan Crawford     if (log)
28658b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - stride %u bytes, size %u bytes, padding %u", stride, size, padding);
2866a0f08674SEwan Crawford 
2867a0f08674SEwan Crawford     // Find dimensions used to index loops, so need to be non-zero
2868a0f08674SEwan Crawford     unsigned int dim_x = alloc->dimension.get()->dim_1;
2869a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 1 : dim_x;
2870a0f08674SEwan Crawford 
2871a0f08674SEwan Crawford     unsigned int dim_y = alloc->dimension.get()->dim_2;
2872a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 1 : dim_y;
2873a0f08674SEwan Crawford 
2874a0f08674SEwan Crawford     unsigned int dim_z = alloc->dimension.get()->dim_3;
2875a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 1 : dim_z;
2876a0f08674SEwan Crawford 
287755232f09SEwan Crawford     // Use data extractor to format output
287855232f09SEwan Crawford     const uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
287955232f09SEwan Crawford     DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(), archByteSize);
288055232f09SEwan Crawford 
2881a0f08674SEwan Crawford     unsigned int offset = 0;   // Offset in buffer to next element to be printed
2882a0f08674SEwan Crawford     unsigned int prev_row = 0; // Offset to the start of the previous row
2883a0f08674SEwan Crawford 
2884a0f08674SEwan Crawford     // Iterate over allocation dimensions, printing results to user
2885a0f08674SEwan Crawford     strm.Printf("Data (X, Y, Z):");
2886a0f08674SEwan Crawford     for (unsigned int z = 0; z < dim_z; ++z)
2887a0f08674SEwan Crawford     {
2888a0f08674SEwan Crawford         for (unsigned int y = 0; y < dim_y; ++y)
2889a0f08674SEwan Crawford         {
2890a0f08674SEwan Crawford             // Use stride to index start of next row.
2891a0f08674SEwan Crawford             if (!(y==0 && z==0))
2892a0f08674SEwan Crawford                 offset = prev_row + stride;
2893a0f08674SEwan Crawford             prev_row = offset;
2894a0f08674SEwan Crawford 
2895a0f08674SEwan Crawford             // Print each element in the row individually
2896a0f08674SEwan Crawford             for (unsigned int x = 0; x < dim_x; ++x)
2897a0f08674SEwan Crawford             {
2898a0f08674SEwan Crawford                 strm.Printf("\n(%u, %u, %u) = ", x, y, z);
28998b244e21SEwan Crawford                 if ((type == Element::RS_TYPE_NONE) && (alloc->element.children.size() > 0) &&
2900fe06b5adSAdrian McCarthy                     (alloc->element.type_name != Element::GetFallbackStructName()))
29018b244e21SEwan Crawford                 {
29028b244e21SEwan Crawford                     // Here we are dumping an Element of struct type.
29038b244e21SEwan Crawford                     // This is done using expression evaluation with the name of the struct type and pointer to element.
29048b244e21SEwan Crawford 
29058b244e21SEwan Crawford                     // Don't print the name of the resulting expression, since this will be '$[0-9]+'
29068b244e21SEwan Crawford                     DumpValueObjectOptions expr_options;
29078b244e21SEwan Crawford                     expr_options.SetHideName(true);
29088b244e21SEwan Crawford 
29098b244e21SEwan Crawford                     // Setup expression as derefrencing a pointer cast to element address.
2910b1651b8dSEwan Crawford                     char expr_char_buffer[jit_max_expr_size];
2911b1651b8dSEwan Crawford                     int chars_written = snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
29128b244e21SEwan Crawford                                         alloc->element.type_name.AsCString(), *alloc->data_ptr.get() + offset);
29138b244e21SEwan Crawford 
2914b1651b8dSEwan Crawford                     if (chars_written < 0 || chars_written >= jit_max_expr_size)
29158b244e21SEwan Crawford                     {
29168b244e21SEwan Crawford                         if (log)
29178b244e21SEwan Crawford                             log->Printf("RenderScriptRuntime::DumpAllocation- Error in snprintf()");
29188b244e21SEwan Crawford                         continue;
29198b244e21SEwan Crawford                     }
29208b244e21SEwan Crawford 
29218b244e21SEwan Crawford                     // Evaluate expression
29228b244e21SEwan Crawford                     ValueObjectSP expr_result;
29238b244e21SEwan Crawford                     GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer, frame_ptr, expr_result);
29248b244e21SEwan Crawford 
29258b244e21SEwan Crawford                     // Print the results to our stream.
29268b244e21SEwan Crawford                     expr_result->Dump(strm, expr_options);
29278b244e21SEwan Crawford                 }
29288b244e21SEwan Crawford                 else
29298b244e21SEwan Crawford                 {
29308b244e21SEwan Crawford                     alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0, 0);
29318b244e21SEwan Crawford                 }
29328b244e21SEwan Crawford                 offset += data_size;
2933a0f08674SEwan Crawford             }
2934a0f08674SEwan Crawford         }
2935a0f08674SEwan Crawford     }
2936a0f08674SEwan Crawford     strm.EOL();
2937a0f08674SEwan Crawford 
2938a0f08674SEwan Crawford     return true;
2939a0f08674SEwan Crawford }
2940a0f08674SEwan Crawford 
294115f2bd95SEwan Crawford // Prints infomation regarding all the currently loaded allocations.
294215f2bd95SEwan Crawford // These details are gathered by jitting the runtime, which has as latency.
294315f2bd95SEwan Crawford void
294415f2bd95SEwan Crawford RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame* frame_ptr, bool recompute)
294515f2bd95SEwan Crawford {
294615f2bd95SEwan Crawford     strm.Printf("RenderScript Allocations:");
294715f2bd95SEwan Crawford     strm.EOL();
294815f2bd95SEwan Crawford     strm.IndentMore();
294915f2bd95SEwan Crawford 
295015f2bd95SEwan Crawford     for (auto &alloc : m_allocations)
295115f2bd95SEwan Crawford     {
295215f2bd95SEwan Crawford         // JIT the allocation info if we haven't done it, or the user forces us to.
29538b59062aSEwan Crawford         bool do_refresh = alloc->shouldRefresh() || recompute;
295415f2bd95SEwan Crawford 
295515f2bd95SEwan Crawford         // JIT current allocation information
295615f2bd95SEwan Crawford         if (do_refresh && !RefreshAllocation(alloc.get(), frame_ptr))
295715f2bd95SEwan Crawford         {
295815f2bd95SEwan Crawford             strm.Printf("Error: Couldn't evaluate details for allocation %u\n", alloc->id);
295915f2bd95SEwan Crawford             continue;
296015f2bd95SEwan Crawford         }
296115f2bd95SEwan Crawford 
296215f2bd95SEwan Crawford         strm.Printf("%u:\n",alloc->id);
296315f2bd95SEwan Crawford         strm.IndentMore();
296415f2bd95SEwan Crawford 
296515f2bd95SEwan Crawford         strm.Indent("Context: ");
296615f2bd95SEwan Crawford         if (!alloc->context.isValid())
296715f2bd95SEwan Crawford             strm.Printf("unknown\n");
296815f2bd95SEwan Crawford         else
296915f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
297015f2bd95SEwan Crawford 
297115f2bd95SEwan Crawford         strm.Indent("Address: ");
297215f2bd95SEwan Crawford         if (!alloc->address.isValid())
297315f2bd95SEwan Crawford             strm.Printf("unknown\n");
297415f2bd95SEwan Crawford         else
297515f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
297615f2bd95SEwan Crawford 
297715f2bd95SEwan Crawford         strm.Indent("Data pointer: ");
297815f2bd95SEwan Crawford         if (!alloc->data_ptr.isValid())
297915f2bd95SEwan Crawford             strm.Printf("unknown\n");
298015f2bd95SEwan Crawford         else
298115f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
298215f2bd95SEwan Crawford 
298315f2bd95SEwan Crawford         strm.Indent("Dimensions: ");
298415f2bd95SEwan Crawford         if (!alloc->dimension.isValid())
298515f2bd95SEwan Crawford             strm.Printf("unknown\n");
298615f2bd95SEwan Crawford         else
298715f2bd95SEwan Crawford             strm.Printf("(%d, %d, %d)\n", alloc->dimension.get()->dim_1,
298815f2bd95SEwan Crawford                                           alloc->dimension.get()->dim_2,
298915f2bd95SEwan Crawford                                           alloc->dimension.get()->dim_3);
299015f2bd95SEwan Crawford 
299115f2bd95SEwan Crawford         strm.Indent("Data Type: ");
29928b244e21SEwan Crawford         if (!alloc->element.type.isValid() || !alloc->element.type_vec_size.isValid())
299315f2bd95SEwan Crawford             strm.Printf("unknown\n");
299415f2bd95SEwan Crawford         else
299515f2bd95SEwan Crawford         {
29968b244e21SEwan Crawford             const int vector_size = *alloc->element.type_vec_size.get();
29972e920715SEwan Crawford             Element::DataType type = *alloc->element.type.get();
299815f2bd95SEwan Crawford 
29998b244e21SEwan Crawford             if (!alloc->element.type_name.IsEmpty())
30008b244e21SEwan Crawford                 strm.Printf("%s\n", alloc->element.type_name.AsCString());
30012e920715SEwan Crawford             else
30022e920715SEwan Crawford             {
30032e920715SEwan Crawford                 // Enum value isn't monotonous, so doesn't always index RsDataTypeToString array
30042e920715SEwan Crawford                 if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
30052e920715SEwan Crawford                     type = static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +  Element::RS_TYPE_MATRIX_2X2 + 1);
30062e920715SEwan Crawford 
30072e920715SEwan Crawford                 if (type >= (sizeof(AllocationDetails::RsDataTypeToString) / sizeof(AllocationDetails::RsDataTypeToString[0]))
30082e920715SEwan Crawford                     || vector_size > 4 || vector_size < 1)
300915f2bd95SEwan Crawford                     strm.Printf("invalid type\n");
301015f2bd95SEwan Crawford                 else
301115f2bd95SEwan Crawford                     strm.Printf("%s\n", AllocationDetails::RsDataTypeToString[static_cast<unsigned int>(type)][vector_size-1]);
301215f2bd95SEwan Crawford             }
30132e920715SEwan Crawford         }
301415f2bd95SEwan Crawford 
301515f2bd95SEwan Crawford         strm.Indent("Data Kind: ");
30168b244e21SEwan Crawford         if (!alloc->element.type_kind.isValid())
301715f2bd95SEwan Crawford             strm.Printf("unknown\n");
301815f2bd95SEwan Crawford         else
301915f2bd95SEwan Crawford         {
30208b244e21SEwan Crawford             const Element::DataKind kind = *alloc->element.type_kind.get();
30218b244e21SEwan Crawford             if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
302215f2bd95SEwan Crawford                 strm.Printf("invalid kind\n");
302315f2bd95SEwan Crawford             else
302415f2bd95SEwan Crawford                 strm.Printf("%s\n", AllocationDetails::RsDataKindToString[static_cast<unsigned int>(kind)]);
302515f2bd95SEwan Crawford         }
302615f2bd95SEwan Crawford 
302715f2bd95SEwan Crawford         strm.EOL();
302815f2bd95SEwan Crawford         strm.IndentLess();
302915f2bd95SEwan Crawford     }
303015f2bd95SEwan Crawford     strm.IndentLess();
303115f2bd95SEwan Crawford }
303215f2bd95SEwan Crawford 
30337dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
30347dc7771cSEwan Crawford void
30357dc7771cSEwan Crawford RenderScriptRuntime::BreakOnModuleKernels(const RSModuleDescriptorSP rsmodule_sp)
30367dc7771cSEwan Crawford {
30377dc7771cSEwan Crawford     for (const auto &kernel : rsmodule_sp->m_kernels)
30387dc7771cSEwan Crawford     {
30397dc7771cSEwan Crawford         // Don't set breakpoint on 'root' kernel
30407dc7771cSEwan Crawford         if (strcmp(kernel.m_name.AsCString(), "root") == 0)
30417dc7771cSEwan Crawford             continue;
30427dc7771cSEwan Crawford 
30437dc7771cSEwan Crawford         CreateKernelBreakpoint(kernel.m_name);
30447dc7771cSEwan Crawford     }
30457dc7771cSEwan Crawford }
30467dc7771cSEwan Crawford 
30477dc7771cSEwan Crawford // Method is internally called by the 'kernel breakpoint all' command to
30487dc7771cSEwan Crawford // enable or disable breaking on all kernels.
30497dc7771cSEwan Crawford //
30507dc7771cSEwan Crawford // When do_break is true we want to enable this functionality.
30517dc7771cSEwan Crawford // When do_break is false we want to disable it.
30527dc7771cSEwan Crawford void
30537dc7771cSEwan Crawford RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target)
30547dc7771cSEwan Crawford {
305554782db7SEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
30567dc7771cSEwan Crawford 
30577dc7771cSEwan Crawford     InitSearchFilter(target);
30587dc7771cSEwan Crawford 
30597dc7771cSEwan Crawford     // Set breakpoints on all the kernels
30607dc7771cSEwan Crawford     if (do_break && !m_breakAllKernels)
30617dc7771cSEwan Crawford     {
30627dc7771cSEwan Crawford         m_breakAllKernels = true;
30637dc7771cSEwan Crawford 
30647dc7771cSEwan Crawford         for (const auto &module : m_rsmodules)
30657dc7771cSEwan Crawford             BreakOnModuleKernels(module);
30667dc7771cSEwan Crawford 
30677dc7771cSEwan Crawford         if (log)
30687dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::SetBreakAllKernels(True)"
30697dc7771cSEwan Crawford                         "- breakpoints set on all currently loaded kernels");
30707dc7771cSEwan Crawford     }
30717dc7771cSEwan Crawford     else if (!do_break && m_breakAllKernels) // Breakpoints won't be set on any new kernels.
30727dc7771cSEwan Crawford     {
30737dc7771cSEwan Crawford         m_breakAllKernels = false;
30747dc7771cSEwan Crawford 
30757dc7771cSEwan Crawford         if (log)
30767dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::SetBreakAllKernels(False) - breakpoints no longer automatically set");
30777dc7771cSEwan Crawford     }
30787dc7771cSEwan Crawford }
30797dc7771cSEwan Crawford 
30807dc7771cSEwan Crawford // Given the name of a kernel this function creates a breakpoint using our
30817dc7771cSEwan Crawford // own breakpoint resolver, and returns the Breakpoint shared pointer.
30827dc7771cSEwan Crawford BreakpointSP
30837dc7771cSEwan Crawford RenderScriptRuntime::CreateKernelBreakpoint(const ConstString& name)
30847dc7771cSEwan Crawford {
308554782db7SEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
30867dc7771cSEwan Crawford 
30877dc7771cSEwan Crawford     if (!m_filtersp)
30887dc7771cSEwan Crawford     {
30897dc7771cSEwan Crawford         if (log)
30907dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::CreateKernelBreakpoint - Error: No breakpoint search filter set");
30917dc7771cSEwan Crawford         return nullptr;
30927dc7771cSEwan Crawford     }
30937dc7771cSEwan Crawford 
30947dc7771cSEwan Crawford     BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
30957dc7771cSEwan Crawford     BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(m_filtersp, resolver_sp, false, false, false);
30967dc7771cSEwan Crawford 
309754782db7SEwan Crawford     // Give RS breakpoints a specific name, so the user can manipulate them as a group.
309854782db7SEwan Crawford     Error err;
309954782db7SEwan Crawford     if (!bp->AddName("RenderScriptKernel", err) && log)
310054782db7SEwan Crawford         log->Printf("RenderScriptRuntime::CreateKernelBreakpoint: Error setting break name, %s", err.AsCString());
310154782db7SEwan Crawford 
31027dc7771cSEwan Crawford     return bp;
31037dc7771cSEwan Crawford }
31047dc7771cSEwan Crawford 
3105018f5a7eSEwan Crawford // Given an expression for a variable this function tries to calculate the variable's value.
3106018f5a7eSEwan Crawford // If this is possible it returns true and sets the uint64_t parameter to the variables unsigned value.
3107018f5a7eSEwan Crawford // Otherwise function returns false.
3108018f5a7eSEwan Crawford bool
3109018f5a7eSEwan Crawford RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp, const char* var_name, uint64_t& val)
3110018f5a7eSEwan Crawford {
3111018f5a7eSEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3112018f5a7eSEwan Crawford     Error error;
3113018f5a7eSEwan Crawford     VariableSP var_sp;
3114018f5a7eSEwan Crawford 
3115018f5a7eSEwan Crawford     // Find variable in stack frame
3116018f5a7eSEwan Crawford     ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(var_name,
3117018f5a7eSEwan Crawford                                                                        eNoDynamicValues,
3118018f5a7eSEwan Crawford                                                                        StackFrame::eExpressionPathOptionCheckPtrVsMember |
3119018f5a7eSEwan Crawford                                                                        StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3120018f5a7eSEwan Crawford                                                                        var_sp,
3121018f5a7eSEwan Crawford                                                                        error));
3122018f5a7eSEwan Crawford     if (!error.Success())
3123018f5a7eSEwan Crawford     {
3124018f5a7eSEwan Crawford         if (log)
3125018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't find '%s' in frame", var_name);
3126018f5a7eSEwan Crawford 
3127018f5a7eSEwan Crawford         return false;
3128018f5a7eSEwan Crawford     }
3129018f5a7eSEwan Crawford 
3130018f5a7eSEwan Crawford     // Find the unsigned int value for the variable
3131018f5a7eSEwan Crawford     bool success = false;
3132018f5a7eSEwan Crawford     val = value_sp->GetValueAsUnsigned(0, &success);
3133018f5a7eSEwan Crawford     if (!success)
3134018f5a7eSEwan Crawford     {
3135018f5a7eSEwan Crawford         if (log)
3136018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't parse '%s' as an unsigned int", var_name);
3137018f5a7eSEwan Crawford 
3138018f5a7eSEwan Crawford         return false;
3139018f5a7eSEwan Crawford     }
3140018f5a7eSEwan Crawford 
3141018f5a7eSEwan Crawford     return true;
3142018f5a7eSEwan Crawford }
3143018f5a7eSEwan Crawford 
3144018f5a7eSEwan Crawford // Callback when a kernel breakpoint hits and we're looking for a specific coordinate.
3145018f5a7eSEwan Crawford // Baton parameter contains a pointer to the target coordinate we want to break on.
3146018f5a7eSEwan Crawford // Function then checks the .expand frame for the current coordinate and breaks to user if it matches.
3147018f5a7eSEwan Crawford // Parameter 'break_id' is the id of the Breakpoint which made the callback.
3148018f5a7eSEwan Crawford // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
3149018f5a7eSEwan Crawford // a single logical breakpoint can have multiple addresses.
3150018f5a7eSEwan Crawford bool
3151018f5a7eSEwan Crawford RenderScriptRuntime::KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx,
3152018f5a7eSEwan Crawford                                          user_id_t break_id, user_id_t break_loc_id)
3153018f5a7eSEwan Crawford {
3154018f5a7eSEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3155018f5a7eSEwan Crawford 
3156018f5a7eSEwan Crawford     assert(baton && "Error: null baton in conditional kernel breakpoint callback");
3157018f5a7eSEwan Crawford 
3158018f5a7eSEwan Crawford     // Coordinate we want to stop on
3159018f5a7eSEwan Crawford     const int* target_coord = static_cast<const int*>(baton);
3160018f5a7eSEwan Crawford 
3161018f5a7eSEwan Crawford     if (log)
3162018f5a7eSEwan Crawford         log->Printf("RenderScriptRuntime::KernelBreakpointHit - Break ID %" PRIu64 ", target coord (%d, %d, %d)",
3163018f5a7eSEwan Crawford                     break_id, target_coord[0], target_coord[1], target_coord[2]);
3164018f5a7eSEwan Crawford 
3165018f5a7eSEwan Crawford     // Go up one stack frame to .expand kernel
3166018f5a7eSEwan Crawford     ExecutionContext context(ctx->exe_ctx_ref);
3167018f5a7eSEwan Crawford     ThreadSP thread_sp = context.GetThreadSP();
3168018f5a7eSEwan Crawford     if (!thread_sp->SetSelectedFrameByIndex(1))
3169018f5a7eSEwan Crawford     {
3170018f5a7eSEwan Crawford         if (log)
3171018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't go up stack frame");
3172018f5a7eSEwan Crawford 
3173018f5a7eSEwan Crawford        return false;
3174018f5a7eSEwan Crawford     }
3175018f5a7eSEwan Crawford 
3176018f5a7eSEwan Crawford     StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
3177018f5a7eSEwan Crawford     if (!frame_sp)
3178018f5a7eSEwan Crawford     {
3179018f5a7eSEwan Crawford         if (log)
3180018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't select .expand stack frame");
3181018f5a7eSEwan Crawford 
3182018f5a7eSEwan Crawford         return false;
3183018f5a7eSEwan Crawford     }
3184018f5a7eSEwan Crawford 
3185018f5a7eSEwan Crawford     // Get values for variables in .expand frame that tell us the current kernel invocation
3186018f5a7eSEwan Crawford     const char* coord_expressions[] = {"rsIndex", "p->current.y", "p->current.z"};
3187018f5a7eSEwan Crawford     uint64_t current_coord[3] = {0, 0, 0};
3188018f5a7eSEwan Crawford 
3189018f5a7eSEwan Crawford     for(int i = 0; i < 3; ++i)
3190018f5a7eSEwan Crawford     {
3191018f5a7eSEwan Crawford         if (!GetFrameVarAsUnsigned(frame_sp, coord_expressions[i], current_coord[i]))
3192018f5a7eSEwan Crawford             return false;
3193018f5a7eSEwan Crawford 
3194018f5a7eSEwan Crawford         if (log)
3195018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit, %s = %" PRIu64, coord_expressions[i], current_coord[i]);
3196018f5a7eSEwan Crawford     }
3197018f5a7eSEwan Crawford 
3198018f5a7eSEwan Crawford     // Check if the current kernel invocation coordinate matches our target coordinate
3199018f5a7eSEwan Crawford     if (current_coord[0] == static_cast<uint64_t>(target_coord[0]) &&
3200018f5a7eSEwan Crawford         current_coord[1] == static_cast<uint64_t>(target_coord[1]) &&
3201018f5a7eSEwan Crawford         current_coord[2] == static_cast<uint64_t>(target_coord[2]))
3202018f5a7eSEwan Crawford     {
3203018f5a7eSEwan Crawford         if (log)
3204018f5a7eSEwan Crawford              log->Printf("RenderScriptRuntime::KernelBreakpointHit, BREAKING %" PRIu64 ", %" PRIu64 ", %" PRIu64,
3205018f5a7eSEwan Crawford                          current_coord[0], current_coord[1], current_coord[2]);
3206018f5a7eSEwan Crawford 
3207018f5a7eSEwan Crawford         BreakpointSP breakpoint_sp = context.GetTargetPtr()->GetBreakpointByID(break_id);
3208018f5a7eSEwan Crawford         assert(breakpoint_sp != nullptr && "Error: Couldn't find breakpoint matching break id for callback");
3209018f5a7eSEwan Crawford         breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint should only be hit once.
3210018f5a7eSEwan Crawford         return true;
3211018f5a7eSEwan Crawford     }
3212018f5a7eSEwan Crawford 
3213018f5a7eSEwan Crawford     // No match on coordinate
3214018f5a7eSEwan Crawford     return false;
3215018f5a7eSEwan Crawford }
3216018f5a7eSEwan Crawford 
3217018f5a7eSEwan Crawford // Tries to set a breakpoint on the start of a kernel, resolved using the kernel name.
3218018f5a7eSEwan Crawford // Argument 'coords', represents a three dimensional coordinate which can be used to specify
3219018f5a7eSEwan Crawford // a single kernel instance to break on. If this is set then we add a callback to the breakpoint.
32204640cde1SColin Riley void
3221018f5a7eSEwan Crawford RenderScriptRuntime::PlaceBreakpointOnKernel(Stream &strm, const char* name, const std::array<int,3> coords,
3222018f5a7eSEwan Crawford                                              Error& error, TargetSP target)
32234640cde1SColin Riley {
32244640cde1SColin Riley     if (!name)
32254640cde1SColin Riley     {
32264640cde1SColin Riley         error.SetErrorString("invalid kernel name");
32274640cde1SColin Riley         return;
32284640cde1SColin Riley     }
32294640cde1SColin Riley 
32307dc7771cSEwan Crawford     InitSearchFilter(target);
323198156583SEwan Crawford 
32324640cde1SColin Riley     ConstString kernel_name(name);
32337dc7771cSEwan Crawford     BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
3234018f5a7eSEwan Crawford 
3235018f5a7eSEwan Crawford     // We have a conditional breakpoint on a specific coordinate
3236018f5a7eSEwan Crawford     if (coords[0] != -1)
3237018f5a7eSEwan Crawford     {
3238018f5a7eSEwan Crawford         strm.Printf("Conditional kernel breakpoint on coordinate %d, %d, %d", coords[0], coords[1], coords[2]);
3239018f5a7eSEwan Crawford         strm.EOL();
3240018f5a7eSEwan Crawford 
3241018f5a7eSEwan Crawford         // Allocate memory for the baton, and copy over coordinate
3242018f5a7eSEwan Crawford         int* baton = new int[3];
3243018f5a7eSEwan Crawford         baton[0] = coords[0]; baton[1] = coords[1]; baton[2] = coords[2];
3244018f5a7eSEwan Crawford 
3245018f5a7eSEwan Crawford         // Create a callback that will be invoked everytime the breakpoint is hit.
3246018f5a7eSEwan Crawford         // The baton object passed to the handler is the target coordinate we want to break on.
3247018f5a7eSEwan Crawford         bp->SetCallback(KernelBreakpointHit, baton, true);
3248018f5a7eSEwan Crawford 
3249018f5a7eSEwan Crawford         // Store a shared pointer to the baton, so the memory will eventually be cleaned up after destruction
3250018f5a7eSEwan Crawford         m_conditional_breaks[bp->GetID()] = std::shared_ptr<int>(baton);
3251018f5a7eSEwan Crawford     }
3252018f5a7eSEwan Crawford 
325398156583SEwan Crawford     if (bp)
325498156583SEwan Crawford         bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
32554640cde1SColin Riley }
32564640cde1SColin Riley 
32574640cde1SColin Riley void
32585ec532a9SColin Riley RenderScriptRuntime::DumpModules(Stream &strm) const
32595ec532a9SColin Riley {
32605ec532a9SColin Riley     strm.Printf("RenderScript Modules:");
32615ec532a9SColin Riley     strm.EOL();
32625ec532a9SColin Riley     strm.IndentMore();
32635ec532a9SColin Riley     for (const auto &module : m_rsmodules)
32645ec532a9SColin Riley     {
32654640cde1SColin Riley         module->Dump(strm);
32665ec532a9SColin Riley     }
32675ec532a9SColin Riley     strm.IndentLess();
32685ec532a9SColin Riley }
32695ec532a9SColin Riley 
327078f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails*
327178f339d1SEwan Crawford RenderScriptRuntime::LookUpScript(addr_t address, bool create)
327278f339d1SEwan Crawford {
327378f339d1SEwan Crawford     for (const auto & s : m_scripts)
327478f339d1SEwan Crawford     {
327578f339d1SEwan Crawford         if (s->script.isValid())
327678f339d1SEwan Crawford             if (*s->script == address)
327778f339d1SEwan Crawford                 return s.get();
327878f339d1SEwan Crawford     }
327978f339d1SEwan Crawford     if (create)
328078f339d1SEwan Crawford     {
328178f339d1SEwan Crawford         std::unique_ptr<ScriptDetails> s(new ScriptDetails);
328278f339d1SEwan Crawford         s->script = address;
328378f339d1SEwan Crawford         m_scripts.push_back(std::move(s));
3284d10ca9deSEwan Crawford         return m_scripts.back().get();
328578f339d1SEwan Crawford     }
328678f339d1SEwan Crawford     return nullptr;
328778f339d1SEwan Crawford }
328878f339d1SEwan Crawford 
328978f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails*
329078f339d1SEwan Crawford RenderScriptRuntime::LookUpAllocation(addr_t address, bool create)
329178f339d1SEwan Crawford {
329278f339d1SEwan Crawford     for (const auto & a : m_allocations)
329378f339d1SEwan Crawford     {
329478f339d1SEwan Crawford         if (a->address.isValid())
329578f339d1SEwan Crawford             if (*a->address == address)
329678f339d1SEwan Crawford                 return a.get();
329778f339d1SEwan Crawford     }
329878f339d1SEwan Crawford     if (create)
329978f339d1SEwan Crawford     {
330078f339d1SEwan Crawford         std::unique_ptr<AllocationDetails> a(new AllocationDetails);
330178f339d1SEwan Crawford         a->address = address;
330278f339d1SEwan Crawford         m_allocations.push_back(std::move(a));
3303d10ca9deSEwan Crawford         return m_allocations.back().get();
330478f339d1SEwan Crawford     }
330578f339d1SEwan Crawford     return nullptr;
330678f339d1SEwan Crawford }
330778f339d1SEwan Crawford 
33085ec532a9SColin Riley void
33095ec532a9SColin Riley RSModuleDescriptor::Dump(Stream &strm) const
33105ec532a9SColin Riley {
33115ec532a9SColin Riley     strm.Indent();
33125ec532a9SColin Riley     m_module->GetFileSpec().Dump(&strm);
33134640cde1SColin Riley     if(m_module->GetNumCompileUnits())
33144640cde1SColin Riley     {
33154640cde1SColin Riley         strm.Indent("Debug info loaded.");
33164640cde1SColin Riley     }
33174640cde1SColin Riley     else
33184640cde1SColin Riley     {
33194640cde1SColin Riley         strm.Indent("Debug info does not exist.");
33204640cde1SColin Riley     }
33215ec532a9SColin Riley     strm.EOL();
33225ec532a9SColin Riley     strm.IndentMore();
33235ec532a9SColin Riley     strm.Indent();
3324189598edSColin Riley     strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
33255ec532a9SColin Riley     strm.EOL();
33265ec532a9SColin Riley     strm.IndentMore();
33275ec532a9SColin Riley     for (const auto &global : m_globals)
33285ec532a9SColin Riley     {
33295ec532a9SColin Riley         global.Dump(strm);
33305ec532a9SColin Riley     }
33315ec532a9SColin Riley     strm.IndentLess();
33325ec532a9SColin Riley     strm.Indent();
3333189598edSColin Riley     strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
33345ec532a9SColin Riley     strm.EOL();
33355ec532a9SColin Riley     strm.IndentMore();
33365ec532a9SColin Riley     for (const auto &kernel : m_kernels)
33375ec532a9SColin Riley     {
33385ec532a9SColin Riley         kernel.Dump(strm);
33395ec532a9SColin Riley     }
33404640cde1SColin Riley     strm.Printf("Pragmas: %"  PRIu64 , static_cast<uint64_t>(m_pragmas.size()));
33414640cde1SColin Riley     strm.EOL();
33424640cde1SColin Riley     strm.IndentMore();
33434640cde1SColin Riley     for (const auto &key_val : m_pragmas)
33444640cde1SColin Riley     {
33454640cde1SColin Riley         strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
33464640cde1SColin Riley         strm.EOL();
33474640cde1SColin Riley     }
33485ec532a9SColin Riley     strm.IndentLess(4);
33495ec532a9SColin Riley }
33505ec532a9SColin Riley 
33515ec532a9SColin Riley void
33525ec532a9SColin Riley RSGlobalDescriptor::Dump(Stream &strm) const
33535ec532a9SColin Riley {
33545ec532a9SColin Riley     strm.Indent(m_name.AsCString());
33554640cde1SColin Riley     VariableList var_list;
33564640cde1SColin Riley     m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
33574640cde1SColin Riley     if (var_list.GetSize() == 1)
33584640cde1SColin Riley     {
33594640cde1SColin Riley         auto var = var_list.GetVariableAtIndex(0);
33604640cde1SColin Riley         auto type = var->GetType();
33614640cde1SColin Riley         if(type)
33624640cde1SColin Riley         {
33634640cde1SColin Riley             strm.Printf(" - ");
33644640cde1SColin Riley             type->DumpTypeName(&strm);
33654640cde1SColin Riley         }
33664640cde1SColin Riley         else
33674640cde1SColin Riley         {
33684640cde1SColin Riley             strm.Printf(" - Unknown Type");
33694640cde1SColin Riley         }
33704640cde1SColin Riley     }
33714640cde1SColin Riley     else
33724640cde1SColin Riley     {
33734640cde1SColin Riley         strm.Printf(" - variable identified, but not found in binary");
33744640cde1SColin Riley         const Symbol* s = m_module->m_module->FindFirstSymbolWithNameAndType(m_name, eSymbolTypeData);
33754640cde1SColin Riley         if (s)
33764640cde1SColin Riley         {
33774640cde1SColin Riley             strm.Printf(" (symbol exists) ");
33784640cde1SColin Riley         }
33794640cde1SColin Riley     }
33804640cde1SColin Riley 
33815ec532a9SColin Riley     strm.EOL();
33825ec532a9SColin Riley }
33835ec532a9SColin Riley 
33845ec532a9SColin Riley void
33855ec532a9SColin Riley RSKernelDescriptor::Dump(Stream &strm) const
33865ec532a9SColin Riley {
33875ec532a9SColin Riley     strm.Indent(m_name.AsCString());
33885ec532a9SColin Riley     strm.EOL();
33895ec532a9SColin Riley }
33905ec532a9SColin Riley 
33915ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleProbe : public CommandObjectParsed
33925ec532a9SColin Riley {
33935ec532a9SColin Riley public:
33945ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleProbe(CommandInterpreter &interpreter)
33955ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module probe",
33965ec532a9SColin Riley                               "Initiates a Probe of all loaded modules for kernels and other renderscript objects.",
33975ec532a9SColin Riley                               "renderscript module probe",
3398e87764f2SEnrico Granata                               eCommandRequiresTarget | eCommandRequiresProcess | eCommandProcessMustBeLaunched)
33995ec532a9SColin Riley     {
34005ec532a9SColin Riley     }
34015ec532a9SColin Riley 
3402222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModuleProbe() override = default;
34035ec532a9SColin Riley 
34045ec532a9SColin Riley     bool
3405222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
34065ec532a9SColin Riley     {
34075ec532a9SColin Riley         const size_t argc = command.GetArgumentCount();
34085ec532a9SColin Riley         if (argc == 0)
34095ec532a9SColin Riley         {
34105ec532a9SColin Riley             Target *target = m_exe_ctx.GetTargetPtr();
34115ec532a9SColin Riley             RenderScriptRuntime *runtime =
34125ec532a9SColin Riley                 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
34135ec532a9SColin Riley             auto module_list = target->GetImages();
34145ec532a9SColin Riley             bool new_rs_details = runtime->ProbeModules(module_list);
34155ec532a9SColin Riley             if (new_rs_details)
34165ec532a9SColin Riley             {
34175ec532a9SColin Riley                 result.AppendMessage("New renderscript modules added to runtime model.");
34185ec532a9SColin Riley             }
34195ec532a9SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
34205ec532a9SColin Riley             return true;
34215ec532a9SColin Riley         }
34225ec532a9SColin Riley 
34235ec532a9SColin Riley         result.AppendErrorWithFormat("'%s' takes no arguments", m_cmd_name.c_str());
34245ec532a9SColin Riley         result.SetStatus(eReturnStatusFailed);
34255ec532a9SColin Riley         return false;
34265ec532a9SColin Riley     }
34275ec532a9SColin Riley };
34285ec532a9SColin Riley 
34295ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed
34305ec532a9SColin Riley {
34315ec532a9SColin Riley public:
34325ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
34335ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module dump",
34345ec532a9SColin Riley                               "Dumps renderscript specific information for all modules.", "renderscript module dump",
3435e87764f2SEnrico Granata                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
34365ec532a9SColin Riley     {
34375ec532a9SColin Riley     }
34385ec532a9SColin Riley 
3439222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
34405ec532a9SColin Riley 
34415ec532a9SColin Riley     bool
3442222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
34435ec532a9SColin Riley     {
34445ec532a9SColin Riley         RenderScriptRuntime *runtime =
34455ec532a9SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
34465ec532a9SColin Riley         runtime->DumpModules(result.GetOutputStream());
34475ec532a9SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
34485ec532a9SColin Riley         return true;
34495ec532a9SColin Riley     }
34505ec532a9SColin Riley };
34515ec532a9SColin Riley 
34525ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword
34535ec532a9SColin Riley {
34545ec532a9SColin Riley public:
34555ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
34565ec532a9SColin Riley         : CommandObjectMultiword(interpreter, "renderscript module", "Commands that deal with renderscript modules.",
34575ec532a9SColin Riley                                  NULL)
34585ec532a9SColin Riley     {
34595ec532a9SColin Riley         LoadSubCommand("probe", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleProbe(interpreter)));
34605ec532a9SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(interpreter)));
34615ec532a9SColin Riley     }
34625ec532a9SColin Riley 
3463222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModule() override = default;
34645ec532a9SColin Riley };
34655ec532a9SColin Riley 
34664640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed
34674640cde1SColin Riley {
34684640cde1SColin Riley public:
34694640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
34704640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript kernel list",
34714640cde1SColin Riley                               "Lists renderscript kernel names and associated script resources.", "renderscript kernel list",
34724640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
34734640cde1SColin Riley     {
34744640cde1SColin Riley     }
34754640cde1SColin Riley 
3476222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelList() override = default;
34774640cde1SColin Riley 
34784640cde1SColin Riley     bool
3479222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
34804640cde1SColin Riley     {
34814640cde1SColin Riley         RenderScriptRuntime *runtime =
34824640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
34834640cde1SColin Riley         runtime->DumpKernels(result.GetOutputStream());
34844640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
34854640cde1SColin Riley         return true;
34864640cde1SColin Riley     }
34874640cde1SColin Riley };
34884640cde1SColin Riley 
34897dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointSet : public CommandObjectParsed
34904640cde1SColin Riley {
34914640cde1SColin Riley public:
34927dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointSet(CommandInterpreter &interpreter)
34937dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint set",
3494018f5a7eSEwan Crawford                               "Sets a breakpoint on a renderscript kernel.", "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
3495018f5a7eSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), m_options(interpreter)
34964640cde1SColin Riley     {
34974640cde1SColin Riley     }
34984640cde1SColin Riley 
3499222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
3500222b937cSEugene Zelenko 
3501222b937cSEugene Zelenko     Options*
3502222b937cSEugene Zelenko     GetOptions() override
3503018f5a7eSEwan Crawford     {
3504018f5a7eSEwan Crawford         return &m_options;
3505018f5a7eSEwan Crawford     }
3506018f5a7eSEwan Crawford 
3507018f5a7eSEwan Crawford     class CommandOptions : public Options
3508018f5a7eSEwan Crawford     {
3509018f5a7eSEwan Crawford     public:
3510018f5a7eSEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter)
3511018f5a7eSEwan Crawford         {
3512018f5a7eSEwan Crawford         }
3513018f5a7eSEwan Crawford 
3514222b937cSEugene Zelenko         ~CommandOptions() override = default;
3515018f5a7eSEwan Crawford 
3516222b937cSEugene Zelenko         Error
3517222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
3518018f5a7eSEwan Crawford         {
3519018f5a7eSEwan Crawford             Error error;
3520018f5a7eSEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
3521018f5a7eSEwan Crawford 
3522018f5a7eSEwan Crawford             switch (short_option)
3523018f5a7eSEwan Crawford             {
3524018f5a7eSEwan Crawford                 case 'c':
3525018f5a7eSEwan Crawford                     if (!ParseCoordinate(option_arg))
3526018f5a7eSEwan Crawford                         error.SetErrorStringWithFormat("Couldn't parse coordinate '%s', should be in format 'x,y,z'.", option_arg);
3527018f5a7eSEwan Crawford                     break;
3528018f5a7eSEwan Crawford                 default:
3529018f5a7eSEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3530018f5a7eSEwan Crawford                     break;
3531018f5a7eSEwan Crawford             }
3532018f5a7eSEwan Crawford             return error;
3533018f5a7eSEwan Crawford         }
3534018f5a7eSEwan Crawford 
3535018f5a7eSEwan Crawford         // -c takes an argument of the form 'num[,num][,num]'.
3536018f5a7eSEwan Crawford         // Where 'id_cstr' is this argument with the whitespace trimmed.
3537018f5a7eSEwan Crawford         // Missing coordinates are defaulted to zero.
3538018f5a7eSEwan Crawford         bool
3539018f5a7eSEwan Crawford         ParseCoordinate(const char* id_cstr)
3540018f5a7eSEwan Crawford         {
3541018f5a7eSEwan Crawford             RegularExpression regex;
3542018f5a7eSEwan Crawford             RegularExpression::Match regex_match(3);
3543018f5a7eSEwan Crawford 
3544018f5a7eSEwan Crawford             bool matched = false;
3545018f5a7eSEwan Crawford             if(regex.Compile("^([0-9]+),([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3546018f5a7eSEwan Crawford                 matched = true;
3547018f5a7eSEwan Crawford             else if(regex.Compile("^([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3548018f5a7eSEwan Crawford                 matched = true;
3549018f5a7eSEwan Crawford             else if(regex.Compile("^([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3550018f5a7eSEwan Crawford                 matched = true;
3551018f5a7eSEwan Crawford             for(uint32_t i = 0; i < 3; i++)
3552018f5a7eSEwan Crawford             {
3553018f5a7eSEwan Crawford                 std::string group;
3554018f5a7eSEwan Crawford                 if(regex_match.GetMatchAtIndex(id_cstr, i + 1, group))
3555018f5a7eSEwan Crawford                     m_coord[i] = (uint32_t)strtoul(group.c_str(), NULL, 0);
3556018f5a7eSEwan Crawford                 else
3557018f5a7eSEwan Crawford                     m_coord[i] = 0;
3558018f5a7eSEwan Crawford             }
3559018f5a7eSEwan Crawford             return matched;
3560018f5a7eSEwan Crawford         }
3561018f5a7eSEwan Crawford 
3562018f5a7eSEwan Crawford         void
3563222b937cSEugene Zelenko         OptionParsingStarting() override
3564018f5a7eSEwan Crawford         {
3565018f5a7eSEwan Crawford             // -1 means the -c option hasn't been set
3566018f5a7eSEwan Crawford             m_coord[0] = -1;
3567018f5a7eSEwan Crawford             m_coord[1] = -1;
3568018f5a7eSEwan Crawford             m_coord[2] = -1;
3569018f5a7eSEwan Crawford         }
3570018f5a7eSEwan Crawford 
3571018f5a7eSEwan Crawford         const OptionDefinition*
3572222b937cSEugene Zelenko         GetDefinitions() override
3573018f5a7eSEwan Crawford         {
3574018f5a7eSEwan Crawford             return g_option_table;
3575018f5a7eSEwan Crawford         }
3576018f5a7eSEwan Crawford 
3577018f5a7eSEwan Crawford         static OptionDefinition g_option_table[];
3578018f5a7eSEwan Crawford         std::array<int,3> m_coord;
3579018f5a7eSEwan Crawford     };
3580018f5a7eSEwan Crawford 
35814640cde1SColin Riley     bool
3582222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
35834640cde1SColin Riley     {
35844640cde1SColin Riley         const size_t argc = command.GetArgumentCount();
3585018f5a7eSEwan Crawford         if (argc < 1)
35864640cde1SColin Riley         {
3587018f5a7eSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of kernel name, and an optional coordinate.", m_cmd_name.c_str());
3588018f5a7eSEwan Crawford             result.SetStatus(eReturnStatusFailed);
3589018f5a7eSEwan Crawford             return false;
3590018f5a7eSEwan Crawford         }
3591018f5a7eSEwan Crawford 
35924640cde1SColin Riley         RenderScriptRuntime *runtime =
35934640cde1SColin Riley                 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
35944640cde1SColin Riley 
35954640cde1SColin Riley         Error error;
3596018f5a7eSEwan Crawford         runtime->PlaceBreakpointOnKernel(result.GetOutputStream(), command.GetArgumentAtIndex(0), m_options.m_coord,
359798156583SEwan Crawford                                          error, m_exe_ctx.GetTargetSP());
35984640cde1SColin Riley 
35994640cde1SColin Riley         if (error.Success())
36004640cde1SColin Riley         {
36014640cde1SColin Riley             result.AppendMessage("Breakpoint(s) created");
36024640cde1SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
36034640cde1SColin Riley             return true;
36044640cde1SColin Riley         }
36054640cde1SColin Riley         result.SetStatus(eReturnStatusFailed);
36064640cde1SColin Riley         result.AppendErrorWithFormat("Error: %s", error.AsCString());
36074640cde1SColin Riley         return false;
36084640cde1SColin Riley     }
36094640cde1SColin Riley 
3610018f5a7eSEwan Crawford private:
3611018f5a7eSEwan Crawford     CommandOptions m_options;
36124640cde1SColin Riley };
36134640cde1SColin Riley 
3614018f5a7eSEwan Crawford OptionDefinition
3615018f5a7eSEwan Crawford CommandObjectRenderScriptRuntimeKernelBreakpointSet::CommandOptions::g_option_table[] =
3616018f5a7eSEwan Crawford {
3617018f5a7eSEwan Crawford     { LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeValue,
3618018f5a7eSEwan Crawford       "Set a breakpoint on a single invocation of the kernel with specified coordinate.\n"
3619018f5a7eSEwan Crawford       "Coordinate takes the form 'x[,y][,z] where x,y,z are positive integers representing kernel dimensions. "
3620018f5a7eSEwan Crawford       "Any unset dimensions will be defaulted to zero."},
3621018f5a7eSEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
3622018f5a7eSEwan Crawford };
3623018f5a7eSEwan Crawford 
36247dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointAll : public CommandObjectParsed
36257dc7771cSEwan Crawford {
36267dc7771cSEwan Crawford public:
36277dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointAll(CommandInterpreter &interpreter)
36287dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint all",
36297dc7771cSEwan Crawford                               "Automatically sets a breakpoint on all renderscript kernels that are or will be loaded.\n"
36307dc7771cSEwan Crawford                               "Disabling option means breakpoints will no longer be set on any kernels loaded in the future, "
36317dc7771cSEwan Crawford                               "but does not remove currently set breakpoints.",
36327dc7771cSEwan Crawford                               "renderscript kernel breakpoint all <enable/disable>",
36337dc7771cSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
36347dc7771cSEwan Crawford     {
36357dc7771cSEwan Crawford     }
36367dc7771cSEwan Crawford 
3637222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
36387dc7771cSEwan Crawford 
36397dc7771cSEwan Crawford     bool
3640222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
36417dc7771cSEwan Crawford     {
36427dc7771cSEwan Crawford         const size_t argc = command.GetArgumentCount();
36437dc7771cSEwan Crawford         if (argc != 1)
36447dc7771cSEwan Crawford         {
36457dc7771cSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
36467dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
36477dc7771cSEwan Crawford             return false;
36487dc7771cSEwan Crawford         }
36497dc7771cSEwan Crawford 
36507dc7771cSEwan Crawford         RenderScriptRuntime *runtime =
36517dc7771cSEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
36527dc7771cSEwan Crawford 
36537dc7771cSEwan Crawford         bool do_break = false;
36547dc7771cSEwan Crawford         const char* argument = command.GetArgumentAtIndex(0);
36557dc7771cSEwan Crawford         if (strcmp(argument, "enable") == 0)
36567dc7771cSEwan Crawford         {
36577dc7771cSEwan Crawford             do_break = true;
36587dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will be set on all kernels.");
36597dc7771cSEwan Crawford         }
36607dc7771cSEwan Crawford         else if (strcmp(argument, "disable") == 0)
36617dc7771cSEwan Crawford         {
36627dc7771cSEwan Crawford             do_break = false;
36637dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will not be set on any new kernels.");
36647dc7771cSEwan Crawford         }
36657dc7771cSEwan Crawford         else
36667dc7771cSEwan Crawford         {
36677dc7771cSEwan Crawford             result.AppendErrorWithFormat("Argument must be either 'enable' or 'disable'");
36687dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
36697dc7771cSEwan Crawford             return false;
36707dc7771cSEwan Crawford         }
36717dc7771cSEwan Crawford 
36727dc7771cSEwan Crawford         runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
36737dc7771cSEwan Crawford 
36747dc7771cSEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
36757dc7771cSEwan Crawford         return true;
36767dc7771cSEwan Crawford     }
36777dc7771cSEwan Crawford };
36787dc7771cSEwan Crawford 
36797dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpoint : public CommandObjectMultiword
36807dc7771cSEwan Crawford {
36817dc7771cSEwan Crawford public:
36827dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpoint(CommandInterpreter &interpreter)
36837dc7771cSEwan Crawford         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that generate breakpoints on renderscript kernels.",
36847dc7771cSEwan Crawford                                  nullptr)
36857dc7771cSEwan Crawford     {
36867dc7771cSEwan Crawford         LoadSubCommand("set", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(interpreter)));
36877dc7771cSEwan Crawford         LoadSubCommand("all", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(interpreter)));
36887dc7771cSEwan Crawford     }
36897dc7771cSEwan Crawford 
3690222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
36917dc7771cSEwan Crawford };
36927dc7771cSEwan Crawford 
36934640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword
36944640cde1SColin Riley {
36954640cde1SColin Riley public:
36964640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
36974640cde1SColin Riley         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that deal with renderscript kernels.",
36984640cde1SColin Riley                                  NULL)
36994640cde1SColin Riley     {
37004640cde1SColin Riley         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(interpreter)));
37014640cde1SColin Riley         LoadSubCommand("breakpoint", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
37024640cde1SColin Riley     }
37034640cde1SColin Riley 
3704222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernel() override = default;
37054640cde1SColin Riley };
37064640cde1SColin Riley 
37074640cde1SColin Riley class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed
37084640cde1SColin Riley {
37094640cde1SColin Riley public:
37104640cde1SColin Riley     CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
37114640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript context dump",
37124640cde1SColin Riley                               "Dumps renderscript context information.", "renderscript context dump",
37134640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
37144640cde1SColin Riley     {
37154640cde1SColin Riley     }
37164640cde1SColin Riley 
3717222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeContextDump() override = default;
37184640cde1SColin Riley 
37194640cde1SColin Riley     bool
3720222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
37214640cde1SColin Riley     {
37224640cde1SColin Riley         RenderScriptRuntime *runtime =
37234640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
37244640cde1SColin Riley         runtime->DumpContexts(result.GetOutputStream());
37254640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
37264640cde1SColin Riley         return true;
37274640cde1SColin Riley     }
37284640cde1SColin Riley };
37294640cde1SColin Riley 
37304640cde1SColin Riley class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword
37314640cde1SColin Riley {
37324640cde1SColin Riley public:
37334640cde1SColin Riley     CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
37344640cde1SColin Riley         : CommandObjectMultiword(interpreter, "renderscript context", "Commands that deal with renderscript contexts.",
37354640cde1SColin Riley                                  NULL)
37364640cde1SColin Riley     {
37374640cde1SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(interpreter)));
37384640cde1SColin Riley     }
37394640cde1SColin Riley 
3740222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeContext() override = default;
37414640cde1SColin Riley };
37424640cde1SColin Riley 
3743a0f08674SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationDump : public CommandObjectParsed
3744a0f08674SEwan Crawford {
3745a0f08674SEwan Crawford public:
3746a0f08674SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationDump(CommandInterpreter &interpreter)
3747a0f08674SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation dump",
3748a0f08674SEwan Crawford                               "Displays the contents of a particular allocation", "renderscript allocation dump <ID>",
3749a0f08674SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter)
3750a0f08674SEwan Crawford     {
3751a0f08674SEwan Crawford     }
3752a0f08674SEwan Crawford 
3753222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
3754222b937cSEugene Zelenko 
3755222b937cSEugene Zelenko     Options*
3756222b937cSEugene Zelenko     GetOptions() override
3757a0f08674SEwan Crawford     {
3758a0f08674SEwan Crawford         return &m_options;
3759a0f08674SEwan Crawford     }
3760a0f08674SEwan Crawford 
3761a0f08674SEwan Crawford     class CommandOptions : public Options
3762a0f08674SEwan Crawford     {
3763a0f08674SEwan Crawford     public:
3764a0f08674SEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter)
3765a0f08674SEwan Crawford         {
3766a0f08674SEwan Crawford         }
3767a0f08674SEwan Crawford 
3768222b937cSEugene Zelenko         ~CommandOptions() override = default;
3769a0f08674SEwan Crawford 
3770222b937cSEugene Zelenko         Error
3771222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
3772a0f08674SEwan Crawford         {
3773a0f08674SEwan Crawford             Error error;
3774a0f08674SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
3775a0f08674SEwan Crawford 
3776a0f08674SEwan Crawford             switch (short_option)
3777a0f08674SEwan Crawford             {
3778a0f08674SEwan Crawford                 case 'f':
3779a0f08674SEwan Crawford                     m_outfile.SetFile(option_arg, true);
3780a0f08674SEwan Crawford                     if (m_outfile.Exists())
3781a0f08674SEwan Crawford                     {
3782a0f08674SEwan Crawford                         m_outfile.Clear();
3783a0f08674SEwan Crawford                         error.SetErrorStringWithFormat("file already exists: '%s'", option_arg);
3784a0f08674SEwan Crawford                     }
3785a0f08674SEwan Crawford                     break;
3786a0f08674SEwan Crawford                 default:
3787a0f08674SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3788a0f08674SEwan Crawford                     break;
3789a0f08674SEwan Crawford             }
3790a0f08674SEwan Crawford             return error;
3791a0f08674SEwan Crawford         }
3792a0f08674SEwan Crawford 
3793a0f08674SEwan Crawford         void
3794222b937cSEugene Zelenko         OptionParsingStarting() override
3795a0f08674SEwan Crawford         {
3796a0f08674SEwan Crawford             m_outfile.Clear();
3797a0f08674SEwan Crawford         }
3798a0f08674SEwan Crawford 
3799a0f08674SEwan Crawford         const OptionDefinition*
3800222b937cSEugene Zelenko         GetDefinitions() override
3801a0f08674SEwan Crawford         {
3802a0f08674SEwan Crawford             return g_option_table;
3803a0f08674SEwan Crawford         }
3804a0f08674SEwan Crawford 
3805a0f08674SEwan Crawford         static OptionDefinition g_option_table[];
3806a0f08674SEwan Crawford         FileSpec m_outfile;
3807a0f08674SEwan Crawford     };
3808a0f08674SEwan Crawford 
3809a0f08674SEwan Crawford     bool
3810222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
3811a0f08674SEwan Crawford     {
3812a0f08674SEwan Crawford         const size_t argc = command.GetArgumentCount();
3813a0f08674SEwan Crawford         if (argc < 1)
3814a0f08674SEwan Crawford         {
3815a0f08674SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. As well as an optional -f argument",
3816a0f08674SEwan Crawford                                          m_cmd_name.c_str());
3817a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3818a0f08674SEwan Crawford             return false;
3819a0f08674SEwan Crawford         }
3820a0f08674SEwan Crawford 
3821a0f08674SEwan Crawford         RenderScriptRuntime *runtime =
3822a0f08674SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
3823a0f08674SEwan Crawford 
3824a0f08674SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
3825a0f08674SEwan Crawford         bool convert_complete = false;
3826a0f08674SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
3827a0f08674SEwan Crawford         if (!convert_complete)
3828a0f08674SEwan Crawford         {
3829a0f08674SEwan Crawford             result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
3830a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3831a0f08674SEwan Crawford             return false;
3832a0f08674SEwan Crawford         }
3833a0f08674SEwan Crawford 
3834a0f08674SEwan Crawford         Stream* output_strm = nullptr;
3835a0f08674SEwan Crawford         StreamFile outfile_stream;
3836a0f08674SEwan Crawford         const FileSpec &outfile_spec = m_options.m_outfile; // Dump allocation to file instead
3837a0f08674SEwan Crawford         if (outfile_spec)
3838a0f08674SEwan Crawford         {
3839a0f08674SEwan Crawford             // Open output file
3840a0f08674SEwan Crawford             char path[256];
3841a0f08674SEwan Crawford             outfile_spec.GetPath(path, sizeof(path));
3842a0f08674SEwan Crawford             if (outfile_stream.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate).Success())
3843a0f08674SEwan Crawford             {
3844a0f08674SEwan Crawford                 output_strm = &outfile_stream;
3845a0f08674SEwan Crawford                 result.GetOutputStream().Printf("Results written to '%s'", path);
3846a0f08674SEwan Crawford                 result.GetOutputStream().EOL();
3847a0f08674SEwan Crawford             }
3848a0f08674SEwan Crawford             else
3849a0f08674SEwan Crawford             {
3850a0f08674SEwan Crawford                 result.AppendErrorWithFormat("Couldn't open file '%s'", path);
3851a0f08674SEwan Crawford                 result.SetStatus(eReturnStatusFailed);
3852a0f08674SEwan Crawford                 return false;
3853a0f08674SEwan Crawford             }
3854a0f08674SEwan Crawford         }
3855a0f08674SEwan Crawford         else
3856a0f08674SEwan Crawford             output_strm = &result.GetOutputStream();
3857a0f08674SEwan Crawford 
3858a0f08674SEwan Crawford         assert(output_strm != nullptr);
3859a0f08674SEwan Crawford         bool success = runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
3860a0f08674SEwan Crawford 
3861a0f08674SEwan Crawford         if (success)
3862a0f08674SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
3863a0f08674SEwan Crawford         else
3864a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3865a0f08674SEwan Crawford 
3866a0f08674SEwan Crawford         return true;
3867a0f08674SEwan Crawford     }
3868a0f08674SEwan Crawford 
3869a0f08674SEwan Crawford private:
3870a0f08674SEwan Crawford     CommandOptions m_options;
3871a0f08674SEwan Crawford };
3872a0f08674SEwan Crawford 
3873a0f08674SEwan Crawford OptionDefinition
3874a0f08674SEwan Crawford CommandObjectRenderScriptRuntimeAllocationDump::CommandOptions::g_option_table[] =
3875a0f08674SEwan Crawford {
3876a0f08674SEwan Crawford     { LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename,
3877a0f08674SEwan Crawford       "Print results to specified file instead of command line."},
3878a0f08674SEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
3879a0f08674SEwan Crawford };
3880a0f08674SEwan Crawford 
388115f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationList : public CommandObjectParsed
388215f2bd95SEwan Crawford {
388315f2bd95SEwan Crawford public:
388415f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationList(CommandInterpreter &interpreter)
388515f2bd95SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation list",
388615f2bd95SEwan Crawford                               "List renderscript allocations and their information.", "renderscript allocation list",
388715f2bd95SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter)
388815f2bd95SEwan Crawford     {
388915f2bd95SEwan Crawford     }
389015f2bd95SEwan Crawford 
3891222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
3892222b937cSEugene Zelenko 
3893222b937cSEugene Zelenko     Options*
3894222b937cSEugene Zelenko     GetOptions() override
389515f2bd95SEwan Crawford     {
389615f2bd95SEwan Crawford         return &m_options;
389715f2bd95SEwan Crawford     }
389815f2bd95SEwan Crawford 
389915f2bd95SEwan Crawford     class CommandOptions : public Options
390015f2bd95SEwan Crawford     {
390115f2bd95SEwan Crawford     public:
390215f2bd95SEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter), m_refresh(false)
390315f2bd95SEwan Crawford         {
390415f2bd95SEwan Crawford         }
390515f2bd95SEwan Crawford 
3906222b937cSEugene Zelenko         ~CommandOptions() override = default;
390715f2bd95SEwan Crawford 
3908222b937cSEugene Zelenko         Error
3909222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
391015f2bd95SEwan Crawford         {
391115f2bd95SEwan Crawford             Error error;
391215f2bd95SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
391315f2bd95SEwan Crawford 
391415f2bd95SEwan Crawford             switch (short_option)
391515f2bd95SEwan Crawford             {
391615f2bd95SEwan Crawford                 case 'r':
391715f2bd95SEwan Crawford                     m_refresh = true;
391815f2bd95SEwan Crawford                     break;
391915f2bd95SEwan Crawford                 default:
392015f2bd95SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
392115f2bd95SEwan Crawford                     break;
392215f2bd95SEwan Crawford             }
392315f2bd95SEwan Crawford             return error;
392415f2bd95SEwan Crawford         }
392515f2bd95SEwan Crawford 
392615f2bd95SEwan Crawford         void
3927222b937cSEugene Zelenko         OptionParsingStarting() override
392815f2bd95SEwan Crawford         {
392915f2bd95SEwan Crawford             m_refresh = false;
393015f2bd95SEwan Crawford         }
393115f2bd95SEwan Crawford 
393215f2bd95SEwan Crawford         const OptionDefinition*
3933222b937cSEugene Zelenko         GetDefinitions() override
393415f2bd95SEwan Crawford         {
393515f2bd95SEwan Crawford             return g_option_table;
393615f2bd95SEwan Crawford         }
393715f2bd95SEwan Crawford 
393815f2bd95SEwan Crawford         static OptionDefinition g_option_table[];
393915f2bd95SEwan Crawford         bool m_refresh;
394015f2bd95SEwan Crawford     };
394115f2bd95SEwan Crawford 
394215f2bd95SEwan Crawford     bool
3943222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
394415f2bd95SEwan Crawford     {
394515f2bd95SEwan Crawford         RenderScriptRuntime *runtime =
394615f2bd95SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
394715f2bd95SEwan Crawford         runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(), m_options.m_refresh);
394815f2bd95SEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
394915f2bd95SEwan Crawford         return true;
395015f2bd95SEwan Crawford     }
395115f2bd95SEwan Crawford 
395215f2bd95SEwan Crawford private:
395315f2bd95SEwan Crawford     CommandOptions m_options;
395415f2bd95SEwan Crawford };
395515f2bd95SEwan Crawford 
395615f2bd95SEwan Crawford OptionDefinition
395715f2bd95SEwan Crawford CommandObjectRenderScriptRuntimeAllocationList::CommandOptions::g_option_table[] =
395815f2bd95SEwan Crawford {
395915f2bd95SEwan Crawford     { LLDB_OPT_SET_1, false, "refresh", 'r', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone,
396015f2bd95SEwan Crawford       "Recompute allocation details."},
396115f2bd95SEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
396215f2bd95SEwan Crawford };
396315f2bd95SEwan Crawford 
396455232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationLoad : public CommandObjectParsed
396555232f09SEwan Crawford {
396655232f09SEwan Crawford public:
396755232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationLoad(CommandInterpreter &interpreter)
396855232f09SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation load",
396955232f09SEwan Crawford                               "Loads renderscript allocation contents from a file.", "renderscript allocation load <ID> <filename>",
397055232f09SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
397155232f09SEwan Crawford     {
397255232f09SEwan Crawford     }
397355232f09SEwan Crawford 
3974222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
397555232f09SEwan Crawford 
397655232f09SEwan Crawford     bool
3977222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
397855232f09SEwan Crawford     {
397955232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
398055232f09SEwan Crawford         if (argc != 2)
398155232f09SEwan Crawford         {
398255232f09SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str());
398355232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
398455232f09SEwan Crawford             return false;
398555232f09SEwan Crawford         }
398655232f09SEwan Crawford 
398755232f09SEwan Crawford         RenderScriptRuntime *runtime =
398855232f09SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
398955232f09SEwan Crawford 
399055232f09SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
399155232f09SEwan Crawford         bool convert_complete = false;
399255232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
399355232f09SEwan Crawford         if (!convert_complete)
399455232f09SEwan Crawford         {
399555232f09SEwan Crawford             result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr);
399655232f09SEwan Crawford             result.SetStatus (eReturnStatusFailed);
399755232f09SEwan Crawford             return false;
399855232f09SEwan Crawford         }
399955232f09SEwan Crawford 
400055232f09SEwan Crawford         const char* filename = command.GetArgumentAtIndex(1);
400155232f09SEwan Crawford         bool success = runtime->LoadAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
400255232f09SEwan Crawford 
400355232f09SEwan Crawford         if (success)
400455232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
400555232f09SEwan Crawford         else
400655232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
400755232f09SEwan Crawford 
400855232f09SEwan Crawford         return true;
400955232f09SEwan Crawford     }
401055232f09SEwan Crawford };
401155232f09SEwan Crawford 
401255232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationSave : public CommandObjectParsed
401355232f09SEwan Crawford {
401455232f09SEwan Crawford public:
401555232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationSave(CommandInterpreter &interpreter)
401655232f09SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation save",
401755232f09SEwan Crawford                               "Write renderscript allocation contents to a file.", "renderscript allocation save <ID> <filename>",
401855232f09SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
401955232f09SEwan Crawford     {
402055232f09SEwan Crawford     }
402155232f09SEwan Crawford 
4022222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
402355232f09SEwan Crawford 
402455232f09SEwan Crawford     bool
4025222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
402655232f09SEwan Crawford     {
402755232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
402855232f09SEwan Crawford         if (argc != 2)
402955232f09SEwan Crawford         {
403055232f09SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str());
403155232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
403255232f09SEwan Crawford             return false;
403355232f09SEwan Crawford         }
403455232f09SEwan Crawford 
403555232f09SEwan Crawford         RenderScriptRuntime *runtime =
403655232f09SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
403755232f09SEwan Crawford 
403855232f09SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
403955232f09SEwan Crawford         bool convert_complete = false;
404055232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
404155232f09SEwan Crawford         if (!convert_complete)
404255232f09SEwan Crawford         {
404355232f09SEwan Crawford             result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr);
404455232f09SEwan Crawford             result.SetStatus (eReturnStatusFailed);
404555232f09SEwan Crawford             return false;
404655232f09SEwan Crawford         }
404755232f09SEwan Crawford 
404855232f09SEwan Crawford         const char* filename = command.GetArgumentAtIndex(1);
404955232f09SEwan Crawford         bool success = runtime->SaveAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
405055232f09SEwan Crawford 
405155232f09SEwan Crawford         if (success)
405255232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
405355232f09SEwan Crawford         else
405455232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
405555232f09SEwan Crawford 
405655232f09SEwan Crawford         return true;
405755232f09SEwan Crawford     }
405855232f09SEwan Crawford };
405955232f09SEwan Crawford 
406015f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocation : public CommandObjectMultiword
406115f2bd95SEwan Crawford {
406215f2bd95SEwan Crawford public:
406315f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
406415f2bd95SEwan Crawford         : CommandObjectMultiword(interpreter, "renderscript allocation", "Commands that deal with renderscript allocations.",
406515f2bd95SEwan Crawford                                  NULL)
406615f2bd95SEwan Crawford     {
406715f2bd95SEwan Crawford         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4068a0f08674SEwan Crawford         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
406955232f09SEwan Crawford         LoadSubCommand("save", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
407055232f09SEwan Crawford         LoadSubCommand("load", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
407115f2bd95SEwan Crawford     }
407215f2bd95SEwan Crawford 
4073222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocation() override = default;
407415f2bd95SEwan Crawford };
407515f2bd95SEwan Crawford 
40764640cde1SColin Riley class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed
40774640cde1SColin Riley {
40784640cde1SColin Riley public:
40794640cde1SColin Riley     CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
40804640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript status",
40814640cde1SColin Riley                               "Displays current renderscript runtime status.", "renderscript status",
40824640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
40834640cde1SColin Riley     {
40844640cde1SColin Riley     }
40854640cde1SColin Riley 
4086222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeStatus() override = default;
40874640cde1SColin Riley 
40884640cde1SColin Riley     bool
4089222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
40904640cde1SColin Riley     {
40914640cde1SColin Riley         RenderScriptRuntime *runtime =
40924640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
40934640cde1SColin Riley         runtime->Status(result.GetOutputStream());
40944640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
40954640cde1SColin Riley         return true;
40964640cde1SColin Riley     }
40974640cde1SColin Riley };
40984640cde1SColin Riley 
40995ec532a9SColin Riley class CommandObjectRenderScriptRuntime : public CommandObjectMultiword
41005ec532a9SColin Riley {
41015ec532a9SColin Riley public:
41025ec532a9SColin Riley     CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
41035ec532a9SColin Riley         : CommandObjectMultiword(interpreter, "renderscript", "A set of commands for operating on renderscript.",
41045ec532a9SColin Riley                                  "renderscript <subcommand> [<subcommand-options>]")
41055ec532a9SColin Riley     {
41065ec532a9SColin Riley         LoadSubCommand("module", CommandObjectSP(new CommandObjectRenderScriptRuntimeModule(interpreter)));
41074640cde1SColin Riley         LoadSubCommand("status", CommandObjectSP(new CommandObjectRenderScriptRuntimeStatus(interpreter)));
41084640cde1SColin Riley         LoadSubCommand("kernel", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernel(interpreter)));
41094640cde1SColin Riley         LoadSubCommand("context", CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(interpreter)));
411015f2bd95SEwan Crawford         LoadSubCommand("allocation", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
41115ec532a9SColin Riley     }
41125ec532a9SColin Riley 
4113222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntime() override = default;
41145ec532a9SColin Riley };
4115ef20b08fSColin Riley 
4116ef20b08fSColin Riley void
4117ef20b08fSColin Riley RenderScriptRuntime::Initiate()
41185ec532a9SColin Riley {
4119ef20b08fSColin Riley     assert(!m_initiated);
41205ec532a9SColin Riley }
4121ef20b08fSColin Riley 
4122ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
41237dc7771cSEwan Crawford     : lldb_private::CPPLanguageRuntime(process), m_initiated(false), m_debuggerPresentFlagged(false),
41247dc7771cSEwan Crawford       m_breakAllKernels(false)
4125ef20b08fSColin Riley {
41264640cde1SColin Riley     ModulesDidLoad(process->GetTarget().GetImages());
4127ef20b08fSColin Riley }
41284640cde1SColin Riley 
41294640cde1SColin Riley lldb::CommandObjectSP
41304640cde1SColin Riley RenderScriptRuntime::GetCommandObject(lldb_private::CommandInterpreter& interpreter)
41314640cde1SColin Riley {
41324640cde1SColin Riley     static CommandObjectSP command_object;
41334640cde1SColin Riley     if(!command_object)
41344640cde1SColin Riley     {
41354640cde1SColin Riley         command_object.reset(new CommandObjectRenderScriptRuntime(interpreter));
41364640cde1SColin Riley     }
41374640cde1SColin Riley     return command_object;
41384640cde1SColin Riley }
41394640cde1SColin Riley 
414078f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
4141