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 
238*26e52a70SEwan Crawford     // The FileHeader struct specifies the header we use for writing allocations to a binary file.
239*26e52a70SEwan Crawford     // Our format begins with the ASCII characters "RSAD", identifying the file as an allocation dump.
240*26e52a70SEwan Crawford     // Member variables dims and hdr_size are then written consecutively, immediately followed by an instance of
241*26e52a70SEwan Crawford     // the ElementHeader struct. Because Elements can contain subelements, there may be more than one instance
242*26e52a70SEwan Crawford     // of the ElementHeader struct. With this first instance being the root element, and the other instances being
243*26e52a70SEwan Crawford     // the root's descendants. To identify which instances are an ElementHeader's children, each struct
244*26e52a70SEwan Crawford     // is immediately followed by a sequence of consecutive offsets to the start of its child structs.
245*26e52a70SEwan 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
249*26e52a70SEwan Crawford         uint32_t dims[3];      // Dimensions
250*26e52a70SEwan Crawford         uint16_t hdr_size;     // Header size in bytes, including all element headers
251*26e52a70SEwan Crawford     };
252*26e52a70SEwan Crawford 
253*26e52a70SEwan Crawford     struct ElementHeader
254*26e52a70SEwan 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
258*26e52a70SEwan Crawford         uint16_t vector_size;   // Vector width
259*26e52a70SEwan 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         "rsdScriptInvokeForEach", // name
58582780287SAidan Dodds         "_Z22rsdScriptInvokeForEachPKN7android12renderscript7ContextEPNS0_6ScriptEjPKNS0_10AllocationEPS6_PKvjPK12RsScriptCall", // symbol name 32bit
58682780287SAidan Dodds         "_Z22rsdScriptInvokeForEachPKN7android12renderscript7ContextEPNS0_6ScriptEjPKNS0_10AllocationEPS6_PKvmPK12RsScriptCall", // symbol name 64bit
58782780287SAidan Dodds         0, // version
58882780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
58982780287SAidan Dodds         nullptr // handler
59082780287SAidan Dodds     },
59182780287SAidan Dodds     {
59282780287SAidan Dodds         "rsdScriptInvokeForEachMulti", // name
59382780287SAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall", // symbol name 32bit
59482780287SAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall", // symbol name 64bit
59582780287SAidan Dodds         0, // version
59682780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
59782780287SAidan Dodds         nullptr // handler
59882780287SAidan Dodds     },
59982780287SAidan Dodds     {
60082780287SAidan Dodds         "rsdScriptInvokeFunction", // name
60182780287SAidan Dodds         "_Z23rsdScriptInvokeFunctionPKN7android12renderscript7ContextEPNS0_6ScriptEjPKvj", // symbol name 32bit
60282780287SAidan Dodds         "_Z23rsdScriptInvokeFunctionPKN7android12renderscript7ContextEPNS0_6ScriptEjPKvm", // symbol name 64bit
60382780287SAidan Dodds         0, // version
60482780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
60582780287SAidan Dodds         nullptr // handler
60682780287SAidan Dodds     },
60782780287SAidan Dodds     {
60882780287SAidan Dodds         "rsdScriptSetGlobalVar", // name
60982780287SAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvj", // symbol name 32bit
61082780287SAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvm", // symbol name 64bit
61182780287SAidan Dodds         0, // version
61282780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
61382780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar1 // handler
61482780287SAidan Dodds     },
6154640cde1SColin Riley 
6164640cde1SColin Riley     //rsdAllocation
61782780287SAidan Dodds     {
61882780287SAidan Dodds         "rsdAllocationInit", // name
61982780287SAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 32bit
62082780287SAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 64bit
62182780287SAidan Dodds         0, // version
62282780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
62382780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureAllocationInit1 // handler
62482780287SAidan Dodds     },
62582780287SAidan Dodds     {
62682780287SAidan Dodds         "rsdAllocationRead2D", //name
62782780287SAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvjj", // symbol name 32bit
62882780287SAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvmm", // symbol name 64bit
62982780287SAidan Dodds         0, // version
63082780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
63182780287SAidan Dodds         nullptr // handler
63282780287SAidan Dodds     },
633e69df382SEwan Crawford     {
634e69df382SEwan Crawford         "rsdAllocationDestroy", // name
635e69df382SEwan Crawford         "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE", // symbol name 32bit
636e69df382SEwan Crawford         "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE", // symbol name 64bit
637e69df382SEwan Crawford         0, // version
638e69df382SEwan Crawford         RenderScriptRuntime::eModuleKindDriver, // type
639e69df382SEwan Crawford         &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy // handler
640e69df382SEwan Crawford     },
6414640cde1SColin Riley };
6424640cde1SColin Riley 
643222b937cSEugene Zelenko const size_t RenderScriptRuntime::s_runtimeHookCount = sizeof(s_runtimeHookDefns)/sizeof(s_runtimeHookDefns[0]);
6444640cde1SColin Riley 
6454640cde1SColin Riley bool
6464640cde1SColin Riley RenderScriptRuntime::HookCallback(void *baton, StoppointCallbackContext *ctx, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
6474640cde1SColin Riley {
6484640cde1SColin Riley     RuntimeHook* hook_info = (RuntimeHook*)baton;
6494640cde1SColin Riley     ExecutionContext context(ctx->exe_ctx_ref);
6504640cde1SColin Riley 
6514640cde1SColin Riley     RenderScriptRuntime *lang_rt = (RenderScriptRuntime *)context.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
6524640cde1SColin Riley 
6534640cde1SColin Riley     lang_rt->HookCallback(hook_info, context);
6544640cde1SColin Riley 
6554640cde1SColin Riley     return false;
6564640cde1SColin Riley }
6574640cde1SColin Riley 
6584640cde1SColin Riley void
6594640cde1SColin Riley RenderScriptRuntime::HookCallback(RuntimeHook* hook_info, ExecutionContext& context)
6604640cde1SColin Riley {
6614640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
6624640cde1SColin Riley 
6634640cde1SColin Riley     if (log)
6644640cde1SColin Riley         log->Printf ("RenderScriptRuntime::HookCallback - '%s' .", hook_info->defn->name);
6654640cde1SColin Riley 
6664640cde1SColin Riley     if (hook_info->defn->grabber)
6674640cde1SColin Riley     {
6684640cde1SColin Riley         (this->*(hook_info->defn->grabber))(hook_info, context);
6694640cde1SColin Riley     }
6704640cde1SColin Riley }
6714640cde1SColin Riley 
6724640cde1SColin Riley bool
67382780287SAidan Dodds RenderScriptRuntime::GetArgSimple(ExecutionContext &context, uint32_t arg, uint64_t *data)
6744640cde1SColin Riley {
675cdfb1485SEwan Crawford     // Get a positional integer argument.
676cdfb1485SEwan Crawford     // Given an ExecutionContext, ``context`` which should be a RenderScript
677cdfb1485SEwan Crawford     // frame, get the value of the positional argument ``arg`` and save its value
678cdfb1485SEwan Crawford     // to the address pointed to by ``data``.
679cdfb1485SEwan Crawford     // returns true on success, false otherwise.
680cdfb1485SEwan Crawford     // If unsuccessful, the value pointed to by ``data`` is undefined. Otherwise,
681cdfb1485SEwan Crawford     // ``data`` will be set to the value of the the given ``arg``.
682cdfb1485SEwan Crawford     // NOTE: only natural width integer arguments for the machine are supported.
683cdfb1485SEwan Crawford     // Behaviour with non primitive arguments is undefined.
684cdfb1485SEwan Crawford 
6854640cde1SColin Riley     if (!data)
6864640cde1SColin Riley         return false;
6874640cde1SColin Riley 
68882780287SAidan Dodds     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
6894640cde1SColin Riley     Error error;
6904640cde1SColin Riley     RegisterContext* reg_ctx = context.GetRegisterContext();
6914640cde1SColin Riley     Process* process = context.GetProcessPtr();
69282780287SAidan Dodds     bool success = false; // return value
6934640cde1SColin Riley 
69482780287SAidan Dodds     if (!context.GetTargetPtr())
69582780287SAidan Dodds     {
69682780287SAidan Dodds         if (log)
69782780287SAidan Dodds             log->Printf("RenderScriptRuntime::GetArgSimple - Invalid target");
69882780287SAidan Dodds 
69982780287SAidan Dodds         return false;
70082780287SAidan Dodds     }
70182780287SAidan Dodds 
70282780287SAidan Dodds     switch (context.GetTargetPtr()->GetArchitecture().GetMachine())
70382780287SAidan Dodds     {
70482780287SAidan Dodds         case llvm::Triple::ArchType::x86:
7054640cde1SColin Riley         {
7064640cde1SColin Riley             uint64_t sp = reg_ctx->GetSP();
7074640cde1SColin Riley             uint32_t offset = (1 + arg) * sizeof(uint32_t);
70882780287SAidan Dodds             uint32_t result = 0;
70982780287SAidan Dodds             process->ReadMemory(sp + offset, &result, sizeof(uint32_t), error);
7104640cde1SColin Riley             if (error.Fail())
7114640cde1SColin Riley             {
7124640cde1SColin Riley                 if (log)
71382780287SAidan Dodds                     log->Printf("RenderScriptRuntime::GetArgSimple - error reading X86 stack: %s.", error.AsCString());
7144640cde1SColin Riley             }
71582780287SAidan Dodds             else
7164640cde1SColin Riley             {
71782780287SAidan Dodds                 *data = result;
71882780287SAidan Dodds                 success = true;
71982780287SAidan Dodds             }
72082780287SAidan Dodds             break;
72182780287SAidan Dodds         }
722cdfb1485SEwan Crawford         case llvm::Triple::ArchType::x86_64:
723cdfb1485SEwan Crawford         {
724cdfb1485SEwan Crawford             // amd64 has 6 integer registers, and 8 XMM registers for parameter passing.
725cdfb1485SEwan Crawford             // Surplus args are spilled onto the stack.
726cdfb1485SEwan Crawford             // rdi, rsi, rdx, rcx, r8, r9, (zmm0 - 7 for vectors)
727cdfb1485SEwan Crawford             // ref: AMD64 ABI Draft 0.99.6 – October 7, 2013 – 10:35; Figure 3.4. Retrieved from
728cdfb1485SEwan Crawford             // http://www.x86-64.org/documentation/abi.pdf
729cdfb1485SEwan Crawford             if (arg > 5)
730cdfb1485SEwan Crawford             {
731cdfb1485SEwan Crawford                 if (log)
732cdfb1485SEwan Crawford                     log->Warning("X86_64 register spill is not supported.");
733cdfb1485SEwan Crawford                 break;
734cdfb1485SEwan Crawford             }
735cdfb1485SEwan Crawford             const char * regnames[] = {"rdi", "rsi", "rdx", "rcx", "r8", "r9"};
736cdfb1485SEwan Crawford             assert((sizeof(regnames) / sizeof(const char *)) > arg);
737cdfb1485SEwan Crawford             const RegisterInfo *rArg = reg_ctx->GetRegisterInfoByName(regnames[arg]);
738cdfb1485SEwan Crawford             RegisterValue rVal;
739cdfb1485SEwan Crawford             success = reg_ctx->ReadRegister(rArg, rVal);
740cdfb1485SEwan Crawford             if (success)
741cdfb1485SEwan Crawford             {
742cdfb1485SEwan Crawford                 *data = rVal.GetAsUInt64(0u, &success);
743cdfb1485SEwan Crawford             }
744cdfb1485SEwan Crawford             else
745cdfb1485SEwan Crawford             {
746cdfb1485SEwan Crawford                 if (log)
747cdfb1485SEwan Crawford                     log->Printf("RenderScriptRuntime::GetArgSimple - error reading x86_64 register: %d.", arg);
748cdfb1485SEwan Crawford             }
749cdfb1485SEwan Crawford             break;
750cdfb1485SEwan Crawford         }
75182780287SAidan Dodds         case llvm::Triple::ArchType::arm:
75282780287SAidan Dodds         {
75382780287SAidan Dodds             // arm 32 bit
75435e7b1adSAidan Dodds             // first 4 arguments are passed via registers
7554640cde1SColin Riley             if (arg < 4)
7564640cde1SColin Riley             {
7574640cde1SColin Riley                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg);
7584640cde1SColin Riley                 RegisterValue rVal;
75902f1c5d1SEwan Crawford                 success = reg_ctx->ReadRegister(rArg, rVal);
76002f1c5d1SEwan Crawford                 if (success)
76102f1c5d1SEwan Crawford                 {
762cdfb1485SEwan Crawford                     (*data) = rVal.GetAsUInt32(0u, &success);
76302f1c5d1SEwan Crawford                 }
76402f1c5d1SEwan Crawford                 else
76502f1c5d1SEwan Crawford                 {
76602f1c5d1SEwan Crawford                     if (log)
76702f1c5d1SEwan Crawford                         log->Printf("RenderScriptRuntime::GetArgSimple - error reading ARM register: %d.", arg);
76802f1c5d1SEwan Crawford                 }
7694640cde1SColin Riley             }
7704640cde1SColin Riley             else
7714640cde1SColin Riley             {
7724640cde1SColin Riley                 uint64_t sp = reg_ctx->GetSP();
7734640cde1SColin Riley                 uint32_t offset = (arg-4) * sizeof(uint32_t);
77435e7b1adSAidan Dodds                 uint32_t value = 0;
77535e7b1adSAidan Dodds                 size_t bytes_read = process->ReadMemory(sp + offset, &value, sizeof(value), error);
77635e7b1adSAidan Dodds                 if (error.Fail() || bytes_read != sizeof(value))
7774640cde1SColin Riley                 {
7784640cde1SColin Riley                     if (log)
77982780287SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple - error reading ARM stack: %s.", error.AsCString());
78082780287SAidan Dodds                 }
78182780287SAidan Dodds                 else
78282780287SAidan Dodds                 {
78335e7b1adSAidan Dodds                     *data = value;
78482780287SAidan Dodds                     success = true;
7854640cde1SColin Riley                 }
7864640cde1SColin Riley             }
78782780287SAidan Dodds             break;
7884640cde1SColin Riley         }
78982780287SAidan Dodds         case llvm::Triple::ArchType::aarch64:
79082780287SAidan Dodds         {
79182780287SAidan Dodds             // arm 64 bit
79282780287SAidan Dodds             // first 8 arguments are in the registers
79382780287SAidan Dodds             if (arg < 8)
79482780287SAidan Dodds             {
79582780287SAidan Dodds                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg);
79682780287SAidan Dodds                 RegisterValue rVal;
79782780287SAidan Dodds                 success = reg_ctx->ReadRegister(rArg, rVal);
79882780287SAidan Dodds                 if (success)
79982780287SAidan Dodds                 {
800cdfb1485SEwan Crawford                     *data = rVal.GetAsUInt64(0u, &success);
80182780287SAidan Dodds                 }
80282780287SAidan Dodds                 else
80382780287SAidan Dodds                 {
80482780287SAidan Dodds                     if (log)
80582780287SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple() - AARCH64 - Error while reading the argument #%d", arg);
80682780287SAidan Dodds                 }
80782780287SAidan Dodds             }
80882780287SAidan Dodds             else
80982780287SAidan Dodds             {
81082780287SAidan Dodds                 // @TODO: need to find the argument in the stack
81182780287SAidan Dodds                 if (log)
81282780287SAidan Dodds                     log->Printf("RenderScriptRuntime::GetArgSimple - AARCH64 - FOR #ARG >= 8 NOT IMPLEMENTED YET. Argument number: %d", arg);
81382780287SAidan Dodds             }
81482780287SAidan Dodds             break;
81582780287SAidan Dodds         }
81674b396d9SAidan Dodds         case llvm::Triple::ArchType::mipsel:
81774b396d9SAidan Dodds         {
81874b396d9SAidan Dodds             // read from the registers
81935e7b1adSAidan Dodds             // first 4 arguments are passed in registers
82074b396d9SAidan Dodds             if (arg < 4){
82174b396d9SAidan Dodds                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg + 4);
82274b396d9SAidan Dodds                 RegisterValue rVal;
82374b396d9SAidan Dodds                 success = reg_ctx->ReadRegister(rArg, rVal);
82474b396d9SAidan Dodds                 if (success)
82574b396d9SAidan Dodds                 {
826cdfb1485SEwan Crawford                     *data = rVal.GetAsUInt64(0u, &success);
82774b396d9SAidan Dodds                 }
82874b396d9SAidan Dodds                 else
82974b396d9SAidan Dodds                 {
83074b396d9SAidan Dodds                     if (log)
83174b396d9SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple() - Mips - Error while reading the argument #%d", arg);
83274b396d9SAidan Dodds                 }
83374b396d9SAidan Dodds             }
83435e7b1adSAidan Dodds             // arguments > 4 are read from the stack
83574b396d9SAidan Dodds             else
83674b396d9SAidan Dodds             {
83774b396d9SAidan Dodds                 uint64_t sp = reg_ctx->GetSP();
83874b396d9SAidan Dodds                 uint32_t offset = arg * sizeof(uint32_t);
83935e7b1adSAidan Dodds                 uint32_t value = 0;
84035e7b1adSAidan Dodds                 size_t bytes_read = process->ReadMemory(sp + offset, &value, sizeof(value), error);
84135e7b1adSAidan Dodds                 if (error.Fail() || bytes_read != sizeof(value))
84274b396d9SAidan Dodds                 {
84374b396d9SAidan Dodds                     if (log)
84474b396d9SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple - error reading Mips stack: %s.", error.AsCString());
84574b396d9SAidan Dodds                 }
84674b396d9SAidan Dodds                 else
84774b396d9SAidan Dodds                 {
84835e7b1adSAidan Dodds                     *data = value;
84974b396d9SAidan Dodds                     success = true;
85074b396d9SAidan Dodds                 }
85174b396d9SAidan Dodds             }
85274b396d9SAidan Dodds             break;
85374b396d9SAidan Dodds         }
85402f1c5d1SEwan Crawford         case llvm::Triple::ArchType::mips64el:
85502f1c5d1SEwan Crawford         {
85602f1c5d1SEwan Crawford             // read from the registers
85702f1c5d1SEwan Crawford             if (arg < 8)
85802f1c5d1SEwan Crawford             {
85902f1c5d1SEwan Crawford                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg + 4);
86002f1c5d1SEwan Crawford                 RegisterValue rVal;
86102f1c5d1SEwan Crawford                 success = reg_ctx->ReadRegister(rArg, rVal);
86202f1c5d1SEwan Crawford                 if (success)
86302f1c5d1SEwan Crawford                 {
864cdfb1485SEwan Crawford                     (*data) = rVal.GetAsUInt64(0u, &success);
86502f1c5d1SEwan Crawford                 }
86602f1c5d1SEwan Crawford                 else
86702f1c5d1SEwan Crawford                 {
86802f1c5d1SEwan Crawford                     if (log)
86902f1c5d1SEwan Crawford                         log->Printf("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading the argument #%d", arg);
87002f1c5d1SEwan Crawford                 }
87102f1c5d1SEwan Crawford             }
87235e7b1adSAidan Dodds             // arguments > 8 are read from the stack
87302f1c5d1SEwan Crawford             else
87402f1c5d1SEwan Crawford             {
87502f1c5d1SEwan Crawford                 uint64_t sp = reg_ctx->GetSP();
87602f1c5d1SEwan Crawford                 uint32_t offset = (arg - 8) * sizeof(uint64_t);
87735e7b1adSAidan Dodds                 uint64_t value = 0;
87835e7b1adSAidan Dodds                 size_t bytes_read = process->ReadMemory(sp + offset, &value, sizeof(value), error);
87935e7b1adSAidan Dodds                 if (error.Fail() || bytes_read != sizeof(value))
88002f1c5d1SEwan Crawford                 {
88102f1c5d1SEwan Crawford                     if (log)
88202f1c5d1SEwan Crawford                         log->Printf("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading Mips64 stack: %s.", error.AsCString());
88302f1c5d1SEwan Crawford                 }
88402f1c5d1SEwan Crawford                 else
88502f1c5d1SEwan Crawford                 {
88635e7b1adSAidan Dodds                     *data = value;
88702f1c5d1SEwan Crawford                     success = true;
88802f1c5d1SEwan Crawford                 }
88902f1c5d1SEwan Crawford             }
89002f1c5d1SEwan Crawford             break;
89102f1c5d1SEwan Crawford         }
89282780287SAidan Dodds         default:
89382780287SAidan Dodds         {
89482780287SAidan Dodds             // invalid architecture
89582780287SAidan Dodds             if (log)
89682780287SAidan Dodds                 log->Printf("RenderScriptRuntime::GetArgSimple - Architecture not supported");
89782780287SAidan Dodds         }
89882780287SAidan Dodds     }
89982780287SAidan Dodds 
900cdfb1485SEwan Crawford     if (!success)
901cdfb1485SEwan Crawford     {
902cdfb1485SEwan Crawford         if (log)
903cdfb1485SEwan Crawford             log->Printf("RenderScriptRuntime::GetArgSimple - failed to get argument at index %" PRIu32, arg);
904cdfb1485SEwan Crawford     }
90582780287SAidan Dodds     return success;
9064640cde1SColin Riley }
9074640cde1SColin Riley 
9084640cde1SColin Riley void
9094640cde1SColin Riley RenderScriptRuntime::CaptureSetGlobalVar1(RuntimeHook* hook_info, ExecutionContext& context)
9104640cde1SColin Riley {
9114640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
9124640cde1SColin Riley 
9134640cde1SColin Riley     //Context, Script, int, data, length
9144640cde1SColin Riley 
91582780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
91682780287SAidan Dodds     uint64_t rs_script_u64 = 0U;
91782780287SAidan Dodds     uint64_t rs_id_u64 = 0U;
91882780287SAidan Dodds     uint64_t rs_data_u64 = 0U;
91982780287SAidan Dodds     uint64_t rs_length_u64 = 0U;
9204640cde1SColin Riley 
92182780287SAidan Dodds     bool success =
92282780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
92382780287SAidan Dodds         GetArgSimple(context, 1, &rs_script_u64) &&
92482780287SAidan Dodds         GetArgSimple(context, 2, &rs_id_u64) &&
92582780287SAidan Dodds         GetArgSimple(context, 3, &rs_data_u64) &&
92682780287SAidan Dodds         GetArgSimple(context, 4, &rs_length_u64);
9274640cde1SColin Riley 
92882780287SAidan Dodds     if (!success)
92982780287SAidan Dodds     {
93082780287SAidan Dodds         if (log)
93182780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureSetGlobalVar1 - Error while reading the function parameters");
93282780287SAidan Dodds         return;
93382780287SAidan Dodds     }
9344640cde1SColin Riley 
9354640cde1SColin Riley     if (log)
9364640cde1SColin Riley     {
9374640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64 ":%" PRIu64 "bytes.",
93882780287SAidan Dodds                         rs_context_u64, rs_script_u64, rs_id_u64, rs_data_u64, rs_length_u64);
9394640cde1SColin Riley 
94082780287SAidan Dodds         addr_t script_addr =  (addr_t)rs_script_u64;
9414640cde1SColin Riley         if (m_scriptMappings.find( script_addr ) != m_scriptMappings.end())
9424640cde1SColin Riley         {
9434640cde1SColin Riley             auto rsm = m_scriptMappings[script_addr];
94482780287SAidan Dodds             if (rs_id_u64 < rsm->m_globals.size())
9454640cde1SColin Riley             {
94682780287SAidan Dodds                 auto rsg = rsm->m_globals[rs_id_u64];
9474640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - Setting of '%s' within '%s' inferred", rsg.m_name.AsCString(),
9484640cde1SColin Riley                                 rsm->m_module->GetFileSpec().GetFilename().AsCString());
9494640cde1SColin Riley             }
9504640cde1SColin Riley         }
9514640cde1SColin Riley     }
9524640cde1SColin Riley }
9534640cde1SColin Riley 
9544640cde1SColin Riley void
9554640cde1SColin Riley RenderScriptRuntime::CaptureAllocationInit1(RuntimeHook* hook_info, ExecutionContext& context)
9564640cde1SColin Riley {
9574640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
9584640cde1SColin Riley 
9594640cde1SColin Riley     //Context, Alloc, bool
9604640cde1SColin Riley 
96182780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
96282780287SAidan Dodds     uint64_t rs_alloc_u64 = 0U;
96382780287SAidan Dodds     uint64_t rs_forceZero_u64 = 0U;
9644640cde1SColin Riley 
96582780287SAidan Dodds     bool success =
96682780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
96782780287SAidan Dodds         GetArgSimple(context, 1, &rs_alloc_u64) &&
96882780287SAidan Dodds         GetArgSimple(context, 2, &rs_forceZero_u64);
96982780287SAidan Dodds     if (!success) // error case
97082780287SAidan Dodds     {
97182780287SAidan Dodds         if (log)
97282780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureAllocationInit1 - Error while reading the function parameters");
97382780287SAidan Dodds         return; // abort
97482780287SAidan Dodds     }
9754640cde1SColin Riley 
9764640cde1SColin Riley     if (log)
9774640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureAllocationInit1 - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
97882780287SAidan Dodds                         rs_context_u64, rs_alloc_u64, rs_forceZero_u64);
97978f339d1SEwan Crawford 
98078f339d1SEwan Crawford     AllocationDetails* alloc = LookUpAllocation(rs_alloc_u64, true);
98178f339d1SEwan Crawford     if (alloc)
98278f339d1SEwan Crawford         alloc->context = rs_context_u64;
9834640cde1SColin Riley }
9844640cde1SColin Riley 
9854640cde1SColin Riley void
986e69df382SEwan Crawford RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook* hook_info, ExecutionContext& context)
987e69df382SEwan Crawford {
988e69df382SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
989e69df382SEwan Crawford 
990e69df382SEwan Crawford     // Context, Alloc
991e69df382SEwan Crawford     uint64_t rs_context_u64 = 0U;
992e69df382SEwan Crawford     uint64_t rs_alloc_u64 = 0U;
993e69df382SEwan Crawford 
994e69df382SEwan Crawford     bool success = GetArgSimple(context, 0, &rs_context_u64) && GetArgSimple(context, 1, &rs_alloc_u64);
995e69df382SEwan Crawford     if (!success) // error case
996e69df382SEwan Crawford     {
997e69df382SEwan Crawford         if (log)
998e69df382SEwan Crawford             log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - Error while reading the function parameters");
999e69df382SEwan Crawford         return; // abort
1000e69df382SEwan Crawford     }
1001e69df382SEwan Crawford 
1002e69df382SEwan Crawford     if (log)
1003e69df382SEwan Crawford         log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - 0x%" PRIx64 ", 0x%" PRIx64 ".",
1004e69df382SEwan Crawford                     rs_context_u64, rs_alloc_u64);
1005e69df382SEwan Crawford 
1006e69df382SEwan Crawford     for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter)
1007e69df382SEwan Crawford     {
1008e69df382SEwan Crawford         auto& allocation_ap = *iter; // get the unique pointer
1009e69df382SEwan Crawford         if (allocation_ap->address.isValid() && *allocation_ap->address.get() == rs_alloc_u64)
1010e69df382SEwan Crawford         {
1011e69df382SEwan Crawford             m_allocations.erase(iter);
1012e69df382SEwan Crawford             if (log)
1013e69df382SEwan Crawford                 log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - Deleted allocation entry");
1014e69df382SEwan Crawford             return;
1015e69df382SEwan Crawford         }
1016e69df382SEwan Crawford     }
1017e69df382SEwan Crawford 
1018e69df382SEwan Crawford     if (log)
1019e69df382SEwan Crawford         log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - Couldn't find destroyed allocation");
1020e69df382SEwan Crawford }
1021e69df382SEwan Crawford 
1022e69df382SEwan Crawford void
10234640cde1SColin Riley RenderScriptRuntime::CaptureScriptInit1(RuntimeHook* hook_info, ExecutionContext& context)
10244640cde1SColin Riley {
10254640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
10264640cde1SColin Riley 
10274640cde1SColin Riley     //Context, Script, resname Str, cachedir Str
10284640cde1SColin Riley     Error error;
10294640cde1SColin Riley     Process* process = context.GetProcessPtr();
10304640cde1SColin Riley 
103182780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
103282780287SAidan Dodds     uint64_t rs_script_u64 = 0U;
103382780287SAidan Dodds     uint64_t rs_resnameptr_u64 = 0U;
103482780287SAidan Dodds     uint64_t rs_cachedirptr_u64 = 0U;
10354640cde1SColin Riley 
10364640cde1SColin Riley     std::string resname;
10374640cde1SColin Riley     std::string cachedir;
10384640cde1SColin Riley 
103982780287SAidan Dodds     // read the function parameters
104082780287SAidan Dodds     bool success =
104182780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
104282780287SAidan Dodds         GetArgSimple(context, 1, &rs_script_u64) &&
104382780287SAidan Dodds         GetArgSimple(context, 2, &rs_resnameptr_u64) &&
104482780287SAidan Dodds         GetArgSimple(context, 3, &rs_cachedirptr_u64);
10454640cde1SColin Riley 
104682780287SAidan Dodds     if (!success)
104782780287SAidan Dodds     {
104882780287SAidan Dodds         if (log)
104982780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureScriptInit1 - Error while reading the function parameters");
105082780287SAidan Dodds         return;
105182780287SAidan Dodds     }
105282780287SAidan Dodds 
105382780287SAidan Dodds     process->ReadCStringFromMemory((lldb::addr_t)rs_resnameptr_u64, resname, error);
10544640cde1SColin Riley     if (error.Fail())
10554640cde1SColin Riley     {
10564640cde1SColin Riley         if (log)
10574640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading resname: %s.", error.AsCString());
10584640cde1SColin Riley 
10594640cde1SColin Riley     }
10604640cde1SColin Riley 
106182780287SAidan Dodds     process->ReadCStringFromMemory((lldb::addr_t)rs_cachedirptr_u64, cachedir, error);
10624640cde1SColin Riley     if (error.Fail())
10634640cde1SColin Riley     {
10644640cde1SColin Riley         if (log)
10654640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading cachedir: %s.", error.AsCString());
10664640cde1SColin Riley     }
10674640cde1SColin Riley 
10684640cde1SColin Riley     if (log)
10694640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
107082780287SAidan Dodds                      rs_context_u64, rs_script_u64, resname.c_str(), cachedir.c_str());
10714640cde1SColin Riley 
10724640cde1SColin Riley     if (resname.size() > 0)
10734640cde1SColin Riley     {
10744640cde1SColin Riley         StreamString strm;
10754640cde1SColin Riley         strm.Printf("librs.%s.so", resname.c_str());
10764640cde1SColin Riley 
107778f339d1SEwan Crawford         ScriptDetails* script = LookUpScript(rs_script_u64, true);
107878f339d1SEwan Crawford         if (script)
107978f339d1SEwan Crawford         {
108078f339d1SEwan Crawford             script->type = ScriptDetails::eScriptC;
108178f339d1SEwan Crawford             script->cacheDir = cachedir;
108278f339d1SEwan Crawford             script->resName = resname;
108378f339d1SEwan Crawford             script->scriptDyLib = strm.GetData();
108478f339d1SEwan Crawford             script->context = addr_t(rs_context_u64);
108578f339d1SEwan Crawford         }
10864640cde1SColin Riley 
10874640cde1SColin Riley         if (log)
10884640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - '%s' tagged with context 0x%" PRIx64 " and script 0x%" PRIx64 ".",
108982780287SAidan Dodds                          strm.GetData(), rs_context_u64, rs_script_u64);
10904640cde1SColin Riley     }
10914640cde1SColin Riley     else if (log)
10924640cde1SColin Riley     {
10934640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - resource name invalid, Script not tagged");
10944640cde1SColin Riley     }
10954640cde1SColin Riley }
10964640cde1SColin Riley 
10974640cde1SColin Riley void
10984640cde1SColin Riley RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind)
10994640cde1SColin Riley {
11004640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11014640cde1SColin Riley 
11024640cde1SColin Riley     if (!module)
11034640cde1SColin Riley     {
11044640cde1SColin Riley         return;
11054640cde1SColin Riley     }
11064640cde1SColin Riley 
110782780287SAidan Dodds     Target &target = GetProcess()->GetTarget();
110882780287SAidan Dodds     llvm::Triple::ArchType targetArchType = target.GetArchitecture().GetMachine();
110982780287SAidan Dodds 
111082780287SAidan Dodds     if (targetArchType != llvm::Triple::ArchType::x86
111182780287SAidan Dodds         && targetArchType != llvm::Triple::ArchType::arm
111202f1c5d1SEwan Crawford         && targetArchType != llvm::Triple::ArchType::aarch64
111374b396d9SAidan Dodds         && targetArchType != llvm::Triple::ArchType::mipsel
111402f1c5d1SEwan Crawford         && targetArchType != llvm::Triple::ArchType::mips64el
1115cdfb1485SEwan Crawford         && targetArchType != llvm::Triple::ArchType::x86_64
111602f1c5d1SEwan Crawford     )
11174640cde1SColin Riley     {
11184640cde1SColin Riley         if (log)
111974b396d9SAidan Dodds             log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to hook runtime. Only X86, ARM, Mips supported currently.");
11204640cde1SColin Riley 
11214640cde1SColin Riley         return;
11224640cde1SColin Riley     }
11234640cde1SColin Riley 
112482780287SAidan Dodds     uint32_t archByteSize = target.GetArchitecture().GetAddressByteSize();
11254640cde1SColin Riley 
11264640cde1SColin Riley     for (size_t idx = 0; idx < s_runtimeHookCount; idx++)
11274640cde1SColin Riley     {
11284640cde1SColin Riley         const HookDefn* hook_defn = &s_runtimeHookDefns[idx];
11294640cde1SColin Riley         if (hook_defn->kind != kind) {
11304640cde1SColin Riley             continue;
11314640cde1SColin Riley         }
11324640cde1SColin Riley 
113382780287SAidan Dodds         const char* symbol_name = (archByteSize == 4) ? hook_defn->symbol_name_m32 : hook_defn->symbol_name_m64;
113482780287SAidan Dodds 
113582780287SAidan Dodds         const Symbol *sym = module->FindFirstSymbolWithNameAndType(ConstString(symbol_name), eSymbolTypeCode);
113682780287SAidan Dodds         if (!sym){
113782780287SAidan Dodds             if (log){
113882780287SAidan Dodds                 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - ERROR: Symbol '%s' related to the function %s not found", symbol_name, hook_defn->name);
113982780287SAidan Dodds             }
114082780287SAidan Dodds             continue;
114182780287SAidan Dodds         }
11424640cde1SColin Riley 
1143358cf1eaSGreg Clayton         addr_t addr = sym->GetLoadAddress(&target);
11444640cde1SColin Riley         if (addr == LLDB_INVALID_ADDRESS)
11454640cde1SColin Riley         {
11464640cde1SColin Riley             if (log)
11474640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to resolve the address of hook function '%s' with symbol '%s'.",
114882780287SAidan Dodds                              hook_defn->name, symbol_name);
11494640cde1SColin Riley             continue;
11504640cde1SColin Riley         }
115182780287SAidan Dodds         else
115282780287SAidan Dodds         {
115382780287SAidan Dodds             if (log)
115482780287SAidan Dodds                 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - Function %s, address resolved at 0x%" PRIx64, hook_defn->name, addr);
115582780287SAidan Dodds         }
11564640cde1SColin Riley 
11574640cde1SColin Riley         RuntimeHookSP hook(new RuntimeHook());
11584640cde1SColin Riley         hook->address = addr;
11594640cde1SColin Riley         hook->defn = hook_defn;
11604640cde1SColin Riley         hook->bp_sp = target.CreateBreakpoint(addr, true, false);
11614640cde1SColin Riley         hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
11624640cde1SColin Riley         m_runtimeHooks[addr] = hook;
11634640cde1SColin Riley         if (log)
11644640cde1SColin Riley         {
11654640cde1SColin Riley             log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Successfully hooked '%s' in '%s' version %" PRIu64 " at 0x%" PRIx64 ".",
11664640cde1SColin Riley                 hook_defn->name, module->GetFileSpec().GetFilename().AsCString(), (uint64_t)hook_defn->version, (uint64_t)addr);
11674640cde1SColin Riley         }
11684640cde1SColin Riley     }
11694640cde1SColin Riley }
11704640cde1SColin Riley 
11714640cde1SColin Riley void
11724640cde1SColin Riley RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp)
11734640cde1SColin Riley {
11744640cde1SColin Riley     if (!rsmodule_sp)
11754640cde1SColin Riley         return;
11764640cde1SColin Riley 
11774640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11784640cde1SColin Riley 
11794640cde1SColin Riley     const ModuleSP module = rsmodule_sp->m_module;
11804640cde1SColin Riley     const FileSpec& file = module->GetPlatformFileSpec();
11814640cde1SColin Riley 
118278f339d1SEwan Crawford     // Iterate over all of the scripts that we currently know of.
118378f339d1SEwan Crawford     // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
11844640cde1SColin Riley     for (const auto & rs_script : m_scripts)
11854640cde1SColin Riley     {
118678f339d1SEwan Crawford         // Extract the expected .so file path for this script.
118778f339d1SEwan Crawford         std::string dylib;
118878f339d1SEwan Crawford         if (!rs_script->scriptDyLib.get(dylib))
118978f339d1SEwan Crawford             continue;
119078f339d1SEwan Crawford 
119178f339d1SEwan Crawford         // Only proceed if the module that has loaded corresponds to this script.
119278f339d1SEwan Crawford         if (file.GetFilename() != ConstString(dylib.c_str()))
119378f339d1SEwan Crawford             continue;
119478f339d1SEwan Crawford 
119578f339d1SEwan Crawford         // Obtain the script address which we use as a key.
119678f339d1SEwan Crawford         lldb::addr_t script;
119778f339d1SEwan Crawford         if (!rs_script->script.get(script))
119878f339d1SEwan Crawford             continue;
119978f339d1SEwan Crawford 
120078f339d1SEwan Crawford         // If we have a script mapping for the current script.
120178f339d1SEwan Crawford         if (m_scriptMappings.find(script) != m_scriptMappings.end())
12024640cde1SColin Riley         {
120378f339d1SEwan Crawford             // if the module we have stored is different to the one we just received.
120478f339d1SEwan Crawford             if (m_scriptMappings[script] != rsmodule_sp)
12054640cde1SColin Riley             {
12064640cde1SColin Riley                 if (log)
12074640cde1SColin Riley                     log->Printf ("RenderScriptRuntime::FixupScriptDetails - Error: script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
120878f339d1SEwan Crawford                                     (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
12094640cde1SColin Riley             }
12104640cde1SColin Riley         }
121178f339d1SEwan Crawford         // We don't have a script mapping for the current script.
12124640cde1SColin Riley         else
12134640cde1SColin Riley         {
121478f339d1SEwan Crawford             // Obtain the script resource name.
121578f339d1SEwan Crawford             std::string resName;
121678f339d1SEwan Crawford             if (rs_script->resName.get(resName))
121778f339d1SEwan Crawford                 // Set the modules resource name.
121878f339d1SEwan Crawford                 rsmodule_sp->m_resname = resName;
121978f339d1SEwan Crawford             // Add Script/Module pair to map.
122078f339d1SEwan Crawford             m_scriptMappings[script] = rsmodule_sp;
12214640cde1SColin Riley             if (log)
12224640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::FixupScriptDetails - script %" PRIx64 " associated with rsmodule '%s'.",
122378f339d1SEwan Crawford                                 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
12244640cde1SColin Riley         }
12254640cde1SColin Riley     }
12264640cde1SColin Riley }
12274640cde1SColin Riley 
122815f2bd95SEwan Crawford // Uses the Target API to evaluate the expression passed as a parameter to the function
122915f2bd95SEwan Crawford // The result of that expression is returned an unsigned 64 bit int, via the result* paramter.
123015f2bd95SEwan Crawford // Function returns true on success, and false on failure
123115f2bd95SEwan Crawford bool
123215f2bd95SEwan Crawford RenderScriptRuntime::EvalRSExpression(const char* expression, StackFrame* frame_ptr, uint64_t* result)
123315f2bd95SEwan Crawford {
123415f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
123515f2bd95SEwan Crawford     if (log)
123615f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::EvalRSExpression(%s)", expression);
123715f2bd95SEwan Crawford 
123815f2bd95SEwan Crawford     ValueObjectSP expr_result;
123915f2bd95SEwan Crawford     // Perform the actual expression evaluation
124015f2bd95SEwan Crawford     GetProcess()->GetTarget().EvaluateExpression(expression, frame_ptr, expr_result);
124115f2bd95SEwan Crawford 
124215f2bd95SEwan Crawford     if (!expr_result)
124315f2bd95SEwan Crawford     {
124415f2bd95SEwan Crawford        if (log)
124515f2bd95SEwan Crawford            log->Printf("RenderScriptRuntime::EvalRSExpression -  Error: Couldn't evaluate expression");
124615f2bd95SEwan Crawford        return false;
124715f2bd95SEwan Crawford     }
124815f2bd95SEwan Crawford 
124915f2bd95SEwan Crawford     // The result of the expression is invalid
125015f2bd95SEwan Crawford     if (!expr_result->GetError().Success())
125115f2bd95SEwan Crawford     {
125215f2bd95SEwan Crawford         Error err = expr_result->GetError();
125315f2bd95SEwan Crawford         if (err.GetError() == UserExpression::kNoResult) // Expression returned void, so this is actually a success
125415f2bd95SEwan Crawford         {
125515f2bd95SEwan Crawford             if (log)
125615f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::EvalRSExpression - Expression returned void");
125715f2bd95SEwan Crawford 
125815f2bd95SEwan Crawford             result = nullptr;
125915f2bd95SEwan Crawford             return true;
126015f2bd95SEwan Crawford         }
126115f2bd95SEwan Crawford 
126215f2bd95SEwan Crawford         if (log)
126315f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::EvalRSExpression - Error evaluating expression result: %s", err.AsCString());
126415f2bd95SEwan Crawford         return false;
126515f2bd95SEwan Crawford     }
126615f2bd95SEwan Crawford 
126715f2bd95SEwan Crawford     bool success = false;
126815f2bd95SEwan Crawford     *result = expr_result->GetValueAsUnsigned(0, &success); // We only read the result as an unsigned int.
126915f2bd95SEwan Crawford 
127015f2bd95SEwan Crawford     if (!success)
127115f2bd95SEwan Crawford     {
127215f2bd95SEwan Crawford        if (log)
127315f2bd95SEwan Crawford            log->Printf("RenderScriptRuntime::EvalRSExpression -  Error: Couldn't convert expression result to unsigned int");
127415f2bd95SEwan Crawford        return false;
127515f2bd95SEwan Crawford     }
127615f2bd95SEwan Crawford 
127715f2bd95SEwan Crawford     return true;
127815f2bd95SEwan Crawford }
127915f2bd95SEwan Crawford 
1280b1651b8dSEwan Crawford namespace // anonymous
128115f2bd95SEwan Crawford {
1282b1651b8dSEwan Crawford     // max length of an expanded expression
1283b1651b8dSEwan Crawford     const int jit_max_expr_size = 768;
128415f2bd95SEwan Crawford 
128515f2bd95SEwan Crawford     // Format strings containing the expressions we may need to evaluate.
128615f2bd95SEwan Crawford     const char runtimeExpressions[][256] =
128715f2bd95SEwan Crawford     {
128815f2bd95SEwan Crawford      // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
128915f2bd95SEwan Crawford      "(int*)_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace(0x%lx, %u, %u, %u, 0, 0)",
129015f2bd95SEwan Crawford 
129115f2bd95SEwan Crawford      // Type* rsaAllocationGetType(Context*, Allocation*)
129215f2bd95SEwan Crawford      "(void*)rsaAllocationGetType(0x%lx, 0x%lx)",
129315f2bd95SEwan Crawford 
129415f2bd95SEwan Crawford      // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
129515f2bd95SEwan Crawford      // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ;
129615f2bd95SEwan Crawford      // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
129715f2bd95SEwan Crawford      // Need to specify 32 or 64 bit for uint_t since this differs between devices
129815f2bd95SEwan Crawford      "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[0]", // X dim
129915f2bd95SEwan Crawford      "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[1]", // Y dim
130015f2bd95SEwan Crawford      "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[2]", // Z dim
130115f2bd95SEwan Crawford      "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[5]", // Element ptr
130215f2bd95SEwan Crawford 
130315f2bd95SEwan Crawford      // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
130415f2bd95SEwan Crawford      // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData
13058b244e21SEwan Crawford      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[0]", // Type
13068b244e21SEwan Crawford      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[1]", // Kind
13078b244e21SEwan Crawford      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[3]", // Vector Size
13088b244e21SEwan Crawford      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[4]", // Field Count
13098b244e21SEwan Crawford 
13108b244e21SEwan Crawford       // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t *ids, const char **names,
13118b244e21SEwan Crawford       // size_t *arraySizes, uint32_t dataSize)
13128b244e21SEwan Crawford       // Needed for Allocations of structs to gather details about fields/Subelements
13138b244e21SEwan Crawford      "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
13148b244e21SEwan Crawford      "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); ids[%u]",     // Element* of field
13158b244e21SEwan Crawford 
13168b244e21SEwan Crawford      "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
13178b244e21SEwan Crawford      "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); names[%u]",   // Name of field
13188b244e21SEwan Crawford 
13198b244e21SEwan Crawford      "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
13208b244e21SEwan Crawford      "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); arr_size[%u]" // Array size of field
132115f2bd95SEwan Crawford     };
132215f2bd95SEwan Crawford 
1323b1651b8dSEwan Crawford 
1324b1651b8dSEwan Crawford     // Temporary workaround for MIPS, until the compiler emits the JAL instruction when invoking directly the function.
1325b1651b8dSEwan Crawford     // At the moment, when evaluating an expression involving a function call, the LLVM codegen for Mips  emits a JAL
1326b1651b8dSEwan Crawford     // instruction, which is able to jump in the range +/- 128MB with respect to the current program counter ($pc). If
1327b1651b8dSEwan Crawford     // the requested function happens to reside outside the above region, the function address will be truncated and the
1328b1651b8dSEwan 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
1329b1651b8dSEwan Crawford     // the nature of allocations. A proper solution in the MIPS compiler is currently being investigated. As temporary
1330b1651b8dSEwan Crawford     // work around for this context, we'll invoke the RS API through function pointers, which cause the compiler to emit a
1331b1651b8dSEwan Crawford     // register based JALR instruction.
1332b1651b8dSEwan Crawford     const char runtimeExpressions_mips[][512] =
1333b1651b8dSEwan Crawford     {
1334b1651b8dSEwan Crawford     // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1335b1651b8dSEwan Crawford     "int* (*f) (void*, int, int, int, int, int) = (int* (*) (void*, int, int, int, int, int)) "
1336b1651b8dSEwan Crawford         "_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace; "
1337b1651b8dSEwan Crawford         "(int*) f((void*) 0x%lx, %u, %u, %u, 0, 0)",
1338b1651b8dSEwan Crawford 
1339b1651b8dSEwan Crawford     // Type* rsaAllocationGetType(Context*, Allocation*)
1340b1651b8dSEwan Crawford     "void* (*f) (void*, void*) = (void* (*) (void*, void*)) rsaAllocationGetType; (void*) f((void*) 0x%lx, (void*) 0x%lx)",
1341b1651b8dSEwan Crawford 
1342b1651b8dSEwan Crawford     // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
1343b1651b8dSEwan Crawford     // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ;
1344b1651b8dSEwan Crawford     // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
1345b1651b8dSEwan Crawford     // Need to specify 32 or 64 bit for uint_t since this differs between devices
1346b1651b8dSEwan Crawford     "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) "
1347b1651b8dSEwan Crawford         "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[0]",
1348b1651b8dSEwan Crawford     "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) "
1349b1651b8dSEwan Crawford         "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[1]",
1350b1651b8dSEwan Crawford     "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) "
1351b1651b8dSEwan Crawford         "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[2]",
1352b1651b8dSEwan Crawford     "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) "
1353b1651b8dSEwan Crawford         "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[5]",
1354b1651b8dSEwan Crawford 
1355b1651b8dSEwan Crawford     // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1356b1651b8dSEwan Crawford     // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData
1357b1651b8dSEwan Crawford     "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) "
1358b1651b8dSEwan Crawford         "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[0]", // Type
1359b1651b8dSEwan Crawford     "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) "
1360b1651b8dSEwan Crawford         "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[1]", // Kind
1361b1651b8dSEwan Crawford     "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) "
1362b1651b8dSEwan Crawford         "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[3]", // Vector size
1363b1651b8dSEwan Crawford     "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) "
1364b1651b8dSEwan Crawford         "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[4]", // Field count
1365b1651b8dSEwan Crawford 
1366b1651b8dSEwan Crawford     // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t *ids, const char **names,
1367b1651b8dSEwan Crawford     // size_t *arraySizes, uint32_t dataSize)
1368b1651b8dSEwan Crawford     // Needed for Allocations of structs to gather details about fields/Subelements
1369b1651b8dSEwan Crawford    "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
1370b1651b8dSEwan Crawford         "void* (*f) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t) = "
1371b1651b8dSEwan Crawford         "(void* (*) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t)) rsaElementGetSubElements;"
1372b1651b8dSEwan Crawford         "(void*) f((void*) 0x%lx, (void*) 0x%lx, (uintptr_t*) ids, names, arr_size, (uint32_t) %u);"
1373b1651b8dSEwan Crawford         "ids[%u]", // Element* of field
1374b1651b8dSEwan Crawford    "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
1375b1651b8dSEwan Crawford         "void* (*f) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t) = "
1376b1651b8dSEwan Crawford         "(void* (*) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t)) rsaElementGetSubElements;"
1377b1651b8dSEwan Crawford         "(void*) f((void*) 0x%lx, (void*) 0x%lx, (uintptr_t*) ids, names, arr_size, (uint32_t) %u);"
1378b1651b8dSEwan Crawford         "names[%u]", // Name of field
1379b1651b8dSEwan Crawford    "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
1380b1651b8dSEwan Crawford         "void* (*f) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t) = "
1381b1651b8dSEwan Crawford         "(void* (*) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t)) rsaElementGetSubElements;"
1382b1651b8dSEwan Crawford         "(void*) f((void*) 0x%lx, (void*) 0x%lx, (uintptr_t*) ids, names, arr_size, (uint32_t) %u);"
1383b1651b8dSEwan Crawford         "arr_size[%u]" // Array size of field
1384b1651b8dSEwan Crawford     };
1385b1651b8dSEwan Crawford 
1386b1651b8dSEwan Crawford } // end of the anonymous namespace
1387b1651b8dSEwan Crawford 
1388b1651b8dSEwan Crawford 
1389b1651b8dSEwan Crawford // Retrieve the string to JIT for the given expression
1390b1651b8dSEwan Crawford const char*
1391b1651b8dSEwan Crawford RenderScriptRuntime::JITTemplate(ExpressionStrings e)
1392b1651b8dSEwan Crawford {
1393b1651b8dSEwan Crawford     // be nice to your Mips friend when adding new expression strings
1394b1651b8dSEwan Crawford     static_assert(sizeof(runtimeExpressions)/sizeof(runtimeExpressions[0]) ==
1395b1651b8dSEwan Crawford             sizeof(runtimeExpressions_mips)/sizeof(runtimeExpressions_mips[0]),
1396b1651b8dSEwan Crawford             "#runtimeExpressions != #runtimeExpressions_mips");
1397b1651b8dSEwan Crawford 
1398b1651b8dSEwan Crawford     assert((e >= eExprGetOffsetPtr && e <= eExprSubelementsArrSize) &&
1399b1651b8dSEwan Crawford            "Expression string out of bounds");
1400b1651b8dSEwan Crawford 
1401b1651b8dSEwan Crawford     llvm::Triple::ArchType arch = GetTargetRef().GetArchitecture().GetMachine();
1402b1651b8dSEwan Crawford 
1403b1651b8dSEwan Crawford     // mips JAL workaround
1404b1651b8dSEwan Crawford     if(arch == llvm::Triple::ArchType::mips64el || arch == llvm::Triple::ArchType::mipsel)
1405b1651b8dSEwan Crawford         return runtimeExpressions_mips[e];
1406b1651b8dSEwan Crawford     else
1407b1651b8dSEwan Crawford         return runtimeExpressions[e];
1408b1651b8dSEwan Crawford }
1409b1651b8dSEwan Crawford 
1410b1651b8dSEwan Crawford 
141115f2bd95SEwan Crawford // JITs the RS runtime for the internal data pointer of an allocation.
141215f2bd95SEwan Crawford // Is passed x,y,z coordinates for the pointer to a specific element.
141315f2bd95SEwan Crawford // Then sets the data_ptr member in Allocation with the result.
141415f2bd95SEwan Crawford // Returns true on success, false otherwise
141515f2bd95SEwan Crawford bool
141615f2bd95SEwan Crawford RenderScriptRuntime::JITDataPointer(AllocationDetails* allocation, StackFrame* frame_ptr,
141715f2bd95SEwan Crawford                                     unsigned int x, unsigned int y, unsigned int z)
141815f2bd95SEwan Crawford {
141915f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
142015f2bd95SEwan Crawford 
142115f2bd95SEwan Crawford     if (!allocation->address.isValid())
142215f2bd95SEwan Crawford     {
142315f2bd95SEwan Crawford         if (log)
142415f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Failed to find allocation details");
142515f2bd95SEwan Crawford         return false;
142615f2bd95SEwan Crawford     }
142715f2bd95SEwan Crawford 
1428b1651b8dSEwan Crawford     const char* expr_cstr = JITTemplate(eExprGetOffsetPtr);
1429b1651b8dSEwan Crawford     char buffer[jit_max_expr_size];
143015f2bd95SEwan Crawford 
1431b1651b8dSEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), x, y, z);
143215f2bd95SEwan Crawford     if (chars_written < 0)
143315f2bd95SEwan Crawford     {
143415f2bd95SEwan Crawford         if (log)
143515f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
143615f2bd95SEwan Crawford         return false;
143715f2bd95SEwan Crawford     }
1438b1651b8dSEwan Crawford     else if (chars_written >= jit_max_expr_size)
143915f2bd95SEwan Crawford     {
144015f2bd95SEwan Crawford         if (log)
144115f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Expression too long");
144215f2bd95SEwan Crawford         return false;
144315f2bd95SEwan Crawford     }
144415f2bd95SEwan Crawford 
144515f2bd95SEwan Crawford     uint64_t result = 0;
144615f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
144715f2bd95SEwan Crawford         return false;
144815f2bd95SEwan Crawford 
144915f2bd95SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
145015f2bd95SEwan Crawford     allocation->data_ptr = mem_ptr;
145115f2bd95SEwan Crawford 
145215f2bd95SEwan Crawford     return true;
145315f2bd95SEwan Crawford }
145415f2bd95SEwan Crawford 
145515f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
145615f2bd95SEwan Crawford // Then sets the type_ptr member in Allocation with the result.
145715f2bd95SEwan Crawford // Returns true on success, false otherwise
145815f2bd95SEwan Crawford bool
145915f2bd95SEwan Crawford RenderScriptRuntime::JITTypePointer(AllocationDetails* allocation, StackFrame* frame_ptr)
146015f2bd95SEwan Crawford {
146115f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
146215f2bd95SEwan Crawford 
146315f2bd95SEwan Crawford     if (!allocation->address.isValid() || !allocation->context.isValid())
146415f2bd95SEwan Crawford     {
146515f2bd95SEwan Crawford         if (log)
146615f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePointer - Failed to find allocation details");
146715f2bd95SEwan Crawford         return false;
146815f2bd95SEwan Crawford     }
146915f2bd95SEwan Crawford 
1470b1651b8dSEwan Crawford     const char* expr_cstr = JITTemplate(eExprAllocGetType);
1471b1651b8dSEwan Crawford     char buffer[jit_max_expr_size];
147215f2bd95SEwan Crawford 
1473b1651b8dSEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->context.get(), *allocation->address.get());
147415f2bd95SEwan Crawford     if (chars_written < 0)
147515f2bd95SEwan Crawford     {
147615f2bd95SEwan Crawford         if (log)
147715f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
147815f2bd95SEwan Crawford         return false;
147915f2bd95SEwan Crawford     }
1480b1651b8dSEwan Crawford     else if (chars_written >= jit_max_expr_size)
148115f2bd95SEwan Crawford     {
148215f2bd95SEwan Crawford         if (log)
148315f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePointer - Expression too long");
148415f2bd95SEwan Crawford         return false;
148515f2bd95SEwan Crawford     }
148615f2bd95SEwan Crawford 
148715f2bd95SEwan Crawford     uint64_t result = 0;
148815f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
148915f2bd95SEwan Crawford         return false;
149015f2bd95SEwan Crawford 
149115f2bd95SEwan Crawford     addr_t type_ptr = static_cast<lldb::addr_t>(result);
149215f2bd95SEwan Crawford     allocation->type_ptr = type_ptr;
149315f2bd95SEwan Crawford 
149415f2bd95SEwan Crawford     return true;
149515f2bd95SEwan Crawford }
149615f2bd95SEwan Crawford 
149715f2bd95SEwan Crawford // JITs the RS runtime for information about the dimensions and type of an allocation
149815f2bd95SEwan Crawford // Then sets dimension and element_ptr members in Allocation with the result.
149915f2bd95SEwan Crawford // Returns true on success, false otherwise
150015f2bd95SEwan Crawford bool
150115f2bd95SEwan Crawford RenderScriptRuntime::JITTypePacked(AllocationDetails* allocation, StackFrame* frame_ptr)
150215f2bd95SEwan Crawford {
150315f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
150415f2bd95SEwan Crawford 
150515f2bd95SEwan Crawford     if (!allocation->type_ptr.isValid() || !allocation->context.isValid())
150615f2bd95SEwan Crawford     {
150715f2bd95SEwan Crawford         if (log)
150815f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePacked - Failed to find allocation details");
150915f2bd95SEwan Crawford         return false;
151015f2bd95SEwan Crawford     }
151115f2bd95SEwan Crawford 
151215f2bd95SEwan Crawford     // Expression is different depending on if device is 32 or 64 bit
151315f2bd95SEwan Crawford     uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
151415f2bd95SEwan Crawford     const unsigned int bits = archByteSize == 4 ? 32 : 64;
151515f2bd95SEwan Crawford 
151615f2bd95SEwan Crawford     // We want 4 elements from packed data
151715f2bd95SEwan Crawford     const unsigned int num_exprs = 4;
151815f2bd95SEwan Crawford     assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) && "Invalid number of expressions");
151915f2bd95SEwan Crawford 
1520b1651b8dSEwan Crawford     char buffer[num_exprs][jit_max_expr_size];
152115f2bd95SEwan Crawford     uint64_t results[num_exprs];
152215f2bd95SEwan Crawford 
152315f2bd95SEwan Crawford     for (unsigned int i = 0; i < num_exprs; ++i)
152415f2bd95SEwan Crawford     {
1525b1651b8dSEwan Crawford         const char* expr_cstr = JITTemplate((ExpressionStrings) (eExprTypeDimX + i));
1526b1651b8dSEwan Crawford         int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, bits,
152715f2bd95SEwan Crawford                                      *allocation->context.get(), *allocation->type_ptr.get());
152815f2bd95SEwan Crawford         if (chars_written < 0)
152915f2bd95SEwan Crawford         {
153015f2bd95SEwan Crawford             if (log)
153115f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
153215f2bd95SEwan Crawford             return false;
153315f2bd95SEwan Crawford         }
1534b1651b8dSEwan Crawford         else if (chars_written >= jit_max_expr_size)
153515f2bd95SEwan Crawford         {
153615f2bd95SEwan Crawford             if (log)
153715f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITTypePacked - Expression too long");
153815f2bd95SEwan Crawford             return false;
153915f2bd95SEwan Crawford         }
154015f2bd95SEwan Crawford 
154115f2bd95SEwan Crawford         // Perform expression evaluation
154215f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
154315f2bd95SEwan Crawford             return false;
154415f2bd95SEwan Crawford     }
154515f2bd95SEwan Crawford 
154615f2bd95SEwan Crawford     // Assign results to allocation members
154715f2bd95SEwan Crawford     AllocationDetails::Dimension dims;
154815f2bd95SEwan Crawford     dims.dim_1 = static_cast<uint32_t>(results[0]);
154915f2bd95SEwan Crawford     dims.dim_2 = static_cast<uint32_t>(results[1]);
155015f2bd95SEwan Crawford     dims.dim_3 = static_cast<uint32_t>(results[2]);
155115f2bd95SEwan Crawford     allocation->dimension = dims;
155215f2bd95SEwan Crawford 
155315f2bd95SEwan Crawford     addr_t elem_ptr = static_cast<lldb::addr_t>(results[3]);
15548b244e21SEwan Crawford     allocation->element.element_ptr = elem_ptr;
155515f2bd95SEwan Crawford 
155615f2bd95SEwan Crawford     if (log)
155715f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::JITTypePacked - dims (%u, %u, %u) Element*: 0x%" PRIx64,
155815f2bd95SEwan Crawford                     dims.dim_1, dims.dim_2, dims.dim_3, elem_ptr);
155915f2bd95SEwan Crawford 
156015f2bd95SEwan Crawford     return true;
156115f2bd95SEwan Crawford }
156215f2bd95SEwan Crawford 
156315f2bd95SEwan Crawford // JITs the RS runtime for information about the Element of an allocation
15648b244e21SEwan Crawford // Then sets type, type_vec_size, field_count and type_kind members in Element with the result.
156515f2bd95SEwan Crawford // Returns true on success, false otherwise
156615f2bd95SEwan Crawford bool
15678b244e21SEwan Crawford RenderScriptRuntime::JITElementPacked(Element& elem, const lldb::addr_t context, StackFrame* frame_ptr)
156815f2bd95SEwan Crawford {
156915f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
157015f2bd95SEwan Crawford 
15718b244e21SEwan Crawford     if (!elem.element_ptr.isValid())
157215f2bd95SEwan Crawford     {
157315f2bd95SEwan Crawford         if (log)
157415f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITElementPacked - Failed to find allocation details");
157515f2bd95SEwan Crawford         return false;
157615f2bd95SEwan Crawford     }
157715f2bd95SEwan Crawford 
15788b244e21SEwan Crawford     // We want 4 elements from packed data
15798b244e21SEwan Crawford     const unsigned int num_exprs = 4;
15808b244e21SEwan Crawford     assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) && "Invalid number of expressions");
158115f2bd95SEwan Crawford 
1582b1651b8dSEwan Crawford     char buffer[num_exprs][jit_max_expr_size];
158315f2bd95SEwan Crawford     uint64_t results[num_exprs];
158415f2bd95SEwan Crawford 
158515f2bd95SEwan Crawford     for (unsigned int i = 0; i < num_exprs; i++)
158615f2bd95SEwan Crawford     {
1587b1651b8dSEwan Crawford         const char* expr_cstr = JITTemplate((ExpressionStrings) (eExprElementType + i));
1588b1651b8dSEwan Crawford         int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, context, *elem.element_ptr.get());
158915f2bd95SEwan Crawford         if (chars_written < 0)
159015f2bd95SEwan Crawford         {
159115f2bd95SEwan Crawford             if (log)
15928b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::JITElementPacked - Encoding error in snprintf()");
159315f2bd95SEwan Crawford             return false;
159415f2bd95SEwan Crawford         }
1595b1651b8dSEwan Crawford         else if (chars_written >= jit_max_expr_size)
159615f2bd95SEwan Crawford         {
159715f2bd95SEwan Crawford             if (log)
159815f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITElementPacked - Expression too long");
159915f2bd95SEwan Crawford             return false;
160015f2bd95SEwan Crawford         }
160115f2bd95SEwan Crawford 
160215f2bd95SEwan Crawford         // Perform expression evaluation
160315f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
160415f2bd95SEwan Crawford             return false;
160515f2bd95SEwan Crawford     }
160615f2bd95SEwan Crawford 
160715f2bd95SEwan Crawford     // Assign results to allocation members
16088b244e21SEwan Crawford     elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
16098b244e21SEwan Crawford     elem.type_kind = static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
16108b244e21SEwan Crawford     elem.type_vec_size = static_cast<uint32_t>(results[2]);
16118b244e21SEwan Crawford     elem.field_count = static_cast<uint32_t>(results[3]);
161215f2bd95SEwan Crawford 
161315f2bd95SEwan Crawford     if (log)
16148b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::JITElementPacked - data type %u, pixel type %u, vector size %u, field count %u",
16158b244e21SEwan Crawford                     *elem.type.get(), *elem.type_kind.get(), *elem.type_vec_size.get(), *elem.field_count.get());
16168b244e21SEwan Crawford 
16178b244e21SEwan Crawford     // If this Element has subelements then JIT rsaElementGetSubElements() for details about its fields
16188b244e21SEwan Crawford     if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
16198b244e21SEwan Crawford         return false;
16208b244e21SEwan Crawford 
16218b244e21SEwan Crawford     return true;
16228b244e21SEwan Crawford }
16238b244e21SEwan Crawford 
16248b244e21SEwan Crawford // JITs the RS runtime for information about the subelements/fields of a struct allocation
16258b244e21SEwan Crawford // This is necessary for infering the struct type so we can pretty print the allocation's contents.
16268b244e21SEwan Crawford // Returns true on success, false otherwise
16278b244e21SEwan Crawford bool
16288b244e21SEwan Crawford RenderScriptRuntime::JITSubelements(Element& elem, const lldb::addr_t context, StackFrame* frame_ptr)
16298b244e21SEwan Crawford {
16308b244e21SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
16318b244e21SEwan Crawford 
16328b244e21SEwan Crawford     if (!elem.element_ptr.isValid() || !elem.field_count.isValid())
16338b244e21SEwan Crawford     {
16348b244e21SEwan Crawford         if (log)
16358b244e21SEwan Crawford             log->Printf("RenderScriptRuntime::JITSubelements - Failed to find allocation details");
16368b244e21SEwan Crawford         return false;
16378b244e21SEwan Crawford     }
16388b244e21SEwan Crawford 
16398b244e21SEwan Crawford     const short num_exprs = 3;
16408b244e21SEwan Crawford     assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) && "Invalid number of expressions");
16418b244e21SEwan Crawford 
1642b1651b8dSEwan Crawford     char expr_buffer[jit_max_expr_size];
16438b244e21SEwan Crawford     uint64_t results;
16448b244e21SEwan Crawford 
16458b244e21SEwan Crawford     // Iterate over struct fields.
16468b244e21SEwan Crawford     const uint32_t field_count = *elem.field_count.get();
16478b244e21SEwan Crawford     for (unsigned int field_index = 0; field_index < field_count; ++field_index)
16488b244e21SEwan Crawford     {
16498b244e21SEwan Crawford         Element child;
16508b244e21SEwan Crawford         for (unsigned int expr_index = 0; expr_index < num_exprs; ++expr_index)
16518b244e21SEwan Crawford         {
1652b1651b8dSEwan Crawford             const char* expr_cstr = JITTemplate((ExpressionStrings) (eExprSubelementsId + expr_index));
1653b1651b8dSEwan Crawford             int chars_written = snprintf(expr_buffer, jit_max_expr_size, expr_cstr,
16548b244e21SEwan Crawford                                          field_count, field_count, field_count,
16558b244e21SEwan Crawford                                          context, *elem.element_ptr.get(), field_count, field_index);
16568b244e21SEwan Crawford             if (chars_written < 0)
16578b244e21SEwan Crawford             {
16588b244e21SEwan Crawford                 if (log)
16598b244e21SEwan Crawford                     log->Printf("RenderScriptRuntime::JITSubelements - Encoding error in snprintf()");
16608b244e21SEwan Crawford                 return false;
16618b244e21SEwan Crawford             }
1662b1651b8dSEwan Crawford             else if (chars_written >= jit_max_expr_size)
16638b244e21SEwan Crawford             {
16648b244e21SEwan Crawford                 if (log)
16658b244e21SEwan Crawford                     log->Printf("RenderScriptRuntime::JITSubelements - Expression too long");
16668b244e21SEwan Crawford                 return false;
16678b244e21SEwan Crawford             }
16688b244e21SEwan Crawford 
16698b244e21SEwan Crawford             // Perform expression evaluation
16708b244e21SEwan Crawford             if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
16718b244e21SEwan Crawford                 return false;
16728b244e21SEwan Crawford 
16738b244e21SEwan Crawford             if (log)
16748b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::JITSubelements - Expr result 0x%" PRIx64, results);
16758b244e21SEwan Crawford 
16768b244e21SEwan Crawford             switch(expr_index)
16778b244e21SEwan Crawford             {
16788b244e21SEwan Crawford                 case 0: // Element* of child
16798b244e21SEwan Crawford                     child.element_ptr = static_cast<addr_t>(results);
16808b244e21SEwan Crawford                     break;
16818b244e21SEwan Crawford                 case 1: // Name of child
16828b244e21SEwan Crawford                 {
16838b244e21SEwan Crawford                     lldb::addr_t address = static_cast<addr_t>(results);
16848b244e21SEwan Crawford                     Error err;
16858b244e21SEwan Crawford                     std::string name;
16868b244e21SEwan Crawford                     GetProcess()->ReadCStringFromMemory(address, name, err);
16878b244e21SEwan Crawford                     if (!err.Fail())
16888b244e21SEwan Crawford                         child.type_name = ConstString(name);
16898b244e21SEwan Crawford                     else
16908b244e21SEwan Crawford                     {
16918b244e21SEwan Crawford                         if (log)
16928b244e21SEwan Crawford                             log->Printf("RenderScriptRuntime::JITSubelements - Warning: Couldn't read field name");
16938b244e21SEwan Crawford                     }
16948b244e21SEwan Crawford                     break;
16958b244e21SEwan Crawford                 }
16968b244e21SEwan Crawford                 case 2: // Array size of child
16978b244e21SEwan Crawford                     child.array_size = static_cast<uint32_t>(results);
16988b244e21SEwan Crawford                     break;
16998b244e21SEwan Crawford             }
17008b244e21SEwan Crawford         }
17018b244e21SEwan Crawford 
17028b244e21SEwan Crawford         // We need to recursively JIT each Element field of the struct since
17038b244e21SEwan Crawford         // structs can be nested inside structs.
17048b244e21SEwan Crawford         if (!JITElementPacked(child, context, frame_ptr))
17058b244e21SEwan Crawford             return false;
17068b244e21SEwan Crawford         elem.children.push_back(child);
17078b244e21SEwan Crawford     }
17088b244e21SEwan Crawford 
17098b244e21SEwan Crawford     // Try to infer the name of the struct type so we can pretty print the allocation contents.
17108b244e21SEwan Crawford     FindStructTypeName(elem, frame_ptr);
171115f2bd95SEwan Crawford 
171215f2bd95SEwan Crawford     return true;
171315f2bd95SEwan Crawford }
171415f2bd95SEwan Crawford 
1715a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
1716a0f08674SEwan Crawford // The `elem_size` paramter represents the size of a single element, including padding.
1717a0f08674SEwan Crawford // Which is needed as an offset from the last element pointer.
1718a0f08674SEwan Crawford // Using this offset minus the starting address we can calculate the size of the allocation.
1719a0f08674SEwan Crawford // Returns true on success, false otherwise
1720a0f08674SEwan Crawford bool
17218b244e21SEwan Crawford RenderScriptRuntime::JITAllocationSize(AllocationDetails* allocation, StackFrame* frame_ptr)
1722a0f08674SEwan Crawford {
1723a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1724a0f08674SEwan Crawford 
1725a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->dimension.isValid()
17268b244e21SEwan Crawford         || !allocation->data_ptr.isValid() || !allocation->element.datum_size.isValid())
1727a0f08674SEwan Crawford     {
1728a0f08674SEwan Crawford         if (log)
1729a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Failed to find allocation details");
1730a0f08674SEwan Crawford         return false;
1731a0f08674SEwan Crawford     }
1732a0f08674SEwan Crawford 
1733a0f08674SEwan Crawford     // Find dimensions
1734a0f08674SEwan Crawford     unsigned int dim_x = allocation->dimension.get()->dim_1;
1735a0f08674SEwan Crawford     unsigned int dim_y = allocation->dimension.get()->dim_2;
1736a0f08674SEwan Crawford     unsigned int dim_z = allocation->dimension.get()->dim_3;
1737a0f08674SEwan Crawford 
17388b244e21SEwan Crawford     // Our plan of jitting the last element address doesn't seem to work for struct Allocations
17398b244e21SEwan Crawford     // Instead try to infer the size ourselves without any inter element padding.
17408b244e21SEwan Crawford     if (allocation->element.children.size() > 0)
17418b244e21SEwan Crawford     {
17428b244e21SEwan Crawford         if (dim_x == 0) dim_x = 1;
17438b244e21SEwan Crawford         if (dim_y == 0) dim_y = 1;
17448b244e21SEwan Crawford         if (dim_z == 0) dim_z = 1;
17458b244e21SEwan Crawford 
17468b244e21SEwan Crawford         allocation->size = dim_x * dim_y * dim_z * *allocation->element.datum_size.get();
17478b244e21SEwan Crawford 
17488b244e21SEwan Crawford         if (log)
17498b244e21SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Infered size of struct allocation %u", *allocation->size.get());
17508b244e21SEwan Crawford 
17518b244e21SEwan Crawford         return true;
17528b244e21SEwan Crawford     }
17538b244e21SEwan Crawford 
1754b1651b8dSEwan Crawford     const char* expr_cstr = JITTemplate(eExprGetOffsetPtr);
1755b1651b8dSEwan Crawford     char buffer[jit_max_expr_size];
17568b244e21SEwan Crawford 
1757a0f08674SEwan Crawford     // Calculate last element
1758a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 0 : dim_x - 1;
1759a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 0 : dim_y - 1;
1760a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 0 : dim_z - 1;
1761a0f08674SEwan Crawford 
1762b1651b8dSEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(),
1763a0f08674SEwan Crawford                                  dim_x, dim_y, dim_z);
1764a0f08674SEwan Crawford     if (chars_written < 0)
1765a0f08674SEwan Crawford     {
1766a0f08674SEwan Crawford         if (log)
1767a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Encoding error in snprintf()");
1768a0f08674SEwan Crawford         return false;
1769a0f08674SEwan Crawford     }
1770b1651b8dSEwan Crawford     else if (chars_written >= jit_max_expr_size)
1771a0f08674SEwan Crawford     {
1772a0f08674SEwan Crawford         if (log)
1773a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Expression too long");
1774a0f08674SEwan Crawford         return false;
1775a0f08674SEwan Crawford     }
1776a0f08674SEwan Crawford 
1777a0f08674SEwan Crawford     uint64_t result = 0;
1778a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1779a0f08674SEwan Crawford         return false;
1780a0f08674SEwan Crawford 
1781a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1782a0f08674SEwan Crawford     // Find pointer to last element and add on size of an element
17838b244e21SEwan Crawford     allocation->size = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()) + *allocation->element.datum_size.get();
1784a0f08674SEwan Crawford 
1785a0f08674SEwan Crawford     return true;
1786a0f08674SEwan Crawford }
1787a0f08674SEwan Crawford 
1788a0f08674SEwan Crawford // JITs the RS runtime for information about the stride between rows in the allocation.
1789a0f08674SEwan Crawford // This is done to detect padding, since allocated memory is 16-byte aligned.
1790a0f08674SEwan Crawford // Returns true on success, false otherwise
1791a0f08674SEwan Crawford bool
1792a0f08674SEwan Crawford RenderScriptRuntime::JITAllocationStride(AllocationDetails* allocation, StackFrame* frame_ptr)
1793a0f08674SEwan Crawford {
1794a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1795a0f08674SEwan Crawford 
1796a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->data_ptr.isValid())
1797a0f08674SEwan Crawford     {
1798a0f08674SEwan Crawford         if (log)
1799a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Failed to find allocation details");
1800a0f08674SEwan Crawford         return false;
1801a0f08674SEwan Crawford     }
1802a0f08674SEwan Crawford 
1803b1651b8dSEwan Crawford     const char* expr_cstr = JITTemplate(eExprGetOffsetPtr);
1804b1651b8dSEwan Crawford     char buffer[jit_max_expr_size];
1805a0f08674SEwan Crawford 
1806b1651b8dSEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(),
1807a0f08674SEwan Crawford                                  0, 1, 0);
1808a0f08674SEwan Crawford     if (chars_written < 0)
1809a0f08674SEwan Crawford     {
1810a0f08674SEwan Crawford         if (log)
1811a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Encoding error in snprintf()");
1812a0f08674SEwan Crawford         return false;
1813a0f08674SEwan Crawford     }
1814b1651b8dSEwan Crawford     else if (chars_written >= jit_max_expr_size)
1815a0f08674SEwan Crawford     {
1816a0f08674SEwan Crawford         if (log)
1817a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Expression too long");
1818a0f08674SEwan Crawford         return false;
1819a0f08674SEwan Crawford     }
1820a0f08674SEwan Crawford 
1821a0f08674SEwan Crawford     uint64_t result = 0;
1822a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1823a0f08674SEwan Crawford         return false;
1824a0f08674SEwan Crawford 
1825a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1826a0f08674SEwan Crawford     allocation->stride = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get());
1827a0f08674SEwan Crawford 
1828a0f08674SEwan Crawford     return true;
1829a0f08674SEwan Crawford }
1830a0f08674SEwan Crawford 
183115f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
183215f2bd95SEwan Crawford bool
183315f2bd95SEwan Crawford RenderScriptRuntime::RefreshAllocation(AllocationDetails* allocation, StackFrame* frame_ptr)
183415f2bd95SEwan Crawford {
183515f2bd95SEwan Crawford     // GetOffsetPointer()
183615f2bd95SEwan Crawford     if (!JITDataPointer(allocation, frame_ptr))
183715f2bd95SEwan Crawford         return false;
183815f2bd95SEwan Crawford 
183915f2bd95SEwan Crawford     // rsaAllocationGetType()
184015f2bd95SEwan Crawford     if (!JITTypePointer(allocation, frame_ptr))
184115f2bd95SEwan Crawford         return false;
184215f2bd95SEwan Crawford 
184315f2bd95SEwan Crawford     // rsaTypeGetNativeData()
184415f2bd95SEwan Crawford     if (!JITTypePacked(allocation, frame_ptr))
184515f2bd95SEwan Crawford         return false;
184615f2bd95SEwan Crawford 
184715f2bd95SEwan Crawford     // rsaElementGetNativeData()
18488b244e21SEwan Crawford     if (!JITElementPacked(allocation->element, *allocation->context.get(), frame_ptr))
184915f2bd95SEwan Crawford         return false;
185015f2bd95SEwan Crawford 
18518b244e21SEwan Crawford     // Sets the datum_size member in Element
18528b244e21SEwan Crawford     SetElementSize(allocation->element);
18538b244e21SEwan Crawford 
185455232f09SEwan Crawford     // Use GetOffsetPointer() to infer size of the allocation
18558b244e21SEwan Crawford     if (!JITAllocationSize(allocation, frame_ptr))
185655232f09SEwan Crawford         return false;
185755232f09SEwan Crawford 
185855232f09SEwan Crawford     return true;
185955232f09SEwan Crawford }
186055232f09SEwan Crawford 
18618b244e21SEwan Crawford // Function attempts to set the type_name member of the paramaterised Element object.
18628b244e21SEwan Crawford // This string should be the name of the struct type the Element represents.
18638b244e21SEwan Crawford // We need this string for pretty printing the Element to users.
18648b244e21SEwan Crawford void
18658b244e21SEwan Crawford RenderScriptRuntime::FindStructTypeName(Element& elem, StackFrame* frame_ptr)
186655232f09SEwan Crawford {
18678b244e21SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
18688b244e21SEwan Crawford 
18698b244e21SEwan Crawford     if (!elem.type_name.IsEmpty()) // Name already set
18708b244e21SEwan Crawford         return;
18718b244e21SEwan Crawford     else
1872fe06b5adSAdrian McCarthy         elem.type_name = Element::GetFallbackStructName(); // Default type name if we don't succeed
18738b244e21SEwan Crawford 
18748b244e21SEwan Crawford     // Find all the global variables from the script rs modules
18758b244e21SEwan Crawford     VariableList variable_list;
18768b244e21SEwan Crawford     for (auto module_sp : m_rsmodules)
18778b244e21SEwan Crawford         module_sp->m_module->FindGlobalVariables(RegularExpression("."), true, UINT32_MAX, variable_list);
18788b244e21SEwan Crawford 
18798b244e21SEwan Crawford     // Iterate over all the global variables looking for one with a matching type to the Element.
18808b244e21SEwan Crawford     // We make the assumption a match exists since there needs to be a global variable to reflect the
18818b244e21SEwan Crawford     // struct type back into java host code.
18828b244e21SEwan Crawford     for (uint32_t var_index = 0; var_index < variable_list.GetSize(); ++var_index)
18838b244e21SEwan Crawford     {
18848b244e21SEwan Crawford         const VariableSP var_sp(variable_list.GetVariableAtIndex(var_index));
18858b244e21SEwan Crawford         if (!var_sp)
18868b244e21SEwan Crawford            continue;
18878b244e21SEwan Crawford 
18888b244e21SEwan Crawford         ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
18898b244e21SEwan Crawford         if (!valobj_sp)
18908b244e21SEwan Crawford             continue;
18918b244e21SEwan Crawford 
18928b244e21SEwan Crawford         // Find the number of variable fields.
18938b244e21SEwan Crawford         // If it has no fields, or more fields than our Element, then it can't be the struct we're looking for.
18948b244e21SEwan Crawford         // Don't check for equality since RS can add extra struct members for padding.
18958b244e21SEwan Crawford         size_t num_children = valobj_sp->GetNumChildren();
18968b244e21SEwan Crawford         if (num_children > elem.children.size() || num_children == 0)
18978b244e21SEwan Crawford             continue;
18988b244e21SEwan Crawford 
18998b244e21SEwan Crawford         // Iterate over children looking for members with matching field names.
19008b244e21SEwan Crawford         // If all the field names match, this is likely the struct we want.
19018b244e21SEwan Crawford         //
19028b244e21SEwan Crawford         //   TODO: This could be made more robust by also checking children data sizes, or array size
19038b244e21SEwan Crawford         bool found = true;
19048b244e21SEwan Crawford         for (size_t child_index = 0; child_index < num_children; ++child_index)
19058b244e21SEwan Crawford         {
19068b244e21SEwan Crawford             ValueObjectSP child = valobj_sp->GetChildAtIndex(child_index, true);
19078b244e21SEwan Crawford             if (!child || (child->GetName() != elem.children[child_index].type_name))
19088b244e21SEwan Crawford             {
19098b244e21SEwan Crawford                 found = false;
19108b244e21SEwan Crawford                 break;
19118b244e21SEwan Crawford             }
19128b244e21SEwan Crawford         }
19138b244e21SEwan Crawford 
19148b244e21SEwan Crawford         // RS can add extra struct members for padding in the format '#rs_padding_[0-9]+'
19158b244e21SEwan Crawford         if (found && num_children < elem.children.size())
19168b244e21SEwan Crawford         {
19178b244e21SEwan Crawford             const unsigned int size_diff = elem.children.size() - num_children;
19188b244e21SEwan Crawford             if (log)
19198b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::FindStructTypeName - %u padding struct entries", size_diff);
19208b244e21SEwan Crawford 
19218b244e21SEwan Crawford             for (unsigned int padding_index = 0; padding_index < size_diff; ++padding_index)
19228b244e21SEwan Crawford             {
19238b244e21SEwan Crawford                 const ConstString& name = elem.children[num_children + padding_index].type_name;
19248b244e21SEwan Crawford                 if (strcmp(name.AsCString(), "#rs_padding") < 0)
19258b244e21SEwan Crawford                     found = false;
19268b244e21SEwan Crawford             }
19278b244e21SEwan Crawford         }
19288b244e21SEwan Crawford 
19298b244e21SEwan Crawford         // We've found a global var with matching type
19308b244e21SEwan Crawford         if (found)
19318b244e21SEwan Crawford         {
19328b244e21SEwan Crawford             // Dereference since our Element type isn't a pointer.
19338b244e21SEwan Crawford             if (valobj_sp->IsPointerType())
19348b244e21SEwan Crawford             {
19358b244e21SEwan Crawford                 Error err;
19368b244e21SEwan Crawford                 ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
19378b244e21SEwan Crawford                 if (!err.Fail())
19388b244e21SEwan Crawford                     valobj_sp = deref_valobj;
19398b244e21SEwan Crawford             }
19408b244e21SEwan Crawford 
19418b244e21SEwan Crawford             // Save name of variable in Element.
19428b244e21SEwan Crawford             elem.type_name = valobj_sp->GetTypeName();
19438b244e21SEwan Crawford             if (log)
19448b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::FindStructTypeName - Element name set to %s", elem.type_name.AsCString());
19458b244e21SEwan Crawford 
19468b244e21SEwan Crawford             return;
19478b244e21SEwan Crawford         }
19488b244e21SEwan Crawford     }
19498b244e21SEwan Crawford }
19508b244e21SEwan Crawford 
19518b244e21SEwan Crawford // Function sets the datum_size member of Element. Representing the size of a single instance including padding.
19528b244e21SEwan Crawford // Assumes the relevant allocation information has already been jitted.
19538b244e21SEwan Crawford void
19548b244e21SEwan Crawford RenderScriptRuntime::SetElementSize(Element& elem)
19558b244e21SEwan Crawford {
19568b244e21SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
19578b244e21SEwan Crawford     const Element::DataType type = *elem.type.get();
19582e920715SEwan Crawford     assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT
195955232f09SEwan Crawford                                                    && "Invalid allocation type");
196055232f09SEwan Crawford 
19618b244e21SEwan Crawford     const unsigned int vec_size = *elem.type_vec_size.get();
19628b244e21SEwan Crawford     unsigned int data_size = 0;
19632e920715SEwan Crawford     unsigned int padding = 0;
196455232f09SEwan Crawford 
19658b244e21SEwan Crawford     // Element is of a struct type, calculate size recursively.
19668b244e21SEwan Crawford     if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0))
19678b244e21SEwan Crawford     {
19688b244e21SEwan Crawford         for (Element& child : elem.children)
19698b244e21SEwan Crawford         {
19708b244e21SEwan Crawford             SetElementSize(child);
19718b244e21SEwan Crawford             const unsigned int array_size = child.array_size.isValid() ? *child.array_size.get() : 1;
19728b244e21SEwan Crawford             data_size += *child.datum_size.get() * array_size;
19738b244e21SEwan Crawford         }
19748b244e21SEwan Crawford     }
19752e920715SEwan Crawford     else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 || type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
19762e920715SEwan Crawford              type == Element::RS_TYPE_UNSIGNED_4_4_4_4) // These have been packed already
19772e920715SEwan Crawford     {
19782e920715SEwan Crawford         data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
19792e920715SEwan Crawford     }
19802e920715SEwan Crawford     else if (type < Element::RS_TYPE_ELEMENT)
19812e920715SEwan Crawford     {
19828b244e21SEwan Crawford         data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
19832e920715SEwan Crawford         if (vec_size == 3)
19842e920715SEwan Crawford             padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
19852e920715SEwan Crawford     }
19862e920715SEwan Crawford     else
19872e920715SEwan Crawford         data_size = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
19888b244e21SEwan Crawford 
19898b244e21SEwan Crawford     elem.padding = padding;
19908b244e21SEwan Crawford     elem.datum_size = data_size + padding;
19918b244e21SEwan Crawford     if (log)
19928b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::SetElementSize - element size set to %u", data_size + padding);
199355232f09SEwan Crawford }
199455232f09SEwan Crawford 
199555232f09SEwan Crawford // Given an allocation, this function copies the allocation contents from device into a buffer on the heap.
199655232f09SEwan Crawford // Returning a shared pointer to the buffer containing the data.
199755232f09SEwan Crawford std::shared_ptr<uint8_t>
199855232f09SEwan Crawford RenderScriptRuntime::GetAllocationData(AllocationDetails* allocation, StackFrame* frame_ptr)
199955232f09SEwan Crawford {
200055232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
200155232f09SEwan Crawford 
200255232f09SEwan Crawford     // JIT all the allocation details
20038b59062aSEwan Crawford     if (allocation->shouldRefresh())
200455232f09SEwan Crawford     {
200555232f09SEwan Crawford         if (log)
200655232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - Allocation details not calculated yet, jitting info");
200755232f09SEwan Crawford 
200855232f09SEwan Crawford         if (!RefreshAllocation(allocation, frame_ptr))
200955232f09SEwan Crawford         {
201055232f09SEwan Crawford             if (log)
201155232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't JIT allocation details");
201255232f09SEwan Crawford             return nullptr;
201355232f09SEwan Crawford         }
201455232f09SEwan Crawford     }
201555232f09SEwan Crawford 
20168b244e21SEwan Crawford     assert(allocation->data_ptr.isValid() && allocation->element.type.isValid() && allocation->element.type_vec_size.isValid()
201755232f09SEwan Crawford            && allocation->size.isValid() && "Allocation information not available");
201855232f09SEwan Crawford 
201955232f09SEwan Crawford     // Allocate a buffer to copy data into
202055232f09SEwan Crawford     const unsigned int size = *allocation->size.get();
202155232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
202255232f09SEwan Crawford     if (!buffer)
202355232f09SEwan Crawford     {
202455232f09SEwan Crawford         if (log)
202555232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't allocate a %u byte buffer", size);
202655232f09SEwan Crawford         return nullptr;
202755232f09SEwan Crawford     }
202855232f09SEwan Crawford 
202955232f09SEwan Crawford     // Read the inferior memory
203055232f09SEwan Crawford     Error error;
203155232f09SEwan Crawford     lldb::addr_t data_ptr = *allocation->data_ptr.get();
203255232f09SEwan Crawford     GetProcess()->ReadMemory(data_ptr, buffer.get(), size, error);
203355232f09SEwan Crawford     if (error.Fail())
203455232f09SEwan Crawford     {
203555232f09SEwan Crawford         if (log)
203655232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - '%s' Couldn't read %u bytes of allocation data from 0x%" PRIx64,
203755232f09SEwan Crawford                         error.AsCString(), size, data_ptr);
203855232f09SEwan Crawford         return nullptr;
203955232f09SEwan Crawford     }
204055232f09SEwan Crawford 
204155232f09SEwan Crawford     return buffer;
204255232f09SEwan Crawford }
204355232f09SEwan Crawford 
204455232f09SEwan Crawford // Function copies data from a binary file into an allocation.
204555232f09SEwan Crawford // There is a header at the start of the file, FileHeader, before the data content itself.
204655232f09SEwan Crawford // Information from this header is used to display warnings to the user about incompatabilities
204755232f09SEwan Crawford bool
204855232f09SEwan Crawford RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr)
204955232f09SEwan Crawford {
205055232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
205155232f09SEwan Crawford 
205255232f09SEwan Crawford     // Find allocation with the given id
205355232f09SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, alloc_id);
205455232f09SEwan Crawford     if (!alloc)
205555232f09SEwan Crawford         return false;
205655232f09SEwan Crawford 
205755232f09SEwan Crawford     if (log)
205855232f09SEwan Crawford         log->Printf("RenderScriptRuntime::LoadAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
205955232f09SEwan Crawford 
206055232f09SEwan Crawford     // JIT all the allocation details
20618b59062aSEwan Crawford     if (alloc->shouldRefresh())
206255232f09SEwan Crawford     {
206355232f09SEwan Crawford         if (log)
206455232f09SEwan Crawford             log->Printf("RenderScriptRuntime::LoadAllocation - Allocation details not calculated yet, jitting info");
206555232f09SEwan Crawford 
206655232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
206755232f09SEwan Crawford         {
206855232f09SEwan Crawford             if (log)
206955232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::LoadAllocation - Couldn't JIT allocation details");
20704cfc9198SSylvestre Ledru             return false;
207155232f09SEwan Crawford         }
207255232f09SEwan Crawford     }
207355232f09SEwan Crawford 
20748b244e21SEwan Crawford     assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid()
20758b244e21SEwan Crawford            && alloc->size.isValid() && alloc->element.datum_size.isValid() && "Allocation information not available");
207655232f09SEwan Crawford 
207755232f09SEwan Crawford     // Check we can read from file
207855232f09SEwan Crawford     FileSpec file(filename, true);
207955232f09SEwan Crawford     if (!file.Exists())
208055232f09SEwan Crawford     {
208155232f09SEwan Crawford         strm.Printf("Error: File %s does not exist", filename);
208255232f09SEwan Crawford         strm.EOL();
208355232f09SEwan Crawford         return false;
208455232f09SEwan Crawford     }
208555232f09SEwan Crawford 
208655232f09SEwan Crawford     if (!file.Readable())
208755232f09SEwan Crawford     {
208855232f09SEwan Crawford         strm.Printf("Error: File %s does not have readable permissions", filename);
208955232f09SEwan Crawford         strm.EOL();
209055232f09SEwan Crawford         return false;
209155232f09SEwan Crawford     }
209255232f09SEwan Crawford 
209355232f09SEwan Crawford     // Read file into data buffer
209455232f09SEwan Crawford     DataBufferSP data_sp(file.ReadFileContents());
209555232f09SEwan Crawford 
209655232f09SEwan Crawford     // Cast start of buffer to FileHeader and use pointer to read metadata
209755232f09SEwan Crawford     void* file_buffer = data_sp->GetBytes();
2098*26e52a70SEwan Crawford     if (file_buffer == NULL || data_sp->GetByteSize() <
2099*26e52a70SEwan Crawford         (sizeof(AllocationDetails::FileHeader) + sizeof(AllocationDetails::ElementHeader)))
2100*26e52a70SEwan Crawford     {
2101*26e52a70SEwan Crawford         strm.Printf("Error: File %s does not contain enough data for header", filename);
2102*26e52a70SEwan Crawford         strm.EOL();
2103*26e52a70SEwan Crawford         return false;
2104*26e52a70SEwan Crawford     }
2105*26e52a70SEwan Crawford     const AllocationDetails::FileHeader* file_header = static_cast<AllocationDetails::FileHeader*>(file_buffer);
210655232f09SEwan Crawford 
2107*26e52a70SEwan Crawford     // Check file starts with ascii characters "RSAD"
2108*26e52a70SEwan Crawford     if (file_header->ident[0] != 'R' || file_header->ident[1] != 'S' || file_header->ident[2] != 'A'
2109*26e52a70SEwan Crawford         || file_header->ident[3] != 'D')
2110*26e52a70SEwan Crawford     {
2111*26e52a70SEwan Crawford         strm.Printf("Error: File doesn't contain identifier for an RS allocation dump. Are you sure this is the correct file?");
2112*26e52a70SEwan Crawford         strm.EOL();
2113*26e52a70SEwan Crawford         return false;
2114*26e52a70SEwan Crawford     }
2115*26e52a70SEwan Crawford 
2116*26e52a70SEwan Crawford     // Look at the type of the root element in the header
2117*26e52a70SEwan Crawford     AllocationDetails::ElementHeader root_element_header;
2118*26e52a70SEwan Crawford     memcpy(&root_element_header, static_cast<uint8_t*>(file_buffer) + sizeof(AllocationDetails::FileHeader),
2119*26e52a70SEwan Crawford            sizeof(AllocationDetails::ElementHeader));
212055232f09SEwan Crawford 
212155232f09SEwan Crawford     if (log)
212255232f09SEwan Crawford         log->Printf("RenderScriptRuntime::LoadAllocation - header type %u, element size %u",
2123*26e52a70SEwan Crawford                     root_element_header.type, root_element_header.element_size);
212455232f09SEwan Crawford 
212555232f09SEwan Crawford     // Check if the target allocation and file both have the same number of bytes for an Element
2126*26e52a70SEwan Crawford     if (*alloc->element.datum_size.get() != root_element_header.element_size)
212755232f09SEwan Crawford     {
212855232f09SEwan Crawford         strm.Printf("Warning: Mismatched Element sizes - file %u bytes, allocation %u bytes",
2129*26e52a70SEwan Crawford                     root_element_header.element_size, *alloc->element.datum_size.get());
213055232f09SEwan Crawford         strm.EOL();
213155232f09SEwan Crawford     }
213255232f09SEwan Crawford 
2133*26e52a70SEwan Crawford     // Check if the target allocation and file both have the same type
2134*26e52a70SEwan Crawford     const unsigned int alloc_type = static_cast<unsigned int>(*alloc->element.type.get());
2135*26e52a70SEwan Crawford     const unsigned int file_type = root_element_header.type;
2136*26e52a70SEwan Crawford 
2137*26e52a70SEwan Crawford     if (file_type > Element::RS_TYPE_FONT)
2138*26e52a70SEwan Crawford     {
2139*26e52a70SEwan Crawford         strm.Printf("Warning: File has unknown allocation type");
2140*26e52a70SEwan Crawford         strm.EOL();
2141*26e52a70SEwan Crawford     }
2142*26e52a70SEwan Crawford     else if (alloc_type != file_type)
214355232f09SEwan Crawford     {
21442e920715SEwan Crawford         // Enum value isn't monotonous, so doesn't always index RsDataTypeToString array
2145*26e52a70SEwan Crawford         unsigned int printable_target_type_index = alloc_type;
2146*26e52a70SEwan Crawford         unsigned int printable_head_type_index = file_type;
2147*26e52a70SEwan Crawford         if (alloc_type >= Element::RS_TYPE_ELEMENT && alloc_type <= Element::RS_TYPE_FONT)
21482e920715SEwan Crawford             printable_target_type_index = static_cast<Element::DataType>(
2149*26e52a70SEwan Crawford                                          (alloc_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 + 1);
21502e920715SEwan Crawford 
2151*26e52a70SEwan Crawford         if (file_type >= Element::RS_TYPE_ELEMENT && file_type <= Element::RS_TYPE_FONT)
21522e920715SEwan Crawford             printable_head_type_index = static_cast<Element::DataType>(
2153*26e52a70SEwan Crawford                                         (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 + 1);
21542e920715SEwan Crawford 
21552e920715SEwan Crawford         const char* file_type_cstr = AllocationDetails::RsDataTypeToString[printable_head_type_index][0];
21562e920715SEwan Crawford         const char* target_type_cstr = AllocationDetails::RsDataTypeToString[printable_target_type_index][0];
215755232f09SEwan Crawford 
215855232f09SEwan Crawford         strm.Printf("Warning: Mismatched Types - file '%s' type, allocation '%s' type",
21592e920715SEwan Crawford                     file_type_cstr, target_type_cstr);
216055232f09SEwan Crawford         strm.EOL();
216155232f09SEwan Crawford     }
216255232f09SEwan Crawford 
2163*26e52a70SEwan Crawford     // Advance buffer past header
2164*26e52a70SEwan Crawford     file_buffer = static_cast<uint8_t*>(file_buffer) + file_header->hdr_size;
2165*26e52a70SEwan Crawford 
216655232f09SEwan Crawford     // Calculate size of allocation data in file
2167*26e52a70SEwan Crawford     size_t length = data_sp->GetByteSize() - file_header->hdr_size;
216855232f09SEwan Crawford 
216955232f09SEwan Crawford     // Check if the target allocation and file both have the same total data size.
217055232f09SEwan Crawford     const unsigned int alloc_size = *alloc->size.get();
217155232f09SEwan Crawford     if (alloc_size != length)
217255232f09SEwan Crawford     {
217355232f09SEwan Crawford         strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64 " bytes, allocation 0x%x bytes",
2174eba832beSJason Molenda                     (uint64_t) length, alloc_size);
217555232f09SEwan Crawford         strm.EOL();
217655232f09SEwan Crawford         length = alloc_size < length ? alloc_size : length; // Set length to copy to minimum
217755232f09SEwan Crawford     }
217855232f09SEwan Crawford 
217955232f09SEwan Crawford     // Copy file data from our buffer into the target allocation.
218055232f09SEwan Crawford     lldb::addr_t alloc_data = *alloc->data_ptr.get();
218155232f09SEwan Crawford     Error error;
218255232f09SEwan Crawford     size_t bytes_written = GetProcess()->WriteMemory(alloc_data, file_buffer, length, error);
218355232f09SEwan Crawford     if (!error.Success() || bytes_written != length)
218455232f09SEwan Crawford     {
218555232f09SEwan Crawford         strm.Printf("Error: Couldn't write data to allocation %s", error.AsCString());
218655232f09SEwan Crawford         strm.EOL();
218755232f09SEwan Crawford         return false;
218855232f09SEwan Crawford     }
218955232f09SEwan Crawford 
219055232f09SEwan Crawford     strm.Printf("Contents of file '%s' read into allocation %u", filename, alloc->id);
219155232f09SEwan Crawford     strm.EOL();
219255232f09SEwan Crawford 
219355232f09SEwan Crawford     return true;
219455232f09SEwan Crawford }
219555232f09SEwan Crawford 
2196*26e52a70SEwan Crawford // Function takes as parameters a byte buffer, which will eventually be written to file as the element header,
2197*26e52a70SEwan Crawford // an offset into that buffer, and an Element that will be saved into the buffer at the parametrised offset.
2198*26e52a70SEwan Crawford // Return value is the new offset after writing the element into the buffer.
2199*26e52a70SEwan Crawford // Elements are saved to the file as the ElementHeader struct followed by offsets to the structs of all the element's children.
2200*26e52a70SEwan Crawford size_t
2201*26e52a70SEwan Crawford RenderScriptRuntime::PopulateElementHeaders(const std::shared_ptr<uint8_t> header_buffer, size_t offset, const Element& elem)
2202*26e52a70SEwan Crawford {
2203*26e52a70SEwan Crawford     // File struct for an element header with all the relevant details copied from elem.
2204*26e52a70SEwan Crawford     // We assume members are valid already.
2205*26e52a70SEwan Crawford     AllocationDetails::ElementHeader elem_header;
2206*26e52a70SEwan Crawford     elem_header.type = *elem.type.get();
2207*26e52a70SEwan Crawford     elem_header.kind = *elem.type_kind.get();
2208*26e52a70SEwan Crawford     elem_header.element_size = *elem.datum_size.get();
2209*26e52a70SEwan Crawford     elem_header.vector_size = *elem.type_vec_size.get();
2210*26e52a70SEwan Crawford     elem_header.array_size = elem.array_size.isValid() ? *elem.array_size.get() : 0;
2211*26e52a70SEwan Crawford     const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
2212*26e52a70SEwan Crawford 
2213*26e52a70SEwan Crawford     // Copy struct into buffer and advance offset
2214*26e52a70SEwan Crawford     // We assume that header_buffer has been checked for NULL before this method is called
2215*26e52a70SEwan Crawford     memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
2216*26e52a70SEwan Crawford     offset += elem_header_size;
2217*26e52a70SEwan Crawford 
2218*26e52a70SEwan Crawford     // Starting offset of child ElementHeader struct
2219*26e52a70SEwan Crawford     size_t child_offset = offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2220*26e52a70SEwan Crawford     for (const RenderScriptRuntime::Element& child : elem.children)
2221*26e52a70SEwan Crawford     {
2222*26e52a70SEwan Crawford         // Recursively populate the buffer with the element header structs of children.
2223*26e52a70SEwan Crawford         // Then save the offsets where they were set after the parent element header.
2224*26e52a70SEwan Crawford         memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
2225*26e52a70SEwan Crawford         offset += sizeof(uint32_t);
2226*26e52a70SEwan Crawford 
2227*26e52a70SEwan Crawford         child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
2228*26e52a70SEwan Crawford     }
2229*26e52a70SEwan Crawford 
2230*26e52a70SEwan Crawford     // Zero indicates no more children
2231*26e52a70SEwan Crawford     memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
2232*26e52a70SEwan Crawford 
2233*26e52a70SEwan Crawford     return child_offset;
2234*26e52a70SEwan Crawford }
2235*26e52a70SEwan Crawford 
2236*26e52a70SEwan Crawford // Given an Element object this function returns the total size needed in the file header to store the element's details.
2237*26e52a70SEwan Crawford // Taking into account the size of the element header struct, plus the offsets to all the element's children.
2238*26e52a70SEwan Crawford // Function is recursive so that the size of all ancestors is taken into account.
2239*26e52a70SEwan Crawford size_t
2240*26e52a70SEwan Crawford RenderScriptRuntime::CalculateElementHeaderSize(const Element& elem)
2241*26e52a70SEwan Crawford {
2242*26e52a70SEwan Crawford     size_t size = (elem.children.size() + 1) * sizeof(uint32_t); // Offsets to children plus zero terminator
2243*26e52a70SEwan Crawford     size += sizeof(AllocationDetails::ElementHeader); // Size of header struct with type details
2244*26e52a70SEwan Crawford 
2245*26e52a70SEwan Crawford     // Calculate recursively for all descendants
2246*26e52a70SEwan Crawford     for (const Element& child : elem.children)
2247*26e52a70SEwan Crawford         size += CalculateElementHeaderSize(child);
2248*26e52a70SEwan Crawford 
2249*26e52a70SEwan Crawford     return size;
2250*26e52a70SEwan Crawford }
2251*26e52a70SEwan Crawford 
225255232f09SEwan Crawford // Function copies allocation contents into a binary file.
225355232f09SEwan Crawford // This file can then be loaded later into a different allocation.
225455232f09SEwan Crawford // There is a header, FileHeader, before the allocation data containing meta-data.
225555232f09SEwan Crawford bool
225655232f09SEwan Crawford RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr)
225755232f09SEwan Crawford {
225855232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
225955232f09SEwan Crawford 
226055232f09SEwan Crawford     // Find allocation with the given id
226155232f09SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, alloc_id);
226255232f09SEwan Crawford     if (!alloc)
226355232f09SEwan Crawford         return false;
226455232f09SEwan Crawford 
226555232f09SEwan Crawford     if (log)
226655232f09SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
226755232f09SEwan Crawford 
226855232f09SEwan Crawford      // JIT all the allocation details
22698b59062aSEwan Crawford     if (alloc->shouldRefresh())
227055232f09SEwan Crawford     {
227155232f09SEwan Crawford         if (log)
227255232f09SEwan Crawford             log->Printf("RenderScriptRuntime::SaveAllocation - Allocation details not calculated yet, jitting info");
227355232f09SEwan Crawford 
227455232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
227555232f09SEwan Crawford         {
227655232f09SEwan Crawford             if (log)
227755232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::SaveAllocation - Couldn't JIT allocation details");
22784cfc9198SSylvestre Ledru             return false;
227955232f09SEwan Crawford         }
228055232f09SEwan Crawford     }
228155232f09SEwan Crawford 
22828b244e21SEwan Crawford     assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid() && alloc->element.datum_size.get()
22838b244e21SEwan Crawford            && alloc->element.type_kind.isValid() && alloc->dimension.isValid() && "Allocation information not available");
228455232f09SEwan Crawford 
228555232f09SEwan Crawford     // Check we can create writable file
228655232f09SEwan Crawford     FileSpec file_spec(filename, true);
228755232f09SEwan Crawford     File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionTruncate);
228855232f09SEwan Crawford     if (!file)
228955232f09SEwan Crawford     {
229055232f09SEwan Crawford         strm.Printf("Error: Failed to open '%s' for writing", filename);
229155232f09SEwan Crawford         strm.EOL();
229255232f09SEwan Crawford         return false;
229355232f09SEwan Crawford     }
229455232f09SEwan Crawford 
229555232f09SEwan Crawford     // Read allocation into buffer of heap memory
229655232f09SEwan Crawford     const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
229755232f09SEwan Crawford     if (!buffer)
229855232f09SEwan Crawford     {
229955232f09SEwan Crawford         strm.Printf("Error: Couldn't read allocation data into buffer");
230055232f09SEwan Crawford         strm.EOL();
230155232f09SEwan Crawford         return false;
230255232f09SEwan Crawford     }
230355232f09SEwan Crawford 
230455232f09SEwan Crawford     // Create the file header
230555232f09SEwan Crawford     AllocationDetails::FileHeader head;
230655232f09SEwan Crawford     head.ident[0] = 'R'; head.ident[1] = 'S'; head.ident[2] = 'A'; head.ident[3] = 'D';
23072d62328aSEwan Crawford     head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
23082d62328aSEwan Crawford     head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
23092d62328aSEwan Crawford     head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
2310*26e52a70SEwan Crawford 
2311*26e52a70SEwan Crawford     const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2312*26e52a70SEwan Crawford     assert((sizeof(AllocationDetails::FileHeader) + element_header_size) < UINT16_MAX && "Element header too large");
2313*26e52a70SEwan Crawford     head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) + element_header_size);
231455232f09SEwan Crawford 
231555232f09SEwan Crawford     // Write the file header
231655232f09SEwan Crawford     size_t num_bytes = sizeof(AllocationDetails::FileHeader);
2317*26e52a70SEwan Crawford     if (log)
2318*26e52a70SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Writing File Header, 0x%zX bytes", num_bytes);
2319*26e52a70SEwan Crawford 
2320*26e52a70SEwan Crawford     Error err = file.Write(&head, num_bytes);
2321*26e52a70SEwan Crawford     if (!err.Success())
2322*26e52a70SEwan Crawford     {
2323*26e52a70SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
2324*26e52a70SEwan Crawford         strm.EOL();
2325*26e52a70SEwan Crawford         return false;
2326*26e52a70SEwan Crawford     }
2327*26e52a70SEwan Crawford 
2328*26e52a70SEwan Crawford     // Create the headers describing the element type of the allocation.
2329*26e52a70SEwan Crawford     std::shared_ptr<uint8_t> element_header_buffer(new uint8_t[element_header_size]);
2330*26e52a70SEwan Crawford     if (element_header_buffer == nullptr)
2331*26e52a70SEwan Crawford     {
2332*26e52a70SEwan Crawford         strm.Printf("Internal Error: Couldn't allocate %zu bytes on the heap", element_header_size);
2333*26e52a70SEwan Crawford         strm.EOL();
2334*26e52a70SEwan Crawford         return false;
2335*26e52a70SEwan Crawford     }
2336*26e52a70SEwan Crawford 
2337*26e52a70SEwan Crawford     PopulateElementHeaders(element_header_buffer, 0, alloc->element);
2338*26e52a70SEwan Crawford 
2339*26e52a70SEwan Crawford     // Write headers for allocation element type to file
2340*26e52a70SEwan Crawford     num_bytes = element_header_size;
2341*26e52a70SEwan Crawford     if (log)
2342*26e52a70SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Writing Element Headers, 0x%zX bytes", num_bytes);
2343*26e52a70SEwan Crawford 
2344*26e52a70SEwan Crawford     err = file.Write(element_header_buffer.get(), num_bytes);
234555232f09SEwan Crawford     if (!err.Success())
234655232f09SEwan Crawford     {
234755232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
234855232f09SEwan Crawford         strm.EOL();
234955232f09SEwan Crawford         return false;
235055232f09SEwan Crawford     }
235155232f09SEwan Crawford 
235255232f09SEwan Crawford     // Write allocation data to file
235355232f09SEwan Crawford     num_bytes = static_cast<size_t>(*alloc->size.get());
235455232f09SEwan Crawford     if (log)
2355*26e52a70SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Writing 0x%zX bytes", num_bytes);
235655232f09SEwan Crawford 
235755232f09SEwan Crawford     err = file.Write(buffer.get(), num_bytes);
235855232f09SEwan Crawford     if (!err.Success())
235955232f09SEwan Crawford     {
236055232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
236155232f09SEwan Crawford         strm.EOL();
236255232f09SEwan Crawford         return false;
236355232f09SEwan Crawford     }
236455232f09SEwan Crawford 
236555232f09SEwan Crawford     strm.Printf("Allocation written to file '%s'", filename);
236655232f09SEwan Crawford     strm.EOL();
236715f2bd95SEwan Crawford     return true;
236815f2bd95SEwan Crawford }
236915f2bd95SEwan Crawford 
23705ec532a9SColin Riley bool
23715ec532a9SColin Riley RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp)
23725ec532a9SColin Riley {
23734640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
23744640cde1SColin Riley 
23755ec532a9SColin Riley     if (module_sp)
23765ec532a9SColin Riley     {
23775ec532a9SColin Riley         for (const auto &rs_module : m_rsmodules)
23785ec532a9SColin Riley         {
23794640cde1SColin Riley             if (rs_module->m_module == module_sp)
23807dc7771cSEwan Crawford             {
23817dc7771cSEwan Crawford                 // Check if the user has enabled automatically breaking on
23827dc7771cSEwan Crawford                 // all RS kernels.
23837dc7771cSEwan Crawford                 if (m_breakAllKernels)
23847dc7771cSEwan Crawford                     BreakOnModuleKernels(rs_module);
23857dc7771cSEwan Crawford 
23865ec532a9SColin Riley                 return false;
23875ec532a9SColin Riley             }
23887dc7771cSEwan Crawford         }
2389ef20b08fSColin Riley         bool module_loaded = false;
2390ef20b08fSColin Riley         switch (GetModuleKind(module_sp))
2391ef20b08fSColin Riley         {
2392ef20b08fSColin Riley             case eModuleKindKernelObj:
2393ef20b08fSColin Riley             {
23944640cde1SColin Riley                 RSModuleDescriptorSP module_desc;
23954640cde1SColin Riley                 module_desc.reset(new RSModuleDescriptor(module_sp));
23964640cde1SColin Riley                 if (module_desc->ParseRSInfo())
23975ec532a9SColin Riley                 {
23985ec532a9SColin Riley                     m_rsmodules.push_back(module_desc);
2399ef20b08fSColin Riley                     module_loaded = true;
24005ec532a9SColin Riley                 }
24014640cde1SColin Riley                 if (module_loaded)
24024640cde1SColin Riley                 {
24034640cde1SColin Riley                     FixupScriptDetails(module_desc);
24044640cde1SColin Riley                 }
2405ef20b08fSColin Riley                 break;
2406ef20b08fSColin Riley             }
2407ef20b08fSColin Riley             case eModuleKindDriver:
24084640cde1SColin Riley             {
24094640cde1SColin Riley                 if (!m_libRSDriver)
24104640cde1SColin Riley                 {
24114640cde1SColin Riley                     m_libRSDriver = module_sp;
24124640cde1SColin Riley                     LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
24134640cde1SColin Riley                 }
24144640cde1SColin Riley                 break;
24154640cde1SColin Riley             }
2416ef20b08fSColin Riley             case eModuleKindImpl:
24174640cde1SColin Riley             {
24184640cde1SColin Riley                 m_libRSCpuRef = module_sp;
24194640cde1SColin Riley                 break;
24204640cde1SColin Riley             }
2421ef20b08fSColin Riley             case eModuleKindLibRS:
24224640cde1SColin Riley             {
24234640cde1SColin Riley                 if (!m_libRS)
24244640cde1SColin Riley                 {
24254640cde1SColin Riley                     m_libRS = module_sp;
24264640cde1SColin Riley                     static ConstString gDbgPresentStr("gDebuggerPresent");
24274640cde1SColin Riley                     const Symbol* debug_present = m_libRS->FindFirstSymbolWithNameAndType(gDbgPresentStr, eSymbolTypeData);
24284640cde1SColin Riley                     if (debug_present)
24294640cde1SColin Riley                     {
24304640cde1SColin Riley                         Error error;
24314640cde1SColin Riley                         uint32_t flag = 0x00000001U;
24324640cde1SColin Riley                         Target &target = GetProcess()->GetTarget();
2433358cf1eaSGreg Clayton                         addr_t addr = debug_present->GetLoadAddress(&target);
24344640cde1SColin Riley                         GetProcess()->WriteMemory(addr, &flag, sizeof(flag), error);
24354640cde1SColin Riley                         if(error.Success())
24364640cde1SColin Riley                         {
24374640cde1SColin Riley                             if (log)
24384640cde1SColin Riley                                 log->Printf ("RenderScriptRuntime::LoadModule - Debugger present flag set on debugee");
24394640cde1SColin Riley 
24404640cde1SColin Riley                             m_debuggerPresentFlagged = true;
24414640cde1SColin Riley                         }
24424640cde1SColin Riley                         else if (log)
24434640cde1SColin Riley                         {
24444640cde1SColin Riley                             log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags '%s' ", error.AsCString());
24454640cde1SColin Riley                         }
24464640cde1SColin Riley                     }
24474640cde1SColin Riley                     else if (log)
24484640cde1SColin Riley                     {
24494640cde1SColin Riley                         log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags - symbol not found");
24504640cde1SColin Riley                     }
24514640cde1SColin Riley                 }
24524640cde1SColin Riley                 break;
24534640cde1SColin Riley             }
2454ef20b08fSColin Riley             default:
2455ef20b08fSColin Riley                 break;
2456ef20b08fSColin Riley         }
2457ef20b08fSColin Riley         if (module_loaded)
2458ef20b08fSColin Riley             Update();
2459ef20b08fSColin Riley         return module_loaded;
24605ec532a9SColin Riley     }
24615ec532a9SColin Riley     return false;
24625ec532a9SColin Riley }
24635ec532a9SColin Riley 
2464ef20b08fSColin Riley void
2465ef20b08fSColin Riley RenderScriptRuntime::Update()
2466ef20b08fSColin Riley {
2467ef20b08fSColin Riley     if (m_rsmodules.size() > 0)
2468ef20b08fSColin Riley     {
2469ef20b08fSColin Riley         if (!m_initiated)
2470ef20b08fSColin Riley         {
2471ef20b08fSColin Riley             Initiate();
2472ef20b08fSColin Riley         }
2473ef20b08fSColin Riley     }
2474ef20b08fSColin Riley }
2475ef20b08fSColin Riley 
24765ec532a9SColin Riley // The maximum line length of an .rs.info packet
24775ec532a9SColin Riley #define MAXLINE 500
24785ec532a9SColin Riley 
24795ec532a9SColin Riley // The .rs.info symbol in renderscript modules contains a string which needs to be parsed.
24805ec532a9SColin Riley // The string is basic and is parsed on a line by line basis.
24815ec532a9SColin Riley bool
24825ec532a9SColin Riley RSModuleDescriptor::ParseRSInfo()
24835ec532a9SColin Riley {
24845ec532a9SColin Riley     const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
24855ec532a9SColin Riley     if (info_sym)
24865ec532a9SColin Riley     {
2487358cf1eaSGreg Clayton         const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
24885ec532a9SColin Riley         const addr_t size = info_sym->GetByteSize();
24895ec532a9SColin Riley         const FileSpec fs = m_module->GetFileSpec();
24905ec532a9SColin Riley 
24915ec532a9SColin Riley         DataBufferSP buffer = fs.ReadFileContents(addr, size);
24925ec532a9SColin Riley 
24935ec532a9SColin Riley         if (!buffer)
24945ec532a9SColin Riley             return false;
24955ec532a9SColin Riley 
24965ec532a9SColin Riley         std::string info((const char *)buffer->GetBytes());
24975ec532a9SColin Riley 
24985ec532a9SColin Riley         std::vector<std::string> info_lines;
2499e8433cc1SBruce Mitchener         size_t lpos = info.find('\n');
25005ec532a9SColin Riley         while (lpos != std::string::npos)
25015ec532a9SColin Riley         {
25025ec532a9SColin Riley             info_lines.push_back(info.substr(0, lpos));
25035ec532a9SColin Riley             info = info.substr(lpos + 1);
2504e8433cc1SBruce Mitchener             lpos = info.find('\n');
25055ec532a9SColin Riley         }
25065ec532a9SColin Riley         size_t offset = 0;
25075ec532a9SColin Riley         while (offset < info_lines.size())
25085ec532a9SColin Riley         {
25095ec532a9SColin Riley             std::string line = info_lines[offset];
25105ec532a9SColin Riley             // Parse directives
25115ec532a9SColin Riley             uint32_t numDefns = 0;
25125ec532a9SColin Riley             if (sscanf(line.c_str(), "exportVarCount: %u", &numDefns) == 1)
25135ec532a9SColin Riley             {
25145ec532a9SColin Riley                 while (numDefns--)
25154640cde1SColin Riley                     m_globals.push_back(RSGlobalDescriptor(this, info_lines[++offset].c_str()));
25165ec532a9SColin Riley             }
25175ec532a9SColin Riley             else if (sscanf(line.c_str(), "exportFuncCount: %u", &numDefns) == 1)
25185ec532a9SColin Riley             {
25195ec532a9SColin Riley             }
25205ec532a9SColin Riley             else if (sscanf(line.c_str(), "exportForEachCount: %u", &numDefns) == 1)
25215ec532a9SColin Riley             {
25225ec532a9SColin Riley                 char name[MAXLINE];
25235ec532a9SColin Riley                 while (numDefns--)
25245ec532a9SColin Riley                 {
25255ec532a9SColin Riley                     uint32_t slot = 0;
25265ec532a9SColin Riley                     name[0] = '\0';
25275ec532a9SColin Riley                     if (sscanf(info_lines[++offset].c_str(), "%u - %s", &slot, &name[0]) == 2)
25285ec532a9SColin Riley                     {
25294640cde1SColin Riley                         m_kernels.push_back(RSKernelDescriptor(this, name, slot));
25304640cde1SColin Riley                     }
25314640cde1SColin Riley                 }
25324640cde1SColin Riley             }
25334640cde1SColin Riley             else if (sscanf(line.c_str(), "pragmaCount: %u", &numDefns) == 1)
25344640cde1SColin Riley             {
25354640cde1SColin Riley                 char name[MAXLINE];
25364640cde1SColin Riley                 char value[MAXLINE];
25374640cde1SColin Riley                 while (numDefns--)
25384640cde1SColin Riley                 {
25394640cde1SColin Riley                     name[0] = '\0';
25404640cde1SColin Riley                     value[0] = '\0';
25414640cde1SColin Riley                     if (sscanf(info_lines[++offset].c_str(), "%s - %s", &name[0], &value[0]) != 0
25424640cde1SColin Riley                         && (name[0] != '\0'))
25434640cde1SColin Riley                     {
25444640cde1SColin Riley                         m_pragmas[std::string(name)] = value;
25455ec532a9SColin Riley                     }
25465ec532a9SColin Riley                 }
25475ec532a9SColin Riley             }
25485ec532a9SColin Riley             else if (sscanf(line.c_str(), "objectSlotCount: %u", &numDefns) == 1)
25495ec532a9SColin Riley             {
25505ec532a9SColin Riley             }
25515ec532a9SColin Riley 
25525ec532a9SColin Riley             offset++;
25535ec532a9SColin Riley         }
25545ec532a9SColin Riley         return m_kernels.size() > 0;
25555ec532a9SColin Riley     }
25565ec532a9SColin Riley     return false;
25575ec532a9SColin Riley }
25585ec532a9SColin Riley 
25595ec532a9SColin Riley bool
25605ec532a9SColin Riley RenderScriptRuntime::ProbeModules(const ModuleList module_list)
25615ec532a9SColin Riley {
25625ec532a9SColin Riley     bool rs_found = false;
25635ec532a9SColin Riley     size_t num_modules = module_list.GetSize();
25645ec532a9SColin Riley     for (size_t i = 0; i < num_modules; i++)
25655ec532a9SColin Riley     {
25665ec532a9SColin Riley         auto module = module_list.GetModuleAtIndex(i);
25675ec532a9SColin Riley         rs_found |= LoadModule(module);
25685ec532a9SColin Riley     }
25695ec532a9SColin Riley     return rs_found;
25705ec532a9SColin Riley }
25715ec532a9SColin Riley 
25725ec532a9SColin Riley void
25734640cde1SColin Riley RenderScriptRuntime::Status(Stream &strm) const
25744640cde1SColin Riley {
25754640cde1SColin Riley     if (m_libRS)
25764640cde1SColin Riley     {
25774640cde1SColin Riley         strm.Printf("Runtime Library discovered.");
25784640cde1SColin Riley         strm.EOL();
25794640cde1SColin Riley     }
25804640cde1SColin Riley     if (m_libRSDriver)
25814640cde1SColin Riley     {
25824640cde1SColin Riley         strm.Printf("Runtime Driver discovered.");
25834640cde1SColin Riley         strm.EOL();
25844640cde1SColin Riley     }
25854640cde1SColin Riley     if (m_libRSCpuRef)
25864640cde1SColin Riley     {
25874640cde1SColin Riley         strm.Printf("CPU Reference Implementation discovered.");
25884640cde1SColin Riley         strm.EOL();
25894640cde1SColin Riley     }
25904640cde1SColin Riley 
25914640cde1SColin Riley     if (m_runtimeHooks.size())
25924640cde1SColin Riley     {
25934640cde1SColin Riley         strm.Printf("Runtime functions hooked:");
25944640cde1SColin Riley         strm.EOL();
25954640cde1SColin Riley         for (auto b : m_runtimeHooks)
25964640cde1SColin Riley         {
25974640cde1SColin Riley             strm.Indent(b.second->defn->name);
25984640cde1SColin Riley             strm.EOL();
25994640cde1SColin Riley         }
26004640cde1SColin Riley     }
26014640cde1SColin Riley     else
26024640cde1SColin Riley     {
26034640cde1SColin Riley         strm.Printf("Runtime is not hooked.");
26044640cde1SColin Riley         strm.EOL();
26054640cde1SColin Riley     }
26064640cde1SColin Riley }
26074640cde1SColin Riley 
26084640cde1SColin Riley void
26094640cde1SColin Riley RenderScriptRuntime::DumpContexts(Stream &strm) const
26104640cde1SColin Riley {
26114640cde1SColin Riley     strm.Printf("Inferred RenderScript Contexts:");
26124640cde1SColin Riley     strm.EOL();
26134640cde1SColin Riley     strm.IndentMore();
26144640cde1SColin Riley 
26154640cde1SColin Riley     std::map<addr_t, uint64_t> contextReferences;
26164640cde1SColin Riley 
261778f339d1SEwan Crawford     // Iterate over all of the currently discovered scripts.
261878f339d1SEwan Crawford     // Note: We cant push or pop from m_scripts inside this loop or it may invalidate script.
26194640cde1SColin Riley     for (const auto & script : m_scripts)
26204640cde1SColin Riley     {
262178f339d1SEwan Crawford         if (!script->context.isValid())
262278f339d1SEwan Crawford             continue;
262378f339d1SEwan Crawford         lldb::addr_t context = *script->context;
262478f339d1SEwan Crawford 
262578f339d1SEwan Crawford         if (contextReferences.find(context) != contextReferences.end())
26264640cde1SColin Riley         {
262778f339d1SEwan Crawford             contextReferences[context]++;
26284640cde1SColin Riley         }
26294640cde1SColin Riley         else
26304640cde1SColin Riley         {
263178f339d1SEwan Crawford             contextReferences[context] = 1;
26324640cde1SColin Riley         }
26334640cde1SColin Riley     }
26344640cde1SColin Riley 
26354640cde1SColin Riley     for (const auto& cRef : contextReferences)
26364640cde1SColin Riley     {
26374640cde1SColin Riley         strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances", cRef.first, cRef.second);
26384640cde1SColin Riley         strm.EOL();
26394640cde1SColin Riley     }
26404640cde1SColin Riley     strm.IndentLess();
26414640cde1SColin Riley }
26424640cde1SColin Riley 
26434640cde1SColin Riley void
26444640cde1SColin Riley RenderScriptRuntime::DumpKernels(Stream &strm) const
26454640cde1SColin Riley {
26464640cde1SColin Riley     strm.Printf("RenderScript Kernels:");
26474640cde1SColin Riley     strm.EOL();
26484640cde1SColin Riley     strm.IndentMore();
26494640cde1SColin Riley     for (const auto &module : m_rsmodules)
26504640cde1SColin Riley     {
26514640cde1SColin Riley         strm.Printf("Resource '%s':",module->m_resname.c_str());
26524640cde1SColin Riley         strm.EOL();
26534640cde1SColin Riley         for (const auto &kernel : module->m_kernels)
26544640cde1SColin Riley         {
26554640cde1SColin Riley             strm.Indent(kernel.m_name.AsCString());
26564640cde1SColin Riley             strm.EOL();
26574640cde1SColin Riley         }
26584640cde1SColin Riley     }
26594640cde1SColin Riley     strm.IndentLess();
26604640cde1SColin Riley }
26614640cde1SColin Riley 
2662a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails*
2663a0f08674SEwan Crawford RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id)
2664a0f08674SEwan Crawford {
2665a0f08674SEwan Crawford     AllocationDetails* alloc = nullptr;
2666a0f08674SEwan Crawford 
2667a0f08674SEwan Crawford     // See if we can find allocation using id as an index;
2668a0f08674SEwan Crawford     if (alloc_id <= m_allocations.size() && alloc_id != 0
2669a0f08674SEwan Crawford         && m_allocations[alloc_id-1]->id == alloc_id)
2670a0f08674SEwan Crawford     {
2671a0f08674SEwan Crawford         alloc = m_allocations[alloc_id-1].get();
2672a0f08674SEwan Crawford         return alloc;
2673a0f08674SEwan Crawford     }
2674a0f08674SEwan Crawford 
2675a0f08674SEwan Crawford     // Fallback to searching
2676a0f08674SEwan Crawford     for (const auto & a : m_allocations)
2677a0f08674SEwan Crawford     {
2678a0f08674SEwan Crawford        if (a->id == alloc_id)
2679a0f08674SEwan Crawford        {
2680a0f08674SEwan Crawford            alloc = a.get();
2681a0f08674SEwan Crawford            break;
2682a0f08674SEwan Crawford        }
2683a0f08674SEwan Crawford     }
2684a0f08674SEwan Crawford 
2685a0f08674SEwan Crawford     if (alloc == nullptr)
2686a0f08674SEwan Crawford     {
2687a0f08674SEwan Crawford         strm.Printf("Error: Couldn't find allocation with id matching %u", alloc_id);
2688a0f08674SEwan Crawford         strm.EOL();
2689a0f08674SEwan Crawford     }
2690a0f08674SEwan Crawford 
2691a0f08674SEwan Crawford     return alloc;
2692a0f08674SEwan Crawford }
2693a0f08674SEwan Crawford 
2694a0f08674SEwan Crawford // Prints the contents of an allocation to the output stream, which may be a file
2695a0f08674SEwan Crawford bool
2696a0f08674SEwan Crawford RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame* frame_ptr, const uint32_t id)
2697a0f08674SEwan Crawford {
2698a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2699a0f08674SEwan Crawford 
2700a0f08674SEwan Crawford     // Check we can find the desired allocation
2701a0f08674SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, id);
2702a0f08674SEwan Crawford     if (!alloc)
2703a0f08674SEwan Crawford         return false; // FindAllocByID() will print error message for us here
2704a0f08674SEwan Crawford 
2705a0f08674SEwan Crawford     if (log)
2706a0f08674SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
2707a0f08674SEwan Crawford 
2708a0f08674SEwan Crawford     // Check we have information about the allocation, if not calculate it
27098b59062aSEwan Crawford     if (alloc->shouldRefresh())
2710a0f08674SEwan Crawford     {
2711a0f08674SEwan Crawford         if (log)
2712a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::DumpAllocation - Allocation details not calculated yet, jitting info");
2713a0f08674SEwan Crawford 
2714a0f08674SEwan Crawford         // JIT all the allocation information
2715a0f08674SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
2716a0f08674SEwan Crawford         {
2717a0f08674SEwan Crawford             strm.Printf("Error: Couldn't JIT allocation details");
2718a0f08674SEwan Crawford             strm.EOL();
2719a0f08674SEwan Crawford             return false;
2720a0f08674SEwan Crawford         }
2721a0f08674SEwan Crawford     }
2722a0f08674SEwan Crawford 
2723a0f08674SEwan Crawford     // Establish format and size of each data element
27248b244e21SEwan Crawford     const unsigned int vec_size = *alloc->element.type_vec_size.get();
27258b244e21SEwan Crawford     const Element::DataType type = *alloc->element.type.get();
2726a0f08674SEwan Crawford 
27272e920715SEwan Crawford     assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT
2728a0f08674SEwan Crawford                                                    && "Invalid allocation type");
2729a0f08674SEwan Crawford 
27302e920715SEwan Crawford     lldb::Format format;
27312e920715SEwan Crawford     if (type >= Element::RS_TYPE_ELEMENT)
27322e920715SEwan Crawford         format = eFormatHex;
27332e920715SEwan Crawford     else
27342e920715SEwan Crawford         format = vec_size == 1 ? static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatSingle])
2735a0f08674SEwan Crawford                                : static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatVector]);
2736a0f08674SEwan Crawford 
27378b244e21SEwan Crawford     const unsigned int data_size = *alloc->element.datum_size.get();
2738a0f08674SEwan Crawford 
2739a0f08674SEwan Crawford     if (log)
27408b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - Element size %u bytes, including padding", data_size);
2741a0f08674SEwan Crawford 
274255232f09SEwan Crawford     // Allocate a buffer to copy data into
274355232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
274455232f09SEwan Crawford     if (!buffer)
274555232f09SEwan Crawford     {
27462e920715SEwan Crawford         strm.Printf("Error: Couldn't read allocation data");
274755232f09SEwan Crawford         strm.EOL();
274855232f09SEwan Crawford         return false;
274955232f09SEwan Crawford     }
275055232f09SEwan Crawford 
2751a0f08674SEwan Crawford     // Calculate stride between rows as there may be padding at end of rows since
2752a0f08674SEwan Crawford     // allocated memory is 16-byte aligned
2753a0f08674SEwan Crawford     if (!alloc->stride.isValid())
2754a0f08674SEwan Crawford     {
2755a0f08674SEwan Crawford         if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
2756a0f08674SEwan Crawford             alloc->stride = 0;
2757a0f08674SEwan Crawford         else if (!JITAllocationStride(alloc, frame_ptr))
2758a0f08674SEwan Crawford         {
2759a0f08674SEwan Crawford             strm.Printf("Error: Couldn't calculate allocation row stride");
2760a0f08674SEwan Crawford             strm.EOL();
2761a0f08674SEwan Crawford             return false;
2762a0f08674SEwan Crawford         }
2763a0f08674SEwan Crawford     }
2764a0f08674SEwan Crawford     const unsigned int stride = *alloc->stride.get();
27658b244e21SEwan Crawford     const unsigned int size = *alloc->size.get(); // Size of whole allocation
27668b244e21SEwan Crawford     const unsigned int padding = alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
2767a0f08674SEwan Crawford     if (log)
27688b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - stride %u bytes, size %u bytes, padding %u", stride, size, padding);
2769a0f08674SEwan Crawford 
2770a0f08674SEwan Crawford     // Find dimensions used to index loops, so need to be non-zero
2771a0f08674SEwan Crawford     unsigned int dim_x = alloc->dimension.get()->dim_1;
2772a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 1 : dim_x;
2773a0f08674SEwan Crawford 
2774a0f08674SEwan Crawford     unsigned int dim_y = alloc->dimension.get()->dim_2;
2775a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 1 : dim_y;
2776a0f08674SEwan Crawford 
2777a0f08674SEwan Crawford     unsigned int dim_z = alloc->dimension.get()->dim_3;
2778a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 1 : dim_z;
2779a0f08674SEwan Crawford 
278055232f09SEwan Crawford     // Use data extractor to format output
278155232f09SEwan Crawford     const uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
278255232f09SEwan Crawford     DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(), archByteSize);
278355232f09SEwan Crawford 
2784a0f08674SEwan Crawford     unsigned int offset = 0;   // Offset in buffer to next element to be printed
2785a0f08674SEwan Crawford     unsigned int prev_row = 0; // Offset to the start of the previous row
2786a0f08674SEwan Crawford 
2787a0f08674SEwan Crawford     // Iterate over allocation dimensions, printing results to user
2788a0f08674SEwan Crawford     strm.Printf("Data (X, Y, Z):");
2789a0f08674SEwan Crawford     for (unsigned int z = 0; z < dim_z; ++z)
2790a0f08674SEwan Crawford     {
2791a0f08674SEwan Crawford         for (unsigned int y = 0; y < dim_y; ++y)
2792a0f08674SEwan Crawford         {
2793a0f08674SEwan Crawford             // Use stride to index start of next row.
2794a0f08674SEwan Crawford             if (!(y==0 && z==0))
2795a0f08674SEwan Crawford                 offset = prev_row + stride;
2796a0f08674SEwan Crawford             prev_row = offset;
2797a0f08674SEwan Crawford 
2798a0f08674SEwan Crawford             // Print each element in the row individually
2799a0f08674SEwan Crawford             for (unsigned int x = 0; x < dim_x; ++x)
2800a0f08674SEwan Crawford             {
2801a0f08674SEwan Crawford                 strm.Printf("\n(%u, %u, %u) = ", x, y, z);
28028b244e21SEwan Crawford                 if ((type == Element::RS_TYPE_NONE) && (alloc->element.children.size() > 0) &&
2803fe06b5adSAdrian McCarthy                     (alloc->element.type_name != Element::GetFallbackStructName()))
28048b244e21SEwan Crawford                 {
28058b244e21SEwan Crawford                     // Here we are dumping an Element of struct type.
28068b244e21SEwan Crawford                     // This is done using expression evaluation with the name of the struct type and pointer to element.
28078b244e21SEwan Crawford 
28088b244e21SEwan Crawford                     // Don't print the name of the resulting expression, since this will be '$[0-9]+'
28098b244e21SEwan Crawford                     DumpValueObjectOptions expr_options;
28108b244e21SEwan Crawford                     expr_options.SetHideName(true);
28118b244e21SEwan Crawford 
28128b244e21SEwan Crawford                     // Setup expression as derefrencing a pointer cast to element address.
2813b1651b8dSEwan Crawford                     char expr_char_buffer[jit_max_expr_size];
2814b1651b8dSEwan Crawford                     int chars_written = snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
28158b244e21SEwan Crawford                                         alloc->element.type_name.AsCString(), *alloc->data_ptr.get() + offset);
28168b244e21SEwan Crawford 
2817b1651b8dSEwan Crawford                     if (chars_written < 0 || chars_written >= jit_max_expr_size)
28188b244e21SEwan Crawford                     {
28198b244e21SEwan Crawford                         if (log)
28208b244e21SEwan Crawford                             log->Printf("RenderScriptRuntime::DumpAllocation- Error in snprintf()");
28218b244e21SEwan Crawford                         continue;
28228b244e21SEwan Crawford                     }
28238b244e21SEwan Crawford 
28248b244e21SEwan Crawford                     // Evaluate expression
28258b244e21SEwan Crawford                     ValueObjectSP expr_result;
28268b244e21SEwan Crawford                     GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer, frame_ptr, expr_result);
28278b244e21SEwan Crawford 
28288b244e21SEwan Crawford                     // Print the results to our stream.
28298b244e21SEwan Crawford                     expr_result->Dump(strm, expr_options);
28308b244e21SEwan Crawford                 }
28318b244e21SEwan Crawford                 else
28328b244e21SEwan Crawford                 {
28338b244e21SEwan Crawford                     alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0, 0);
28348b244e21SEwan Crawford                 }
28358b244e21SEwan Crawford                 offset += data_size;
2836a0f08674SEwan Crawford             }
2837a0f08674SEwan Crawford         }
2838a0f08674SEwan Crawford     }
2839a0f08674SEwan Crawford     strm.EOL();
2840a0f08674SEwan Crawford 
2841a0f08674SEwan Crawford     return true;
2842a0f08674SEwan Crawford }
2843a0f08674SEwan Crawford 
284415f2bd95SEwan Crawford // Prints infomation regarding all the currently loaded allocations.
284515f2bd95SEwan Crawford // These details are gathered by jitting the runtime, which has as latency.
284615f2bd95SEwan Crawford void
284715f2bd95SEwan Crawford RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame* frame_ptr, bool recompute)
284815f2bd95SEwan Crawford {
284915f2bd95SEwan Crawford     strm.Printf("RenderScript Allocations:");
285015f2bd95SEwan Crawford     strm.EOL();
285115f2bd95SEwan Crawford     strm.IndentMore();
285215f2bd95SEwan Crawford 
285315f2bd95SEwan Crawford     for (auto &alloc : m_allocations)
285415f2bd95SEwan Crawford     {
285515f2bd95SEwan Crawford         // JIT the allocation info if we haven't done it, or the user forces us to.
28568b59062aSEwan Crawford         bool do_refresh = alloc->shouldRefresh() || recompute;
285715f2bd95SEwan Crawford 
285815f2bd95SEwan Crawford         // JIT current allocation information
285915f2bd95SEwan Crawford         if (do_refresh && !RefreshAllocation(alloc.get(), frame_ptr))
286015f2bd95SEwan Crawford         {
286115f2bd95SEwan Crawford             strm.Printf("Error: Couldn't evaluate details for allocation %u\n", alloc->id);
286215f2bd95SEwan Crawford             continue;
286315f2bd95SEwan Crawford         }
286415f2bd95SEwan Crawford 
286515f2bd95SEwan Crawford         strm.Printf("%u:\n",alloc->id);
286615f2bd95SEwan Crawford         strm.IndentMore();
286715f2bd95SEwan Crawford 
286815f2bd95SEwan Crawford         strm.Indent("Context: ");
286915f2bd95SEwan Crawford         if (!alloc->context.isValid())
287015f2bd95SEwan Crawford             strm.Printf("unknown\n");
287115f2bd95SEwan Crawford         else
287215f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
287315f2bd95SEwan Crawford 
287415f2bd95SEwan Crawford         strm.Indent("Address: ");
287515f2bd95SEwan Crawford         if (!alloc->address.isValid())
287615f2bd95SEwan Crawford             strm.Printf("unknown\n");
287715f2bd95SEwan Crawford         else
287815f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
287915f2bd95SEwan Crawford 
288015f2bd95SEwan Crawford         strm.Indent("Data pointer: ");
288115f2bd95SEwan Crawford         if (!alloc->data_ptr.isValid())
288215f2bd95SEwan Crawford             strm.Printf("unknown\n");
288315f2bd95SEwan Crawford         else
288415f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
288515f2bd95SEwan Crawford 
288615f2bd95SEwan Crawford         strm.Indent("Dimensions: ");
288715f2bd95SEwan Crawford         if (!alloc->dimension.isValid())
288815f2bd95SEwan Crawford             strm.Printf("unknown\n");
288915f2bd95SEwan Crawford         else
289015f2bd95SEwan Crawford             strm.Printf("(%d, %d, %d)\n", alloc->dimension.get()->dim_1,
289115f2bd95SEwan Crawford                                           alloc->dimension.get()->dim_2,
289215f2bd95SEwan Crawford                                           alloc->dimension.get()->dim_3);
289315f2bd95SEwan Crawford 
289415f2bd95SEwan Crawford         strm.Indent("Data Type: ");
28958b244e21SEwan Crawford         if (!alloc->element.type.isValid() || !alloc->element.type_vec_size.isValid())
289615f2bd95SEwan Crawford             strm.Printf("unknown\n");
289715f2bd95SEwan Crawford         else
289815f2bd95SEwan Crawford         {
28998b244e21SEwan Crawford             const int vector_size = *alloc->element.type_vec_size.get();
29002e920715SEwan Crawford             Element::DataType type = *alloc->element.type.get();
290115f2bd95SEwan Crawford 
29028b244e21SEwan Crawford             if (!alloc->element.type_name.IsEmpty())
29038b244e21SEwan Crawford                 strm.Printf("%s\n", alloc->element.type_name.AsCString());
29042e920715SEwan Crawford             else
29052e920715SEwan Crawford             {
29062e920715SEwan Crawford                 // Enum value isn't monotonous, so doesn't always index RsDataTypeToString array
29072e920715SEwan Crawford                 if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
29082e920715SEwan Crawford                     type = static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +  Element::RS_TYPE_MATRIX_2X2 + 1);
29092e920715SEwan Crawford 
29102e920715SEwan Crawford                 if (type >= (sizeof(AllocationDetails::RsDataTypeToString) / sizeof(AllocationDetails::RsDataTypeToString[0]))
29112e920715SEwan Crawford                     || vector_size > 4 || vector_size < 1)
291215f2bd95SEwan Crawford                     strm.Printf("invalid type\n");
291315f2bd95SEwan Crawford                 else
291415f2bd95SEwan Crawford                     strm.Printf("%s\n", AllocationDetails::RsDataTypeToString[static_cast<unsigned int>(type)][vector_size-1]);
291515f2bd95SEwan Crawford             }
29162e920715SEwan Crawford         }
291715f2bd95SEwan Crawford 
291815f2bd95SEwan Crawford         strm.Indent("Data Kind: ");
29198b244e21SEwan Crawford         if (!alloc->element.type_kind.isValid())
292015f2bd95SEwan Crawford             strm.Printf("unknown\n");
292115f2bd95SEwan Crawford         else
292215f2bd95SEwan Crawford         {
29238b244e21SEwan Crawford             const Element::DataKind kind = *alloc->element.type_kind.get();
29248b244e21SEwan Crawford             if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
292515f2bd95SEwan Crawford                 strm.Printf("invalid kind\n");
292615f2bd95SEwan Crawford             else
292715f2bd95SEwan Crawford                 strm.Printf("%s\n", AllocationDetails::RsDataKindToString[static_cast<unsigned int>(kind)]);
292815f2bd95SEwan Crawford         }
292915f2bd95SEwan Crawford 
293015f2bd95SEwan Crawford         strm.EOL();
293115f2bd95SEwan Crawford         strm.IndentLess();
293215f2bd95SEwan Crawford     }
293315f2bd95SEwan Crawford     strm.IndentLess();
293415f2bd95SEwan Crawford }
293515f2bd95SEwan Crawford 
29367dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
29377dc7771cSEwan Crawford void
29387dc7771cSEwan Crawford RenderScriptRuntime::BreakOnModuleKernels(const RSModuleDescriptorSP rsmodule_sp)
29397dc7771cSEwan Crawford {
29407dc7771cSEwan Crawford     for (const auto &kernel : rsmodule_sp->m_kernels)
29417dc7771cSEwan Crawford     {
29427dc7771cSEwan Crawford         // Don't set breakpoint on 'root' kernel
29437dc7771cSEwan Crawford         if (strcmp(kernel.m_name.AsCString(), "root") == 0)
29447dc7771cSEwan Crawford             continue;
29457dc7771cSEwan Crawford 
29467dc7771cSEwan Crawford         CreateKernelBreakpoint(kernel.m_name);
29477dc7771cSEwan Crawford     }
29487dc7771cSEwan Crawford }
29497dc7771cSEwan Crawford 
29507dc7771cSEwan Crawford // Method is internally called by the 'kernel breakpoint all' command to
29517dc7771cSEwan Crawford // enable or disable breaking on all kernels.
29527dc7771cSEwan Crawford //
29537dc7771cSEwan Crawford // When do_break is true we want to enable this functionality.
29547dc7771cSEwan Crawford // When do_break is false we want to disable it.
29557dc7771cSEwan Crawford void
29567dc7771cSEwan Crawford RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target)
29577dc7771cSEwan Crawford {
295854782db7SEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
29597dc7771cSEwan Crawford 
29607dc7771cSEwan Crawford     InitSearchFilter(target);
29617dc7771cSEwan Crawford 
29627dc7771cSEwan Crawford     // Set breakpoints on all the kernels
29637dc7771cSEwan Crawford     if (do_break && !m_breakAllKernels)
29647dc7771cSEwan Crawford     {
29657dc7771cSEwan Crawford         m_breakAllKernels = true;
29667dc7771cSEwan Crawford 
29677dc7771cSEwan Crawford         for (const auto &module : m_rsmodules)
29687dc7771cSEwan Crawford             BreakOnModuleKernels(module);
29697dc7771cSEwan Crawford 
29707dc7771cSEwan Crawford         if (log)
29717dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::SetBreakAllKernels(True)"
29727dc7771cSEwan Crawford                         "- breakpoints set on all currently loaded kernels");
29737dc7771cSEwan Crawford     }
29747dc7771cSEwan Crawford     else if (!do_break && m_breakAllKernels) // Breakpoints won't be set on any new kernels.
29757dc7771cSEwan Crawford     {
29767dc7771cSEwan Crawford         m_breakAllKernels = false;
29777dc7771cSEwan Crawford 
29787dc7771cSEwan Crawford         if (log)
29797dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::SetBreakAllKernels(False) - breakpoints no longer automatically set");
29807dc7771cSEwan Crawford     }
29817dc7771cSEwan Crawford }
29827dc7771cSEwan Crawford 
29837dc7771cSEwan Crawford // Given the name of a kernel this function creates a breakpoint using our
29847dc7771cSEwan Crawford // own breakpoint resolver, and returns the Breakpoint shared pointer.
29857dc7771cSEwan Crawford BreakpointSP
29867dc7771cSEwan Crawford RenderScriptRuntime::CreateKernelBreakpoint(const ConstString& name)
29877dc7771cSEwan Crawford {
298854782db7SEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
29897dc7771cSEwan Crawford 
29907dc7771cSEwan Crawford     if (!m_filtersp)
29917dc7771cSEwan Crawford     {
29927dc7771cSEwan Crawford         if (log)
29937dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::CreateKernelBreakpoint - Error: No breakpoint search filter set");
29947dc7771cSEwan Crawford         return nullptr;
29957dc7771cSEwan Crawford     }
29967dc7771cSEwan Crawford 
29977dc7771cSEwan Crawford     BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
29987dc7771cSEwan Crawford     BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(m_filtersp, resolver_sp, false, false, false);
29997dc7771cSEwan Crawford 
300054782db7SEwan Crawford     // Give RS breakpoints a specific name, so the user can manipulate them as a group.
300154782db7SEwan Crawford     Error err;
300254782db7SEwan Crawford     if (!bp->AddName("RenderScriptKernel", err) && log)
300354782db7SEwan Crawford         log->Printf("RenderScriptRuntime::CreateKernelBreakpoint: Error setting break name, %s", err.AsCString());
300454782db7SEwan Crawford 
30057dc7771cSEwan Crawford     return bp;
30067dc7771cSEwan Crawford }
30077dc7771cSEwan Crawford 
3008018f5a7eSEwan Crawford // Given an expression for a variable this function tries to calculate the variable's value.
3009018f5a7eSEwan Crawford // If this is possible it returns true and sets the uint64_t parameter to the variables unsigned value.
3010018f5a7eSEwan Crawford // Otherwise function returns false.
3011018f5a7eSEwan Crawford bool
3012018f5a7eSEwan Crawford RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp, const char* var_name, uint64_t& val)
3013018f5a7eSEwan Crawford {
3014018f5a7eSEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3015018f5a7eSEwan Crawford     Error error;
3016018f5a7eSEwan Crawford     VariableSP var_sp;
3017018f5a7eSEwan Crawford 
3018018f5a7eSEwan Crawford     // Find variable in stack frame
3019018f5a7eSEwan Crawford     ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(var_name,
3020018f5a7eSEwan Crawford                                                                        eNoDynamicValues,
3021018f5a7eSEwan Crawford                                                                        StackFrame::eExpressionPathOptionCheckPtrVsMember |
3022018f5a7eSEwan Crawford                                                                        StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3023018f5a7eSEwan Crawford                                                                        var_sp,
3024018f5a7eSEwan Crawford                                                                        error));
3025018f5a7eSEwan Crawford     if (!error.Success())
3026018f5a7eSEwan Crawford     {
3027018f5a7eSEwan Crawford         if (log)
3028018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't find '%s' in frame", var_name);
3029018f5a7eSEwan Crawford 
3030018f5a7eSEwan Crawford         return false;
3031018f5a7eSEwan Crawford     }
3032018f5a7eSEwan Crawford 
3033018f5a7eSEwan Crawford     // Find the unsigned int value for the variable
3034018f5a7eSEwan Crawford     bool success = false;
3035018f5a7eSEwan Crawford     val = value_sp->GetValueAsUnsigned(0, &success);
3036018f5a7eSEwan Crawford     if (!success)
3037018f5a7eSEwan Crawford     {
3038018f5a7eSEwan Crawford         if (log)
3039018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't parse '%s' as an unsigned int", var_name);
3040018f5a7eSEwan Crawford 
3041018f5a7eSEwan Crawford         return false;
3042018f5a7eSEwan Crawford     }
3043018f5a7eSEwan Crawford 
3044018f5a7eSEwan Crawford     return true;
3045018f5a7eSEwan Crawford }
3046018f5a7eSEwan Crawford 
3047018f5a7eSEwan Crawford // Callback when a kernel breakpoint hits and we're looking for a specific coordinate.
3048018f5a7eSEwan Crawford // Baton parameter contains a pointer to the target coordinate we want to break on.
3049018f5a7eSEwan Crawford // Function then checks the .expand frame for the current coordinate and breaks to user if it matches.
3050018f5a7eSEwan Crawford // Parameter 'break_id' is the id of the Breakpoint which made the callback.
3051018f5a7eSEwan Crawford // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
3052018f5a7eSEwan Crawford // a single logical breakpoint can have multiple addresses.
3053018f5a7eSEwan Crawford bool
3054018f5a7eSEwan Crawford RenderScriptRuntime::KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx,
3055018f5a7eSEwan Crawford                                          user_id_t break_id, user_id_t break_loc_id)
3056018f5a7eSEwan Crawford {
3057018f5a7eSEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3058018f5a7eSEwan Crawford 
3059018f5a7eSEwan Crawford     assert(baton && "Error: null baton in conditional kernel breakpoint callback");
3060018f5a7eSEwan Crawford 
3061018f5a7eSEwan Crawford     // Coordinate we want to stop on
3062018f5a7eSEwan Crawford     const int* target_coord = static_cast<const int*>(baton);
3063018f5a7eSEwan Crawford 
3064018f5a7eSEwan Crawford     if (log)
3065018f5a7eSEwan Crawford         log->Printf("RenderScriptRuntime::KernelBreakpointHit - Break ID %" PRIu64 ", target coord (%d, %d, %d)",
3066018f5a7eSEwan Crawford                     break_id, target_coord[0], target_coord[1], target_coord[2]);
3067018f5a7eSEwan Crawford 
3068018f5a7eSEwan Crawford     // Go up one stack frame to .expand kernel
3069018f5a7eSEwan Crawford     ExecutionContext context(ctx->exe_ctx_ref);
3070018f5a7eSEwan Crawford     ThreadSP thread_sp = context.GetThreadSP();
3071018f5a7eSEwan Crawford     if (!thread_sp->SetSelectedFrameByIndex(1))
3072018f5a7eSEwan Crawford     {
3073018f5a7eSEwan Crawford         if (log)
3074018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't go up stack frame");
3075018f5a7eSEwan Crawford 
3076018f5a7eSEwan Crawford        return false;
3077018f5a7eSEwan Crawford     }
3078018f5a7eSEwan Crawford 
3079018f5a7eSEwan Crawford     StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
3080018f5a7eSEwan Crawford     if (!frame_sp)
3081018f5a7eSEwan Crawford     {
3082018f5a7eSEwan Crawford         if (log)
3083018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't select .expand stack frame");
3084018f5a7eSEwan Crawford 
3085018f5a7eSEwan Crawford         return false;
3086018f5a7eSEwan Crawford     }
3087018f5a7eSEwan Crawford 
3088018f5a7eSEwan Crawford     // Get values for variables in .expand frame that tell us the current kernel invocation
3089018f5a7eSEwan Crawford     const char* coord_expressions[] = {"rsIndex", "p->current.y", "p->current.z"};
3090018f5a7eSEwan Crawford     uint64_t current_coord[3] = {0, 0, 0};
3091018f5a7eSEwan Crawford 
3092018f5a7eSEwan Crawford     for(int i = 0; i < 3; ++i)
3093018f5a7eSEwan Crawford     {
3094018f5a7eSEwan Crawford         if (!GetFrameVarAsUnsigned(frame_sp, coord_expressions[i], current_coord[i]))
3095018f5a7eSEwan Crawford             return false;
3096018f5a7eSEwan Crawford 
3097018f5a7eSEwan Crawford         if (log)
3098018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit, %s = %" PRIu64, coord_expressions[i], current_coord[i]);
3099018f5a7eSEwan Crawford     }
3100018f5a7eSEwan Crawford 
3101018f5a7eSEwan Crawford     // Check if the current kernel invocation coordinate matches our target coordinate
3102018f5a7eSEwan Crawford     if (current_coord[0] == static_cast<uint64_t>(target_coord[0]) &&
3103018f5a7eSEwan Crawford         current_coord[1] == static_cast<uint64_t>(target_coord[1]) &&
3104018f5a7eSEwan Crawford         current_coord[2] == static_cast<uint64_t>(target_coord[2]))
3105018f5a7eSEwan Crawford     {
3106018f5a7eSEwan Crawford         if (log)
3107018f5a7eSEwan Crawford              log->Printf("RenderScriptRuntime::KernelBreakpointHit, BREAKING %" PRIu64 ", %" PRIu64 ", %" PRIu64,
3108018f5a7eSEwan Crawford                          current_coord[0], current_coord[1], current_coord[2]);
3109018f5a7eSEwan Crawford 
3110018f5a7eSEwan Crawford         BreakpointSP breakpoint_sp = context.GetTargetPtr()->GetBreakpointByID(break_id);
3111018f5a7eSEwan Crawford         assert(breakpoint_sp != nullptr && "Error: Couldn't find breakpoint matching break id for callback");
3112018f5a7eSEwan Crawford         breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint should only be hit once.
3113018f5a7eSEwan Crawford         return true;
3114018f5a7eSEwan Crawford     }
3115018f5a7eSEwan Crawford 
3116018f5a7eSEwan Crawford     // No match on coordinate
3117018f5a7eSEwan Crawford     return false;
3118018f5a7eSEwan Crawford }
3119018f5a7eSEwan Crawford 
3120018f5a7eSEwan Crawford // Tries to set a breakpoint on the start of a kernel, resolved using the kernel name.
3121018f5a7eSEwan Crawford // Argument 'coords', represents a three dimensional coordinate which can be used to specify
3122018f5a7eSEwan Crawford // a single kernel instance to break on. If this is set then we add a callback to the breakpoint.
31234640cde1SColin Riley void
3124018f5a7eSEwan Crawford RenderScriptRuntime::PlaceBreakpointOnKernel(Stream &strm, const char* name, const std::array<int,3> coords,
3125018f5a7eSEwan Crawford                                              Error& error, TargetSP target)
31264640cde1SColin Riley {
31274640cde1SColin Riley     if (!name)
31284640cde1SColin Riley     {
31294640cde1SColin Riley         error.SetErrorString("invalid kernel name");
31304640cde1SColin Riley         return;
31314640cde1SColin Riley     }
31324640cde1SColin Riley 
31337dc7771cSEwan Crawford     InitSearchFilter(target);
313498156583SEwan Crawford 
31354640cde1SColin Riley     ConstString kernel_name(name);
31367dc7771cSEwan Crawford     BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
3137018f5a7eSEwan Crawford 
3138018f5a7eSEwan Crawford     // We have a conditional breakpoint on a specific coordinate
3139018f5a7eSEwan Crawford     if (coords[0] != -1)
3140018f5a7eSEwan Crawford     {
3141018f5a7eSEwan Crawford         strm.Printf("Conditional kernel breakpoint on coordinate %d, %d, %d", coords[0], coords[1], coords[2]);
3142018f5a7eSEwan Crawford         strm.EOL();
3143018f5a7eSEwan Crawford 
3144018f5a7eSEwan Crawford         // Allocate memory for the baton, and copy over coordinate
3145018f5a7eSEwan Crawford         int* baton = new int[3];
3146018f5a7eSEwan Crawford         baton[0] = coords[0]; baton[1] = coords[1]; baton[2] = coords[2];
3147018f5a7eSEwan Crawford 
3148018f5a7eSEwan Crawford         // Create a callback that will be invoked everytime the breakpoint is hit.
3149018f5a7eSEwan Crawford         // The baton object passed to the handler is the target coordinate we want to break on.
3150018f5a7eSEwan Crawford         bp->SetCallback(KernelBreakpointHit, baton, true);
3151018f5a7eSEwan Crawford 
3152018f5a7eSEwan Crawford         // Store a shared pointer to the baton, so the memory will eventually be cleaned up after destruction
3153018f5a7eSEwan Crawford         m_conditional_breaks[bp->GetID()] = std::shared_ptr<int>(baton);
3154018f5a7eSEwan Crawford     }
3155018f5a7eSEwan Crawford 
315698156583SEwan Crawford     if (bp)
315798156583SEwan Crawford         bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
31584640cde1SColin Riley }
31594640cde1SColin Riley 
31604640cde1SColin Riley void
31615ec532a9SColin Riley RenderScriptRuntime::DumpModules(Stream &strm) const
31625ec532a9SColin Riley {
31635ec532a9SColin Riley     strm.Printf("RenderScript Modules:");
31645ec532a9SColin Riley     strm.EOL();
31655ec532a9SColin Riley     strm.IndentMore();
31665ec532a9SColin Riley     for (const auto &module : m_rsmodules)
31675ec532a9SColin Riley     {
31684640cde1SColin Riley         module->Dump(strm);
31695ec532a9SColin Riley     }
31705ec532a9SColin Riley     strm.IndentLess();
31715ec532a9SColin Riley }
31725ec532a9SColin Riley 
317378f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails*
317478f339d1SEwan Crawford RenderScriptRuntime::LookUpScript(addr_t address, bool create)
317578f339d1SEwan Crawford {
317678f339d1SEwan Crawford     for (const auto & s : m_scripts)
317778f339d1SEwan Crawford     {
317878f339d1SEwan Crawford         if (s->script.isValid())
317978f339d1SEwan Crawford             if (*s->script == address)
318078f339d1SEwan Crawford                 return s.get();
318178f339d1SEwan Crawford     }
318278f339d1SEwan Crawford     if (create)
318378f339d1SEwan Crawford     {
318478f339d1SEwan Crawford         std::unique_ptr<ScriptDetails> s(new ScriptDetails);
318578f339d1SEwan Crawford         s->script = address;
318678f339d1SEwan Crawford         m_scripts.push_back(std::move(s));
3187d10ca9deSEwan Crawford         return m_scripts.back().get();
318878f339d1SEwan Crawford     }
318978f339d1SEwan Crawford     return nullptr;
319078f339d1SEwan Crawford }
319178f339d1SEwan Crawford 
319278f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails*
319378f339d1SEwan Crawford RenderScriptRuntime::LookUpAllocation(addr_t address, bool create)
319478f339d1SEwan Crawford {
319578f339d1SEwan Crawford     for (const auto & a : m_allocations)
319678f339d1SEwan Crawford     {
319778f339d1SEwan Crawford         if (a->address.isValid())
319878f339d1SEwan Crawford             if (*a->address == address)
319978f339d1SEwan Crawford                 return a.get();
320078f339d1SEwan Crawford     }
320178f339d1SEwan Crawford     if (create)
320278f339d1SEwan Crawford     {
320378f339d1SEwan Crawford         std::unique_ptr<AllocationDetails> a(new AllocationDetails);
320478f339d1SEwan Crawford         a->address = address;
320578f339d1SEwan Crawford         m_allocations.push_back(std::move(a));
3206d10ca9deSEwan Crawford         return m_allocations.back().get();
320778f339d1SEwan Crawford     }
320878f339d1SEwan Crawford     return nullptr;
320978f339d1SEwan Crawford }
321078f339d1SEwan Crawford 
32115ec532a9SColin Riley void
32125ec532a9SColin Riley RSModuleDescriptor::Dump(Stream &strm) const
32135ec532a9SColin Riley {
32145ec532a9SColin Riley     strm.Indent();
32155ec532a9SColin Riley     m_module->GetFileSpec().Dump(&strm);
32164640cde1SColin Riley     if(m_module->GetNumCompileUnits())
32174640cde1SColin Riley     {
32184640cde1SColin Riley         strm.Indent("Debug info loaded.");
32194640cde1SColin Riley     }
32204640cde1SColin Riley     else
32214640cde1SColin Riley     {
32224640cde1SColin Riley         strm.Indent("Debug info does not exist.");
32234640cde1SColin Riley     }
32245ec532a9SColin Riley     strm.EOL();
32255ec532a9SColin Riley     strm.IndentMore();
32265ec532a9SColin Riley     strm.Indent();
3227189598edSColin Riley     strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
32285ec532a9SColin Riley     strm.EOL();
32295ec532a9SColin Riley     strm.IndentMore();
32305ec532a9SColin Riley     for (const auto &global : m_globals)
32315ec532a9SColin Riley     {
32325ec532a9SColin Riley         global.Dump(strm);
32335ec532a9SColin Riley     }
32345ec532a9SColin Riley     strm.IndentLess();
32355ec532a9SColin Riley     strm.Indent();
3236189598edSColin Riley     strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
32375ec532a9SColin Riley     strm.EOL();
32385ec532a9SColin Riley     strm.IndentMore();
32395ec532a9SColin Riley     for (const auto &kernel : m_kernels)
32405ec532a9SColin Riley     {
32415ec532a9SColin Riley         kernel.Dump(strm);
32425ec532a9SColin Riley     }
32434640cde1SColin Riley     strm.Printf("Pragmas: %"  PRIu64 , static_cast<uint64_t>(m_pragmas.size()));
32444640cde1SColin Riley     strm.EOL();
32454640cde1SColin Riley     strm.IndentMore();
32464640cde1SColin Riley     for (const auto &key_val : m_pragmas)
32474640cde1SColin Riley     {
32484640cde1SColin Riley         strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
32494640cde1SColin Riley         strm.EOL();
32504640cde1SColin Riley     }
32515ec532a9SColin Riley     strm.IndentLess(4);
32525ec532a9SColin Riley }
32535ec532a9SColin Riley 
32545ec532a9SColin Riley void
32555ec532a9SColin Riley RSGlobalDescriptor::Dump(Stream &strm) const
32565ec532a9SColin Riley {
32575ec532a9SColin Riley     strm.Indent(m_name.AsCString());
32584640cde1SColin Riley     VariableList var_list;
32594640cde1SColin Riley     m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
32604640cde1SColin Riley     if (var_list.GetSize() == 1)
32614640cde1SColin Riley     {
32624640cde1SColin Riley         auto var = var_list.GetVariableAtIndex(0);
32634640cde1SColin Riley         auto type = var->GetType();
32644640cde1SColin Riley         if(type)
32654640cde1SColin Riley         {
32664640cde1SColin Riley             strm.Printf(" - ");
32674640cde1SColin Riley             type->DumpTypeName(&strm);
32684640cde1SColin Riley         }
32694640cde1SColin Riley         else
32704640cde1SColin Riley         {
32714640cde1SColin Riley             strm.Printf(" - Unknown Type");
32724640cde1SColin Riley         }
32734640cde1SColin Riley     }
32744640cde1SColin Riley     else
32754640cde1SColin Riley     {
32764640cde1SColin Riley         strm.Printf(" - variable identified, but not found in binary");
32774640cde1SColin Riley         const Symbol* s = m_module->m_module->FindFirstSymbolWithNameAndType(m_name, eSymbolTypeData);
32784640cde1SColin Riley         if (s)
32794640cde1SColin Riley         {
32804640cde1SColin Riley             strm.Printf(" (symbol exists) ");
32814640cde1SColin Riley         }
32824640cde1SColin Riley     }
32834640cde1SColin Riley 
32845ec532a9SColin Riley     strm.EOL();
32855ec532a9SColin Riley }
32865ec532a9SColin Riley 
32875ec532a9SColin Riley void
32885ec532a9SColin Riley RSKernelDescriptor::Dump(Stream &strm) const
32895ec532a9SColin Riley {
32905ec532a9SColin Riley     strm.Indent(m_name.AsCString());
32915ec532a9SColin Riley     strm.EOL();
32925ec532a9SColin Riley }
32935ec532a9SColin Riley 
32945ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleProbe : public CommandObjectParsed
32955ec532a9SColin Riley {
32965ec532a9SColin Riley public:
32975ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleProbe(CommandInterpreter &interpreter)
32985ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module probe",
32995ec532a9SColin Riley                               "Initiates a Probe of all loaded modules for kernels and other renderscript objects.",
33005ec532a9SColin Riley                               "renderscript module probe",
3301e87764f2SEnrico Granata                               eCommandRequiresTarget | eCommandRequiresProcess | eCommandProcessMustBeLaunched)
33025ec532a9SColin Riley     {
33035ec532a9SColin Riley     }
33045ec532a9SColin Riley 
3305222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModuleProbe() override = default;
33065ec532a9SColin Riley 
33075ec532a9SColin Riley     bool
3308222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
33095ec532a9SColin Riley     {
33105ec532a9SColin Riley         const size_t argc = command.GetArgumentCount();
33115ec532a9SColin Riley         if (argc == 0)
33125ec532a9SColin Riley         {
33135ec532a9SColin Riley             Target *target = m_exe_ctx.GetTargetPtr();
33145ec532a9SColin Riley             RenderScriptRuntime *runtime =
33155ec532a9SColin Riley                 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
33165ec532a9SColin Riley             auto module_list = target->GetImages();
33175ec532a9SColin Riley             bool new_rs_details = runtime->ProbeModules(module_list);
33185ec532a9SColin Riley             if (new_rs_details)
33195ec532a9SColin Riley             {
33205ec532a9SColin Riley                 result.AppendMessage("New renderscript modules added to runtime model.");
33215ec532a9SColin Riley             }
33225ec532a9SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
33235ec532a9SColin Riley             return true;
33245ec532a9SColin Riley         }
33255ec532a9SColin Riley 
33265ec532a9SColin Riley         result.AppendErrorWithFormat("'%s' takes no arguments", m_cmd_name.c_str());
33275ec532a9SColin Riley         result.SetStatus(eReturnStatusFailed);
33285ec532a9SColin Riley         return false;
33295ec532a9SColin Riley     }
33305ec532a9SColin Riley };
33315ec532a9SColin Riley 
33325ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed
33335ec532a9SColin Riley {
33345ec532a9SColin Riley public:
33355ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
33365ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module dump",
33375ec532a9SColin Riley                               "Dumps renderscript specific information for all modules.", "renderscript module dump",
3338e87764f2SEnrico Granata                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
33395ec532a9SColin Riley     {
33405ec532a9SColin Riley     }
33415ec532a9SColin Riley 
3342222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
33435ec532a9SColin Riley 
33445ec532a9SColin Riley     bool
3345222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
33465ec532a9SColin Riley     {
33475ec532a9SColin Riley         RenderScriptRuntime *runtime =
33485ec532a9SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
33495ec532a9SColin Riley         runtime->DumpModules(result.GetOutputStream());
33505ec532a9SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
33515ec532a9SColin Riley         return true;
33525ec532a9SColin Riley     }
33535ec532a9SColin Riley };
33545ec532a9SColin Riley 
33555ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword
33565ec532a9SColin Riley {
33575ec532a9SColin Riley public:
33585ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
33595ec532a9SColin Riley         : CommandObjectMultiword(interpreter, "renderscript module", "Commands that deal with renderscript modules.",
33605ec532a9SColin Riley                                  NULL)
33615ec532a9SColin Riley     {
33625ec532a9SColin Riley         LoadSubCommand("probe", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleProbe(interpreter)));
33635ec532a9SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(interpreter)));
33645ec532a9SColin Riley     }
33655ec532a9SColin Riley 
3366222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModule() override = default;
33675ec532a9SColin Riley };
33685ec532a9SColin Riley 
33694640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed
33704640cde1SColin Riley {
33714640cde1SColin Riley public:
33724640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
33734640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript kernel list",
33744640cde1SColin Riley                               "Lists renderscript kernel names and associated script resources.", "renderscript kernel list",
33754640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
33764640cde1SColin Riley     {
33774640cde1SColin Riley     }
33784640cde1SColin Riley 
3379222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelList() override = default;
33804640cde1SColin Riley 
33814640cde1SColin Riley     bool
3382222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
33834640cde1SColin Riley     {
33844640cde1SColin Riley         RenderScriptRuntime *runtime =
33854640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
33864640cde1SColin Riley         runtime->DumpKernels(result.GetOutputStream());
33874640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
33884640cde1SColin Riley         return true;
33894640cde1SColin Riley     }
33904640cde1SColin Riley };
33914640cde1SColin Riley 
33927dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointSet : public CommandObjectParsed
33934640cde1SColin Riley {
33944640cde1SColin Riley public:
33957dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointSet(CommandInterpreter &interpreter)
33967dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint set",
3397018f5a7eSEwan Crawford                               "Sets a breakpoint on a renderscript kernel.", "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
3398018f5a7eSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), m_options(interpreter)
33994640cde1SColin Riley     {
34004640cde1SColin Riley     }
34014640cde1SColin Riley 
3402222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
3403222b937cSEugene Zelenko 
3404222b937cSEugene Zelenko     Options*
3405222b937cSEugene Zelenko     GetOptions() override
3406018f5a7eSEwan Crawford     {
3407018f5a7eSEwan Crawford         return &m_options;
3408018f5a7eSEwan Crawford     }
3409018f5a7eSEwan Crawford 
3410018f5a7eSEwan Crawford     class CommandOptions : public Options
3411018f5a7eSEwan Crawford     {
3412018f5a7eSEwan Crawford     public:
3413018f5a7eSEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter)
3414018f5a7eSEwan Crawford         {
3415018f5a7eSEwan Crawford         }
3416018f5a7eSEwan Crawford 
3417222b937cSEugene Zelenko         ~CommandOptions() override = default;
3418018f5a7eSEwan Crawford 
3419222b937cSEugene Zelenko         Error
3420222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
3421018f5a7eSEwan Crawford         {
3422018f5a7eSEwan Crawford             Error error;
3423018f5a7eSEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
3424018f5a7eSEwan Crawford 
3425018f5a7eSEwan Crawford             switch (short_option)
3426018f5a7eSEwan Crawford             {
3427018f5a7eSEwan Crawford                 case 'c':
3428018f5a7eSEwan Crawford                     if (!ParseCoordinate(option_arg))
3429018f5a7eSEwan Crawford                         error.SetErrorStringWithFormat("Couldn't parse coordinate '%s', should be in format 'x,y,z'.", option_arg);
3430018f5a7eSEwan Crawford                     break;
3431018f5a7eSEwan Crawford                 default:
3432018f5a7eSEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3433018f5a7eSEwan Crawford                     break;
3434018f5a7eSEwan Crawford             }
3435018f5a7eSEwan Crawford             return error;
3436018f5a7eSEwan Crawford         }
3437018f5a7eSEwan Crawford 
3438018f5a7eSEwan Crawford         // -c takes an argument of the form 'num[,num][,num]'.
3439018f5a7eSEwan Crawford         // Where 'id_cstr' is this argument with the whitespace trimmed.
3440018f5a7eSEwan Crawford         // Missing coordinates are defaulted to zero.
3441018f5a7eSEwan Crawford         bool
3442018f5a7eSEwan Crawford         ParseCoordinate(const char* id_cstr)
3443018f5a7eSEwan Crawford         {
3444018f5a7eSEwan Crawford             RegularExpression regex;
3445018f5a7eSEwan Crawford             RegularExpression::Match regex_match(3);
3446018f5a7eSEwan Crawford 
3447018f5a7eSEwan Crawford             bool matched = false;
3448018f5a7eSEwan Crawford             if(regex.Compile("^([0-9]+),([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3449018f5a7eSEwan Crawford                 matched = true;
3450018f5a7eSEwan Crawford             else if(regex.Compile("^([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3451018f5a7eSEwan Crawford                 matched = true;
3452018f5a7eSEwan Crawford             else if(regex.Compile("^([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3453018f5a7eSEwan Crawford                 matched = true;
3454018f5a7eSEwan Crawford             for(uint32_t i = 0; i < 3; i++)
3455018f5a7eSEwan Crawford             {
3456018f5a7eSEwan Crawford                 std::string group;
3457018f5a7eSEwan Crawford                 if(regex_match.GetMatchAtIndex(id_cstr, i + 1, group))
3458018f5a7eSEwan Crawford                     m_coord[i] = (uint32_t)strtoul(group.c_str(), NULL, 0);
3459018f5a7eSEwan Crawford                 else
3460018f5a7eSEwan Crawford                     m_coord[i] = 0;
3461018f5a7eSEwan Crawford             }
3462018f5a7eSEwan Crawford             return matched;
3463018f5a7eSEwan Crawford         }
3464018f5a7eSEwan Crawford 
3465018f5a7eSEwan Crawford         void
3466222b937cSEugene Zelenko         OptionParsingStarting() override
3467018f5a7eSEwan Crawford         {
3468018f5a7eSEwan Crawford             // -1 means the -c option hasn't been set
3469018f5a7eSEwan Crawford             m_coord[0] = -1;
3470018f5a7eSEwan Crawford             m_coord[1] = -1;
3471018f5a7eSEwan Crawford             m_coord[2] = -1;
3472018f5a7eSEwan Crawford         }
3473018f5a7eSEwan Crawford 
3474018f5a7eSEwan Crawford         const OptionDefinition*
3475222b937cSEugene Zelenko         GetDefinitions() override
3476018f5a7eSEwan Crawford         {
3477018f5a7eSEwan Crawford             return g_option_table;
3478018f5a7eSEwan Crawford         }
3479018f5a7eSEwan Crawford 
3480018f5a7eSEwan Crawford         static OptionDefinition g_option_table[];
3481018f5a7eSEwan Crawford         std::array<int,3> m_coord;
3482018f5a7eSEwan Crawford     };
3483018f5a7eSEwan Crawford 
34844640cde1SColin Riley     bool
3485222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
34864640cde1SColin Riley     {
34874640cde1SColin Riley         const size_t argc = command.GetArgumentCount();
3488018f5a7eSEwan Crawford         if (argc < 1)
34894640cde1SColin Riley         {
3490018f5a7eSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of kernel name, and an optional coordinate.", m_cmd_name.c_str());
3491018f5a7eSEwan Crawford             result.SetStatus(eReturnStatusFailed);
3492018f5a7eSEwan Crawford             return false;
3493018f5a7eSEwan Crawford         }
3494018f5a7eSEwan Crawford 
34954640cde1SColin Riley         RenderScriptRuntime *runtime =
34964640cde1SColin Riley                 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
34974640cde1SColin Riley 
34984640cde1SColin Riley         Error error;
3499018f5a7eSEwan Crawford         runtime->PlaceBreakpointOnKernel(result.GetOutputStream(), command.GetArgumentAtIndex(0), m_options.m_coord,
350098156583SEwan Crawford                                          error, m_exe_ctx.GetTargetSP());
35014640cde1SColin Riley 
35024640cde1SColin Riley         if (error.Success())
35034640cde1SColin Riley         {
35044640cde1SColin Riley             result.AppendMessage("Breakpoint(s) created");
35054640cde1SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
35064640cde1SColin Riley             return true;
35074640cde1SColin Riley         }
35084640cde1SColin Riley         result.SetStatus(eReturnStatusFailed);
35094640cde1SColin Riley         result.AppendErrorWithFormat("Error: %s", error.AsCString());
35104640cde1SColin Riley         return false;
35114640cde1SColin Riley     }
35124640cde1SColin Riley 
3513018f5a7eSEwan Crawford private:
3514018f5a7eSEwan Crawford     CommandOptions m_options;
35154640cde1SColin Riley };
35164640cde1SColin Riley 
3517018f5a7eSEwan Crawford OptionDefinition
3518018f5a7eSEwan Crawford CommandObjectRenderScriptRuntimeKernelBreakpointSet::CommandOptions::g_option_table[] =
3519018f5a7eSEwan Crawford {
3520018f5a7eSEwan Crawford     { LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeValue,
3521018f5a7eSEwan Crawford       "Set a breakpoint on a single invocation of the kernel with specified coordinate.\n"
3522018f5a7eSEwan Crawford       "Coordinate takes the form 'x[,y][,z] where x,y,z are positive integers representing kernel dimensions. "
3523018f5a7eSEwan Crawford       "Any unset dimensions will be defaulted to zero."},
3524018f5a7eSEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
3525018f5a7eSEwan Crawford };
3526018f5a7eSEwan Crawford 
35277dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointAll : public CommandObjectParsed
35287dc7771cSEwan Crawford {
35297dc7771cSEwan Crawford public:
35307dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointAll(CommandInterpreter &interpreter)
35317dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint all",
35327dc7771cSEwan Crawford                               "Automatically sets a breakpoint on all renderscript kernels that are or will be loaded.\n"
35337dc7771cSEwan Crawford                               "Disabling option means breakpoints will no longer be set on any kernels loaded in the future, "
35347dc7771cSEwan Crawford                               "but does not remove currently set breakpoints.",
35357dc7771cSEwan Crawford                               "renderscript kernel breakpoint all <enable/disable>",
35367dc7771cSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
35377dc7771cSEwan Crawford     {
35387dc7771cSEwan Crawford     }
35397dc7771cSEwan Crawford 
3540222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
35417dc7771cSEwan Crawford 
35427dc7771cSEwan Crawford     bool
3543222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
35447dc7771cSEwan Crawford     {
35457dc7771cSEwan Crawford         const size_t argc = command.GetArgumentCount();
35467dc7771cSEwan Crawford         if (argc != 1)
35477dc7771cSEwan Crawford         {
35487dc7771cSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
35497dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
35507dc7771cSEwan Crawford             return false;
35517dc7771cSEwan Crawford         }
35527dc7771cSEwan Crawford 
35537dc7771cSEwan Crawford         RenderScriptRuntime *runtime =
35547dc7771cSEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
35557dc7771cSEwan Crawford 
35567dc7771cSEwan Crawford         bool do_break = false;
35577dc7771cSEwan Crawford         const char* argument = command.GetArgumentAtIndex(0);
35587dc7771cSEwan Crawford         if (strcmp(argument, "enable") == 0)
35597dc7771cSEwan Crawford         {
35607dc7771cSEwan Crawford             do_break = true;
35617dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will be set on all kernels.");
35627dc7771cSEwan Crawford         }
35637dc7771cSEwan Crawford         else if (strcmp(argument, "disable") == 0)
35647dc7771cSEwan Crawford         {
35657dc7771cSEwan Crawford             do_break = false;
35667dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will not be set on any new kernels.");
35677dc7771cSEwan Crawford         }
35687dc7771cSEwan Crawford         else
35697dc7771cSEwan Crawford         {
35707dc7771cSEwan Crawford             result.AppendErrorWithFormat("Argument must be either 'enable' or 'disable'");
35717dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
35727dc7771cSEwan Crawford             return false;
35737dc7771cSEwan Crawford         }
35747dc7771cSEwan Crawford 
35757dc7771cSEwan Crawford         runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
35767dc7771cSEwan Crawford 
35777dc7771cSEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
35787dc7771cSEwan Crawford         return true;
35797dc7771cSEwan Crawford     }
35807dc7771cSEwan Crawford };
35817dc7771cSEwan Crawford 
35827dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpoint : public CommandObjectMultiword
35837dc7771cSEwan Crawford {
35847dc7771cSEwan Crawford public:
35857dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpoint(CommandInterpreter &interpreter)
35867dc7771cSEwan Crawford         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that generate breakpoints on renderscript kernels.",
35877dc7771cSEwan Crawford                                  nullptr)
35887dc7771cSEwan Crawford     {
35897dc7771cSEwan Crawford         LoadSubCommand("set", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(interpreter)));
35907dc7771cSEwan Crawford         LoadSubCommand("all", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(interpreter)));
35917dc7771cSEwan Crawford     }
35927dc7771cSEwan Crawford 
3593222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
35947dc7771cSEwan Crawford };
35957dc7771cSEwan Crawford 
35964640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword
35974640cde1SColin Riley {
35984640cde1SColin Riley public:
35994640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
36004640cde1SColin Riley         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that deal with renderscript kernels.",
36014640cde1SColin Riley                                  NULL)
36024640cde1SColin Riley     {
36034640cde1SColin Riley         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(interpreter)));
36044640cde1SColin Riley         LoadSubCommand("breakpoint", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
36054640cde1SColin Riley     }
36064640cde1SColin Riley 
3607222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernel() override = default;
36084640cde1SColin Riley };
36094640cde1SColin Riley 
36104640cde1SColin Riley class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed
36114640cde1SColin Riley {
36124640cde1SColin Riley public:
36134640cde1SColin Riley     CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
36144640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript context dump",
36154640cde1SColin Riley                               "Dumps renderscript context information.", "renderscript context dump",
36164640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
36174640cde1SColin Riley     {
36184640cde1SColin Riley     }
36194640cde1SColin Riley 
3620222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeContextDump() override = default;
36214640cde1SColin Riley 
36224640cde1SColin Riley     bool
3623222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
36244640cde1SColin Riley     {
36254640cde1SColin Riley         RenderScriptRuntime *runtime =
36264640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
36274640cde1SColin Riley         runtime->DumpContexts(result.GetOutputStream());
36284640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
36294640cde1SColin Riley         return true;
36304640cde1SColin Riley     }
36314640cde1SColin Riley };
36324640cde1SColin Riley 
36334640cde1SColin Riley class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword
36344640cde1SColin Riley {
36354640cde1SColin Riley public:
36364640cde1SColin Riley     CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
36374640cde1SColin Riley         : CommandObjectMultiword(interpreter, "renderscript context", "Commands that deal with renderscript contexts.",
36384640cde1SColin Riley                                  NULL)
36394640cde1SColin Riley     {
36404640cde1SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(interpreter)));
36414640cde1SColin Riley     }
36424640cde1SColin Riley 
3643222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeContext() override = default;
36444640cde1SColin Riley };
36454640cde1SColin Riley 
3646a0f08674SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationDump : public CommandObjectParsed
3647a0f08674SEwan Crawford {
3648a0f08674SEwan Crawford public:
3649a0f08674SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationDump(CommandInterpreter &interpreter)
3650a0f08674SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation dump",
3651a0f08674SEwan Crawford                               "Displays the contents of a particular allocation", "renderscript allocation dump <ID>",
3652a0f08674SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter)
3653a0f08674SEwan Crawford     {
3654a0f08674SEwan Crawford     }
3655a0f08674SEwan Crawford 
3656222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
3657222b937cSEugene Zelenko 
3658222b937cSEugene Zelenko     Options*
3659222b937cSEugene Zelenko     GetOptions() override
3660a0f08674SEwan Crawford     {
3661a0f08674SEwan Crawford         return &m_options;
3662a0f08674SEwan Crawford     }
3663a0f08674SEwan Crawford 
3664a0f08674SEwan Crawford     class CommandOptions : public Options
3665a0f08674SEwan Crawford     {
3666a0f08674SEwan Crawford     public:
3667a0f08674SEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter)
3668a0f08674SEwan Crawford         {
3669a0f08674SEwan Crawford         }
3670a0f08674SEwan Crawford 
3671222b937cSEugene Zelenko         ~CommandOptions() override = default;
3672a0f08674SEwan Crawford 
3673222b937cSEugene Zelenko         Error
3674222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
3675a0f08674SEwan Crawford         {
3676a0f08674SEwan Crawford             Error error;
3677a0f08674SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
3678a0f08674SEwan Crawford 
3679a0f08674SEwan Crawford             switch (short_option)
3680a0f08674SEwan Crawford             {
3681a0f08674SEwan Crawford                 case 'f':
3682a0f08674SEwan Crawford                     m_outfile.SetFile(option_arg, true);
3683a0f08674SEwan Crawford                     if (m_outfile.Exists())
3684a0f08674SEwan Crawford                     {
3685a0f08674SEwan Crawford                         m_outfile.Clear();
3686a0f08674SEwan Crawford                         error.SetErrorStringWithFormat("file already exists: '%s'", option_arg);
3687a0f08674SEwan Crawford                     }
3688a0f08674SEwan Crawford                     break;
3689a0f08674SEwan Crawford                 default:
3690a0f08674SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3691a0f08674SEwan Crawford                     break;
3692a0f08674SEwan Crawford             }
3693a0f08674SEwan Crawford             return error;
3694a0f08674SEwan Crawford         }
3695a0f08674SEwan Crawford 
3696a0f08674SEwan Crawford         void
3697222b937cSEugene Zelenko         OptionParsingStarting() override
3698a0f08674SEwan Crawford         {
3699a0f08674SEwan Crawford             m_outfile.Clear();
3700a0f08674SEwan Crawford         }
3701a0f08674SEwan Crawford 
3702a0f08674SEwan Crawford         const OptionDefinition*
3703222b937cSEugene Zelenko         GetDefinitions() override
3704a0f08674SEwan Crawford         {
3705a0f08674SEwan Crawford             return g_option_table;
3706a0f08674SEwan Crawford         }
3707a0f08674SEwan Crawford 
3708a0f08674SEwan Crawford         static OptionDefinition g_option_table[];
3709a0f08674SEwan Crawford         FileSpec m_outfile;
3710a0f08674SEwan Crawford     };
3711a0f08674SEwan Crawford 
3712a0f08674SEwan Crawford     bool
3713222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
3714a0f08674SEwan Crawford     {
3715a0f08674SEwan Crawford         const size_t argc = command.GetArgumentCount();
3716a0f08674SEwan Crawford         if (argc < 1)
3717a0f08674SEwan Crawford         {
3718a0f08674SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. As well as an optional -f argument",
3719a0f08674SEwan Crawford                                          m_cmd_name.c_str());
3720a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3721a0f08674SEwan Crawford             return false;
3722a0f08674SEwan Crawford         }
3723a0f08674SEwan Crawford 
3724a0f08674SEwan Crawford         RenderScriptRuntime *runtime =
3725a0f08674SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
3726a0f08674SEwan Crawford 
3727a0f08674SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
3728a0f08674SEwan Crawford         bool convert_complete = false;
3729a0f08674SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
3730a0f08674SEwan Crawford         if (!convert_complete)
3731a0f08674SEwan Crawford         {
3732a0f08674SEwan Crawford             result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
3733a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3734a0f08674SEwan Crawford             return false;
3735a0f08674SEwan Crawford         }
3736a0f08674SEwan Crawford 
3737a0f08674SEwan Crawford         Stream* output_strm = nullptr;
3738a0f08674SEwan Crawford         StreamFile outfile_stream;
3739a0f08674SEwan Crawford         const FileSpec &outfile_spec = m_options.m_outfile; // Dump allocation to file instead
3740a0f08674SEwan Crawford         if (outfile_spec)
3741a0f08674SEwan Crawford         {
3742a0f08674SEwan Crawford             // Open output file
3743a0f08674SEwan Crawford             char path[256];
3744a0f08674SEwan Crawford             outfile_spec.GetPath(path, sizeof(path));
3745a0f08674SEwan Crawford             if (outfile_stream.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate).Success())
3746a0f08674SEwan Crawford             {
3747a0f08674SEwan Crawford                 output_strm = &outfile_stream;
3748a0f08674SEwan Crawford                 result.GetOutputStream().Printf("Results written to '%s'", path);
3749a0f08674SEwan Crawford                 result.GetOutputStream().EOL();
3750a0f08674SEwan Crawford             }
3751a0f08674SEwan Crawford             else
3752a0f08674SEwan Crawford             {
3753a0f08674SEwan Crawford                 result.AppendErrorWithFormat("Couldn't open file '%s'", path);
3754a0f08674SEwan Crawford                 result.SetStatus(eReturnStatusFailed);
3755a0f08674SEwan Crawford                 return false;
3756a0f08674SEwan Crawford             }
3757a0f08674SEwan Crawford         }
3758a0f08674SEwan Crawford         else
3759a0f08674SEwan Crawford             output_strm = &result.GetOutputStream();
3760a0f08674SEwan Crawford 
3761a0f08674SEwan Crawford         assert(output_strm != nullptr);
3762a0f08674SEwan Crawford         bool success = runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
3763a0f08674SEwan Crawford 
3764a0f08674SEwan Crawford         if (success)
3765a0f08674SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
3766a0f08674SEwan Crawford         else
3767a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3768a0f08674SEwan Crawford 
3769a0f08674SEwan Crawford         return true;
3770a0f08674SEwan Crawford     }
3771a0f08674SEwan Crawford 
3772a0f08674SEwan Crawford private:
3773a0f08674SEwan Crawford     CommandOptions m_options;
3774a0f08674SEwan Crawford };
3775a0f08674SEwan Crawford 
3776a0f08674SEwan Crawford OptionDefinition
3777a0f08674SEwan Crawford CommandObjectRenderScriptRuntimeAllocationDump::CommandOptions::g_option_table[] =
3778a0f08674SEwan Crawford {
3779a0f08674SEwan Crawford     { LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename,
3780a0f08674SEwan Crawford       "Print results to specified file instead of command line."},
3781a0f08674SEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
3782a0f08674SEwan Crawford };
3783a0f08674SEwan Crawford 
378415f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationList : public CommandObjectParsed
378515f2bd95SEwan Crawford {
378615f2bd95SEwan Crawford public:
378715f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationList(CommandInterpreter &interpreter)
378815f2bd95SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation list",
378915f2bd95SEwan Crawford                               "List renderscript allocations and their information.", "renderscript allocation list",
379015f2bd95SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter)
379115f2bd95SEwan Crawford     {
379215f2bd95SEwan Crawford     }
379315f2bd95SEwan Crawford 
3794222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
3795222b937cSEugene Zelenko 
3796222b937cSEugene Zelenko     Options*
3797222b937cSEugene Zelenko     GetOptions() override
379815f2bd95SEwan Crawford     {
379915f2bd95SEwan Crawford         return &m_options;
380015f2bd95SEwan Crawford     }
380115f2bd95SEwan Crawford 
380215f2bd95SEwan Crawford     class CommandOptions : public Options
380315f2bd95SEwan Crawford     {
380415f2bd95SEwan Crawford     public:
380515f2bd95SEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter), m_refresh(false)
380615f2bd95SEwan Crawford         {
380715f2bd95SEwan Crawford         }
380815f2bd95SEwan Crawford 
3809222b937cSEugene Zelenko         ~CommandOptions() override = default;
381015f2bd95SEwan Crawford 
3811222b937cSEugene Zelenko         Error
3812222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
381315f2bd95SEwan Crawford         {
381415f2bd95SEwan Crawford             Error error;
381515f2bd95SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
381615f2bd95SEwan Crawford 
381715f2bd95SEwan Crawford             switch (short_option)
381815f2bd95SEwan Crawford             {
381915f2bd95SEwan Crawford                 case 'r':
382015f2bd95SEwan Crawford                     m_refresh = true;
382115f2bd95SEwan Crawford                     break;
382215f2bd95SEwan Crawford                 default:
382315f2bd95SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
382415f2bd95SEwan Crawford                     break;
382515f2bd95SEwan Crawford             }
382615f2bd95SEwan Crawford             return error;
382715f2bd95SEwan Crawford         }
382815f2bd95SEwan Crawford 
382915f2bd95SEwan Crawford         void
3830222b937cSEugene Zelenko         OptionParsingStarting() override
383115f2bd95SEwan Crawford         {
383215f2bd95SEwan Crawford             m_refresh = false;
383315f2bd95SEwan Crawford         }
383415f2bd95SEwan Crawford 
383515f2bd95SEwan Crawford         const OptionDefinition*
3836222b937cSEugene Zelenko         GetDefinitions() override
383715f2bd95SEwan Crawford         {
383815f2bd95SEwan Crawford             return g_option_table;
383915f2bd95SEwan Crawford         }
384015f2bd95SEwan Crawford 
384115f2bd95SEwan Crawford         static OptionDefinition g_option_table[];
384215f2bd95SEwan Crawford         bool m_refresh;
384315f2bd95SEwan Crawford     };
384415f2bd95SEwan Crawford 
384515f2bd95SEwan Crawford     bool
3846222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
384715f2bd95SEwan Crawford     {
384815f2bd95SEwan Crawford         RenderScriptRuntime *runtime =
384915f2bd95SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
385015f2bd95SEwan Crawford         runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(), m_options.m_refresh);
385115f2bd95SEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
385215f2bd95SEwan Crawford         return true;
385315f2bd95SEwan Crawford     }
385415f2bd95SEwan Crawford 
385515f2bd95SEwan Crawford private:
385615f2bd95SEwan Crawford     CommandOptions m_options;
385715f2bd95SEwan Crawford };
385815f2bd95SEwan Crawford 
385915f2bd95SEwan Crawford OptionDefinition
386015f2bd95SEwan Crawford CommandObjectRenderScriptRuntimeAllocationList::CommandOptions::g_option_table[] =
386115f2bd95SEwan Crawford {
386215f2bd95SEwan Crawford     { LLDB_OPT_SET_1, false, "refresh", 'r', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone,
386315f2bd95SEwan Crawford       "Recompute allocation details."},
386415f2bd95SEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
386515f2bd95SEwan Crawford };
386615f2bd95SEwan Crawford 
386755232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationLoad : public CommandObjectParsed
386855232f09SEwan Crawford {
386955232f09SEwan Crawford public:
387055232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationLoad(CommandInterpreter &interpreter)
387155232f09SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation load",
387255232f09SEwan Crawford                               "Loads renderscript allocation contents from a file.", "renderscript allocation load <ID> <filename>",
387355232f09SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
387455232f09SEwan Crawford     {
387555232f09SEwan Crawford     }
387655232f09SEwan Crawford 
3877222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
387855232f09SEwan Crawford 
387955232f09SEwan Crawford     bool
3880222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
388155232f09SEwan Crawford     {
388255232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
388355232f09SEwan Crawford         if (argc != 2)
388455232f09SEwan Crawford         {
388555232f09SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str());
388655232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
388755232f09SEwan Crawford             return false;
388855232f09SEwan Crawford         }
388955232f09SEwan Crawford 
389055232f09SEwan Crawford         RenderScriptRuntime *runtime =
389155232f09SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
389255232f09SEwan Crawford 
389355232f09SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
389455232f09SEwan Crawford         bool convert_complete = false;
389555232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
389655232f09SEwan Crawford         if (!convert_complete)
389755232f09SEwan Crawford         {
389855232f09SEwan Crawford             result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr);
389955232f09SEwan Crawford             result.SetStatus (eReturnStatusFailed);
390055232f09SEwan Crawford             return false;
390155232f09SEwan Crawford         }
390255232f09SEwan Crawford 
390355232f09SEwan Crawford         const char* filename = command.GetArgumentAtIndex(1);
390455232f09SEwan Crawford         bool success = runtime->LoadAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
390555232f09SEwan Crawford 
390655232f09SEwan Crawford         if (success)
390755232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
390855232f09SEwan Crawford         else
390955232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
391055232f09SEwan Crawford 
391155232f09SEwan Crawford         return true;
391255232f09SEwan Crawford     }
391355232f09SEwan Crawford };
391455232f09SEwan Crawford 
391555232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationSave : public CommandObjectParsed
391655232f09SEwan Crawford {
391755232f09SEwan Crawford public:
391855232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationSave(CommandInterpreter &interpreter)
391955232f09SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation save",
392055232f09SEwan Crawford                               "Write renderscript allocation contents to a file.", "renderscript allocation save <ID> <filename>",
392155232f09SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
392255232f09SEwan Crawford     {
392355232f09SEwan Crawford     }
392455232f09SEwan Crawford 
3925222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
392655232f09SEwan Crawford 
392755232f09SEwan Crawford     bool
3928222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
392955232f09SEwan Crawford     {
393055232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
393155232f09SEwan Crawford         if (argc != 2)
393255232f09SEwan Crawford         {
393355232f09SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str());
393455232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
393555232f09SEwan Crawford             return false;
393655232f09SEwan Crawford         }
393755232f09SEwan Crawford 
393855232f09SEwan Crawford         RenderScriptRuntime *runtime =
393955232f09SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
394055232f09SEwan Crawford 
394155232f09SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
394255232f09SEwan Crawford         bool convert_complete = false;
394355232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
394455232f09SEwan Crawford         if (!convert_complete)
394555232f09SEwan Crawford         {
394655232f09SEwan Crawford             result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr);
394755232f09SEwan Crawford             result.SetStatus (eReturnStatusFailed);
394855232f09SEwan Crawford             return false;
394955232f09SEwan Crawford         }
395055232f09SEwan Crawford 
395155232f09SEwan Crawford         const char* filename = command.GetArgumentAtIndex(1);
395255232f09SEwan Crawford         bool success = runtime->SaveAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
395355232f09SEwan Crawford 
395455232f09SEwan Crawford         if (success)
395555232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
395655232f09SEwan Crawford         else
395755232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
395855232f09SEwan Crawford 
395955232f09SEwan Crawford         return true;
396055232f09SEwan Crawford     }
396155232f09SEwan Crawford };
396255232f09SEwan Crawford 
396315f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocation : public CommandObjectMultiword
396415f2bd95SEwan Crawford {
396515f2bd95SEwan Crawford public:
396615f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
396715f2bd95SEwan Crawford         : CommandObjectMultiword(interpreter, "renderscript allocation", "Commands that deal with renderscript allocations.",
396815f2bd95SEwan Crawford                                  NULL)
396915f2bd95SEwan Crawford     {
397015f2bd95SEwan Crawford         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
3971a0f08674SEwan Crawford         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
397255232f09SEwan Crawford         LoadSubCommand("save", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
397355232f09SEwan Crawford         LoadSubCommand("load", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
397415f2bd95SEwan Crawford     }
397515f2bd95SEwan Crawford 
3976222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocation() override = default;
397715f2bd95SEwan Crawford };
397815f2bd95SEwan Crawford 
39794640cde1SColin Riley class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed
39804640cde1SColin Riley {
39814640cde1SColin Riley public:
39824640cde1SColin Riley     CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
39834640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript status",
39844640cde1SColin Riley                               "Displays current renderscript runtime status.", "renderscript status",
39854640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
39864640cde1SColin Riley     {
39874640cde1SColin Riley     }
39884640cde1SColin Riley 
3989222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeStatus() override = default;
39904640cde1SColin Riley 
39914640cde1SColin Riley     bool
3992222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
39934640cde1SColin Riley     {
39944640cde1SColin Riley         RenderScriptRuntime *runtime =
39954640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
39964640cde1SColin Riley         runtime->Status(result.GetOutputStream());
39974640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
39984640cde1SColin Riley         return true;
39994640cde1SColin Riley     }
40004640cde1SColin Riley };
40014640cde1SColin Riley 
40025ec532a9SColin Riley class CommandObjectRenderScriptRuntime : public CommandObjectMultiword
40035ec532a9SColin Riley {
40045ec532a9SColin Riley public:
40055ec532a9SColin Riley     CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
40065ec532a9SColin Riley         : CommandObjectMultiword(interpreter, "renderscript", "A set of commands for operating on renderscript.",
40075ec532a9SColin Riley                                  "renderscript <subcommand> [<subcommand-options>]")
40085ec532a9SColin Riley     {
40095ec532a9SColin Riley         LoadSubCommand("module", CommandObjectSP(new CommandObjectRenderScriptRuntimeModule(interpreter)));
40104640cde1SColin Riley         LoadSubCommand("status", CommandObjectSP(new CommandObjectRenderScriptRuntimeStatus(interpreter)));
40114640cde1SColin Riley         LoadSubCommand("kernel", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernel(interpreter)));
40124640cde1SColin Riley         LoadSubCommand("context", CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(interpreter)));
401315f2bd95SEwan Crawford         LoadSubCommand("allocation", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
40145ec532a9SColin Riley     }
40155ec532a9SColin Riley 
4016222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntime() override = default;
40175ec532a9SColin Riley };
4018ef20b08fSColin Riley 
4019ef20b08fSColin Riley void
4020ef20b08fSColin Riley RenderScriptRuntime::Initiate()
40215ec532a9SColin Riley {
4022ef20b08fSColin Riley     assert(!m_initiated);
40235ec532a9SColin Riley }
4024ef20b08fSColin Riley 
4025ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
40267dc7771cSEwan Crawford     : lldb_private::CPPLanguageRuntime(process), m_initiated(false), m_debuggerPresentFlagged(false),
40277dc7771cSEwan Crawford       m_breakAllKernels(false)
4028ef20b08fSColin Riley {
40294640cde1SColin Riley     ModulesDidLoad(process->GetTarget().GetImages());
4030ef20b08fSColin Riley }
40314640cde1SColin Riley 
40324640cde1SColin Riley lldb::CommandObjectSP
40334640cde1SColin Riley RenderScriptRuntime::GetCommandObject(lldb_private::CommandInterpreter& interpreter)
40344640cde1SColin Riley {
40354640cde1SColin Riley     static CommandObjectSP command_object;
40364640cde1SColin Riley     if(!command_object)
40374640cde1SColin Riley     {
40384640cde1SColin Riley         command_object.reset(new CommandObjectRenderScriptRuntime(interpreter));
40394640cde1SColin Riley     }
40404640cde1SColin Riley     return command_object;
40414640cde1SColin Riley }
40424640cde1SColin Riley 
404378f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
4044