11c3bbb01SEd Maste //===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===//
21c3bbb01SEd Maste //
31c3bbb01SEd Maste //                     The LLVM Compiler Infrastructure
41c3bbb01SEd Maste //
51c3bbb01SEd Maste // This file is distributed under the University of Illinois Open Source
61c3bbb01SEd Maste // License. See LICENSE.TXT for details.
71c3bbb01SEd Maste //
81c3bbb01SEd Maste //===----------------------------------------------------------------------===//
91c3bbb01SEd Maste 
10435933ddSDimitry Andric #include "llvm/ADT/StringSwitch.h"
11435933ddSDimitry Andric 
121c3bbb01SEd Maste #include "RenderScriptRuntime.h"
13435933ddSDimitry Andric #include "RenderScriptScriptGroup.h"
141c3bbb01SEd Maste 
154bb0738eSEd Maste #include "lldb/Breakpoint/StoppointCallbackContext.h"
161c3bbb01SEd Maste #include "lldb/Core/Debugger.h"
17f678e45dSDimitry Andric #include "lldb/Core/DumpDataExtractor.h"
181c3bbb01SEd Maste #include "lldb/Core/PluginManager.h"
194bb0738eSEd Maste #include "lldb/Core/ValueObjectVariable.h"
209f2f44ceSEd Maste #include "lldb/DataFormatters/DumpValueObjectOptions.h"
214bb0738eSEd Maste #include "lldb/Expression/UserExpression.h"
22f678e45dSDimitry Andric #include "lldb/Host/OptionParser.h"
239f2f44ceSEd Maste #include "lldb/Host/StringConvert.h"
244bb0738eSEd Maste #include "lldb/Interpreter/CommandInterpreter.h"
254bb0738eSEd Maste #include "lldb/Interpreter/CommandObjectMultiword.h"
264bb0738eSEd Maste #include "lldb/Interpreter/CommandReturnObject.h"
274bb0738eSEd Maste #include "lldb/Interpreter/Options.h"
28435933ddSDimitry Andric #include "lldb/Symbol/Function.h"
291c3bbb01SEd Maste #include "lldb/Symbol/Symbol.h"
301c3bbb01SEd Maste #include "lldb/Symbol/Type.h"
314bb0738eSEd Maste #include "lldb/Symbol/VariableList.h"
321c3bbb01SEd Maste #include "lldb/Target/Process.h"
334bb0738eSEd Maste #include "lldb/Target/RegisterContext.h"
34435933ddSDimitry Andric #include "lldb/Target/SectionLoadList.h"
351c3bbb01SEd Maste #include "lldb/Target/Target.h"
369f2f44ceSEd Maste #include "lldb/Target/Thread.h"
374ba319b5SDimitry Andric #include "lldb/Utility/Args.h"
38f678e45dSDimitry Andric #include "lldb/Utility/ConstString.h"
39f678e45dSDimitry Andric #include "lldb/Utility/Log.h"
40*b5893f02SDimitry Andric #include "lldb/Utility/RegisterValue.h"
41f678e45dSDimitry Andric #include "lldb/Utility/RegularExpression.h"
425517e702SDimitry Andric #include "lldb/Utility/Status.h"
431c3bbb01SEd Maste 
441c3bbb01SEd Maste using namespace lldb;
451c3bbb01SEd Maste using namespace lldb_private;
469f2f44ceSEd Maste using namespace lldb_renderscript;
479f2f44ceSEd Maste 
48435933ddSDimitry Andric #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")"
49435933ddSDimitry Andric 
50435933ddSDimitry Andric namespace {
519f2f44ceSEd Maste 
529f2f44ceSEd Maste // The empirical_type adds a basic level of validation to arbitrary data
53435933ddSDimitry Andric // allowing us to track if data has been discovered and stored or not. An
54435933ddSDimitry Andric // empirical_type will be marked as valid only if it has been explicitly
55435933ddSDimitry Andric // assigned to.
56435933ddSDimitry Andric template <typename type_t> class empirical_type {
579f2f44ceSEd Maste public:
589f2f44ceSEd Maste   // Ctor. Contents is invalid when constructed.
empirical_type()594bb0738eSEd Maste   empirical_type() : valid(false) {}
609f2f44ceSEd Maste 
619f2f44ceSEd Maste   // Return true and copy contents to out if valid, else return false.
get(type_t & out) const62435933ddSDimitry Andric   bool get(type_t &out) const {
639f2f44ceSEd Maste     if (valid)
649f2f44ceSEd Maste       out = data;
659f2f44ceSEd Maste     return valid;
669f2f44ceSEd Maste   }
679f2f44ceSEd Maste 
689f2f44ceSEd Maste   // Return a pointer to the contents or nullptr if it was not valid.
get() const69435933ddSDimitry Andric   const type_t *get() const { return valid ? &data : nullptr; }
709f2f44ceSEd Maste 
719f2f44ceSEd Maste   // Assign data explicitly.
set(const type_t in)72435933ddSDimitry Andric   void set(const type_t in) {
739f2f44ceSEd Maste     data = in;
749f2f44ceSEd Maste     valid = true;
759f2f44ceSEd Maste   }
769f2f44ceSEd Maste 
779f2f44ceSEd Maste   // Mark contents as invalid.
invalidate()78435933ddSDimitry Andric   void invalidate() { valid = false; }
799f2f44ceSEd Maste 
809f2f44ceSEd Maste   // Returns true if this type contains valid data.
isValid() const81435933ddSDimitry Andric   bool isValid() const { return valid; }
829f2f44ceSEd Maste 
839f2f44ceSEd Maste   // Assignment operator.
operator =(const type_t in)84435933ddSDimitry Andric   empirical_type<type_t> &operator=(const type_t in) {
859f2f44ceSEd Maste     set(in);
869f2f44ceSEd Maste     return *this;
879f2f44ceSEd Maste   }
889f2f44ceSEd Maste 
899f2f44ceSEd Maste   // Dereference operator returns contents.
909f2f44ceSEd Maste   // Warning: Will assert if not valid so use only when you know data is valid.
operator *() const91435933ddSDimitry Andric   const type_t &operator*() const {
929f2f44ceSEd Maste     assert(valid);
939f2f44ceSEd Maste     return data;
949f2f44ceSEd Maste   }
959f2f44ceSEd Maste 
969f2f44ceSEd Maste protected:
979f2f44ceSEd Maste   bool valid;
989f2f44ceSEd Maste   type_t data;
999f2f44ceSEd Maste };
1009f2f44ceSEd Maste 
101435933ddSDimitry Andric // ArgItem is used by the GetArgs() function when reading function arguments
102435933ddSDimitry Andric // from the target.
103435933ddSDimitry Andric struct ArgItem {
104435933ddSDimitry Andric   enum { ePointer, eInt32, eInt64, eLong, eBool } type;
1054bb0738eSEd Maste 
1064bb0738eSEd Maste   uint64_t value;
1074bb0738eSEd Maste 
operator uint64_t__anoncd9ccec90111::ArgItem1084bb0738eSEd Maste   explicit operator uint64_t() const { return value; }
1094bb0738eSEd Maste };
1104bb0738eSEd Maste 
111435933ddSDimitry Andric // Context structure to be passed into GetArgsXXX(), argument reading functions
112435933ddSDimitry Andric // below.
113435933ddSDimitry Andric struct GetArgsCtx {
1144bb0738eSEd Maste   RegisterContext *reg_ctx;
1154bb0738eSEd Maste   Process *process;
1164bb0738eSEd Maste };
1174bb0738eSEd Maste 
GetArgsX86(const GetArgsCtx & ctx,ArgItem * arg_list,size_t num_args)118435933ddSDimitry Andric bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
1194bb0738eSEd Maste   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
1204bb0738eSEd Maste 
1215517e702SDimitry Andric   Status err;
1224bb0738eSEd Maste 
1234bb0738eSEd Maste   // get the current stack pointer
1244bb0738eSEd Maste   uint64_t sp = ctx.reg_ctx->GetSP();
1254bb0738eSEd Maste 
126435933ddSDimitry Andric   for (size_t i = 0; i < num_args; ++i) {
1274bb0738eSEd Maste     ArgItem &arg = arg_list[i];
1284bb0738eSEd Maste     // advance up the stack by one argument
1294bb0738eSEd Maste     sp += sizeof(uint32_t);
1304bb0738eSEd Maste     // get the argument type size
1314bb0738eSEd Maste     size_t arg_size = sizeof(uint32_t);
1324bb0738eSEd Maste     // read the argument from memory
1334bb0738eSEd Maste     arg.value = 0;
1345517e702SDimitry Andric     Status err;
135435933ddSDimitry Andric     size_t read =
136435933ddSDimitry Andric         ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
137435933ddSDimitry Andric     if (read != arg_size || !err.Success()) {
1384bb0738eSEd Maste       if (log)
139435933ddSDimitry Andric         log->Printf("%s - error reading argument: %" PRIu64 " '%s'",
140435933ddSDimitry Andric                     __FUNCTION__, uint64_t(i), err.AsCString());
1414bb0738eSEd Maste       return false;
1424bb0738eSEd Maste     }
1434bb0738eSEd Maste   }
1444bb0738eSEd Maste   return true;
1454bb0738eSEd Maste }
1464bb0738eSEd Maste 
GetArgsX86_64(GetArgsCtx & ctx,ArgItem * arg_list,size_t num_args)147435933ddSDimitry Andric bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
1484bb0738eSEd Maste   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
1494bb0738eSEd Maste 
1504bb0738eSEd Maste   // number of arguments passed in registers
151435933ddSDimitry Andric   static const uint32_t args_in_reg = 6;
1524bb0738eSEd Maste   // register passing order
153435933ddSDimitry Andric   static const std::array<const char *, args_in_reg> reg_names{
154435933ddSDimitry Andric       {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
1554bb0738eSEd Maste   // argument type to size mapping
1564bb0738eSEd Maste   static const std::array<size_t, 5> arg_size{{
1574bb0738eSEd Maste       8, // ePointer,
1584bb0738eSEd Maste       4, // eInt32,
1594bb0738eSEd Maste       8, // eInt64,
1604bb0738eSEd Maste       8, // eLong,
1614bb0738eSEd Maste       4, // eBool,
1624bb0738eSEd Maste   }};
1634bb0738eSEd Maste 
1645517e702SDimitry Andric   Status err;
1654bb0738eSEd Maste 
1664bb0738eSEd Maste   // get the current stack pointer
1674bb0738eSEd Maste   uint64_t sp = ctx.reg_ctx->GetSP();
1684bb0738eSEd Maste   // step over the return address
1694bb0738eSEd Maste   sp += sizeof(uint64_t);
1704bb0738eSEd Maste 
1714bb0738eSEd Maste   // check the stack alignment was correct (16 byte aligned)
172435933ddSDimitry Andric   if ((sp & 0xf) != 0x0) {
1734bb0738eSEd Maste     if (log)
1744bb0738eSEd Maste       log->Printf("%s - stack misaligned", __FUNCTION__);
1754bb0738eSEd Maste     return false;
1764bb0738eSEd Maste   }
1774bb0738eSEd Maste 
1784bb0738eSEd Maste   // find the start of arguments on the stack
1794bb0738eSEd Maste   uint64_t sp_offset = 0;
180435933ddSDimitry Andric   for (uint32_t i = args_in_reg; i < num_args; ++i) {
1814bb0738eSEd Maste     sp_offset += arg_size[arg_list[i].type];
1824bb0738eSEd Maste   }
1834bb0738eSEd Maste   // round up to multiple of 16
1844bb0738eSEd Maste   sp_offset = (sp_offset + 0xf) & 0xf;
1854bb0738eSEd Maste   sp += sp_offset;
1864bb0738eSEd Maste 
187435933ddSDimitry Andric   for (size_t i = 0; i < num_args; ++i) {
1884bb0738eSEd Maste     bool success = false;
1894bb0738eSEd Maste     ArgItem &arg = arg_list[i];
1904bb0738eSEd Maste     // arguments passed in registers
191435933ddSDimitry Andric     if (i < args_in_reg) {
192435933ddSDimitry Andric       const RegisterInfo *reg =
193435933ddSDimitry Andric           ctx.reg_ctx->GetRegisterInfoByName(reg_names[i]);
194435933ddSDimitry Andric       RegisterValue reg_val;
195435933ddSDimitry Andric       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
196435933ddSDimitry Andric         arg.value = reg_val.GetAsUInt64(0, &success);
1974bb0738eSEd Maste     }
1984bb0738eSEd Maste     // arguments passed on the stack
199435933ddSDimitry Andric     else {
2004bb0738eSEd Maste       // get the argument type size
2014bb0738eSEd Maste       const size_t size = arg_size[arg_list[i].type];
2024bb0738eSEd Maste       // read the argument from memory
2034bb0738eSEd Maste       arg.value = 0;
204435933ddSDimitry Andric       // note: due to little endian layout reading 4 or 8 bytes will give the
205435933ddSDimitry Andric       // correct value.
206435933ddSDimitry Andric       size_t read = ctx.process->ReadMemory(sp, &arg.value, size, err);
207435933ddSDimitry Andric       success = (err.Success() && read == size);
2084bb0738eSEd Maste       // advance past this argument
2094bb0738eSEd Maste       sp -= size;
2104bb0738eSEd Maste     }
2114bb0738eSEd Maste     // fail if we couldn't read this argument
212435933ddSDimitry Andric     if (!success) {
2134bb0738eSEd Maste       if (log)
2144bb0738eSEd Maste         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
215435933ddSDimitry Andric                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
2164bb0738eSEd Maste       return false;
2174bb0738eSEd Maste     }
2184bb0738eSEd Maste   }
2194bb0738eSEd Maste   return true;
2204bb0738eSEd Maste }
2214bb0738eSEd Maste 
GetArgsArm(GetArgsCtx & ctx,ArgItem * arg_list,size_t num_args)222435933ddSDimitry Andric bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
2234bb0738eSEd Maste   // number of arguments passed in registers
224435933ddSDimitry Andric   static const uint32_t args_in_reg = 4;
2254bb0738eSEd Maste 
2264bb0738eSEd Maste   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
2274bb0738eSEd Maste 
2285517e702SDimitry Andric   Status err;
2294bb0738eSEd Maste 
2304bb0738eSEd Maste   // get the current stack pointer
2314bb0738eSEd Maste   uint64_t sp = ctx.reg_ctx->GetSP();
2324bb0738eSEd Maste 
233435933ddSDimitry Andric   for (size_t i = 0; i < num_args; ++i) {
2344bb0738eSEd Maste     bool success = false;
2354bb0738eSEd Maste     ArgItem &arg = arg_list[i];
2364bb0738eSEd Maste     // arguments passed in registers
237435933ddSDimitry Andric     if (i < args_in_reg) {
238435933ddSDimitry Andric       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
239435933ddSDimitry Andric       RegisterValue reg_val;
240435933ddSDimitry Andric       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
241435933ddSDimitry Andric         arg.value = reg_val.GetAsUInt32(0, &success);
2424bb0738eSEd Maste     }
2434bb0738eSEd Maste     // arguments passed on the stack
244435933ddSDimitry Andric     else {
2454bb0738eSEd Maste       // get the argument type size
2464bb0738eSEd Maste       const size_t arg_size = sizeof(uint32_t);
2474bb0738eSEd Maste       // clear all 64bits
2484bb0738eSEd Maste       arg.value = 0;
2494bb0738eSEd Maste       // read this argument from memory
250435933ddSDimitry Andric       size_t bytes_read =
251435933ddSDimitry Andric           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
252435933ddSDimitry Andric       success = (err.Success() && bytes_read == arg_size);
2534bb0738eSEd Maste       // advance the stack pointer
2544bb0738eSEd Maste       sp += sizeof(uint32_t);
2554bb0738eSEd Maste     }
2564bb0738eSEd Maste     // fail if we couldn't read this argument
257435933ddSDimitry Andric     if (!success) {
2584bb0738eSEd Maste       if (log)
2594bb0738eSEd Maste         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
260435933ddSDimitry Andric                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
2614bb0738eSEd Maste       return false;
2624bb0738eSEd Maste     }
2634bb0738eSEd Maste   }
2644bb0738eSEd Maste   return true;
2654bb0738eSEd Maste }
2664bb0738eSEd Maste 
GetArgsAarch64(GetArgsCtx & ctx,ArgItem * arg_list,size_t num_args)267435933ddSDimitry Andric bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
2684bb0738eSEd Maste   // number of arguments passed in registers
269435933ddSDimitry Andric   static const uint32_t args_in_reg = 8;
2704bb0738eSEd Maste 
2714bb0738eSEd Maste   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
2724bb0738eSEd Maste 
273435933ddSDimitry Andric   for (size_t i = 0; i < num_args; ++i) {
2744bb0738eSEd Maste     bool success = false;
2754bb0738eSEd Maste     ArgItem &arg = arg_list[i];
2764bb0738eSEd Maste     // arguments passed in registers
277435933ddSDimitry Andric     if (i < args_in_reg) {
278435933ddSDimitry Andric       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
279435933ddSDimitry Andric       RegisterValue reg_val;
280435933ddSDimitry Andric       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
281435933ddSDimitry Andric         arg.value = reg_val.GetAsUInt64(0, &success);
2824bb0738eSEd Maste     }
2834bb0738eSEd Maste     // arguments passed on the stack
284435933ddSDimitry Andric     else {
2854bb0738eSEd Maste       if (log)
286435933ddSDimitry Andric         log->Printf("%s - reading arguments spilled to stack not implemented",
287435933ddSDimitry Andric                     __FUNCTION__);
2884bb0738eSEd Maste     }
2894bb0738eSEd Maste     // fail if we couldn't read this argument
290435933ddSDimitry Andric     if (!success) {
2914bb0738eSEd Maste       if (log)
2924bb0738eSEd Maste         log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__,
2934bb0738eSEd Maste                     uint64_t(i));
2944bb0738eSEd Maste       return false;
2954bb0738eSEd Maste     }
2964bb0738eSEd Maste   }
2974bb0738eSEd Maste   return true;
2984bb0738eSEd Maste }
2994bb0738eSEd Maste 
GetArgsMipsel(GetArgsCtx & ctx,ArgItem * arg_list,size_t num_args)300435933ddSDimitry Andric bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
3014bb0738eSEd Maste   // number of arguments passed in registers
302435933ddSDimitry Andric   static const uint32_t args_in_reg = 4;
3034bb0738eSEd Maste   // register file offset to first argument
304435933ddSDimitry Andric   static const uint32_t reg_offset = 4;
3054bb0738eSEd Maste 
3064bb0738eSEd Maste   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
3074bb0738eSEd Maste 
3085517e702SDimitry Andric   Status err;
3094bb0738eSEd Maste 
3104ba319b5SDimitry Andric   // find offset to arguments on the stack (+16 to skip over a0-a3 shadow
3114ba319b5SDimitry Andric   // space)
3124bb0738eSEd Maste   uint64_t sp = ctx.reg_ctx->GetSP() + 16;
3134bb0738eSEd Maste 
314435933ddSDimitry Andric   for (size_t i = 0; i < num_args; ++i) {
3154bb0738eSEd Maste     bool success = false;
3164bb0738eSEd Maste     ArgItem &arg = arg_list[i];
3174bb0738eSEd Maste     // arguments passed in registers
318435933ddSDimitry Andric     if (i < args_in_reg) {
319435933ddSDimitry Andric       const RegisterInfo *reg =
320435933ddSDimitry Andric           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
321435933ddSDimitry Andric       RegisterValue reg_val;
322435933ddSDimitry Andric       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
323435933ddSDimitry Andric         arg.value = reg_val.GetAsUInt64(0, &success);
3244bb0738eSEd Maste     }
3254bb0738eSEd Maste     // arguments passed on the stack
326435933ddSDimitry Andric     else {
3274bb0738eSEd Maste       const size_t arg_size = sizeof(uint32_t);
3284bb0738eSEd Maste       arg.value = 0;
329435933ddSDimitry Andric       size_t bytes_read =
330435933ddSDimitry Andric           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
331435933ddSDimitry Andric       success = (err.Success() && bytes_read == arg_size);
3324bb0738eSEd Maste       // advance the stack pointer
3334bb0738eSEd Maste       sp += arg_size;
3344bb0738eSEd Maste     }
3354bb0738eSEd Maste     // fail if we couldn't read this argument
336435933ddSDimitry Andric     if (!success) {
3374bb0738eSEd Maste       if (log)
3384bb0738eSEd Maste         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
339435933ddSDimitry Andric                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
3404bb0738eSEd Maste       return false;
3414bb0738eSEd Maste     }
3424bb0738eSEd Maste   }
3434bb0738eSEd Maste   return true;
3444bb0738eSEd Maste }
3454bb0738eSEd Maste 
GetArgsMips64el(GetArgsCtx & ctx,ArgItem * arg_list,size_t num_args)346435933ddSDimitry Andric bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
3474bb0738eSEd Maste   // number of arguments passed in registers
348435933ddSDimitry Andric   static const uint32_t args_in_reg = 8;
3494bb0738eSEd Maste   // register file offset to first argument
350435933ddSDimitry Andric   static const uint32_t reg_offset = 4;
3514bb0738eSEd Maste 
3524bb0738eSEd Maste   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
3534bb0738eSEd Maste 
3545517e702SDimitry Andric   Status err;
3554bb0738eSEd Maste 
3564bb0738eSEd Maste   // get the current stack pointer
3574bb0738eSEd Maste   uint64_t sp = ctx.reg_ctx->GetSP();
3584bb0738eSEd Maste 
359435933ddSDimitry Andric   for (size_t i = 0; i < num_args; ++i) {
3604bb0738eSEd Maste     bool success = false;
3614bb0738eSEd Maste     ArgItem &arg = arg_list[i];
3624bb0738eSEd Maste     // arguments passed in registers
363435933ddSDimitry Andric     if (i < args_in_reg) {
364435933ddSDimitry Andric       const RegisterInfo *reg =
365435933ddSDimitry Andric           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
366435933ddSDimitry Andric       RegisterValue reg_val;
367435933ddSDimitry Andric       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
368435933ddSDimitry Andric         arg.value = reg_val.GetAsUInt64(0, &success);
3694bb0738eSEd Maste     }
3704bb0738eSEd Maste     // arguments passed on the stack
371435933ddSDimitry Andric     else {
3724bb0738eSEd Maste       // get the argument type size
3734bb0738eSEd Maste       const size_t arg_size = sizeof(uint64_t);
3744bb0738eSEd Maste       // clear all 64bits
3754bb0738eSEd Maste       arg.value = 0;
3764bb0738eSEd Maste       // read this argument from memory
377435933ddSDimitry Andric       size_t bytes_read =
378435933ddSDimitry Andric           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
379435933ddSDimitry Andric       success = (err.Success() && bytes_read == arg_size);
3804bb0738eSEd Maste       // advance the stack pointer
3814bb0738eSEd Maste       sp += arg_size;
3824bb0738eSEd Maste     }
3834bb0738eSEd Maste     // fail if we couldn't read this argument
384435933ddSDimitry Andric     if (!success) {
3854bb0738eSEd Maste       if (log)
3864bb0738eSEd Maste         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
387435933ddSDimitry Andric                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
3884bb0738eSEd Maste       return false;
3894bb0738eSEd Maste     }
3904bb0738eSEd Maste   }
3914bb0738eSEd Maste   return true;
3924bb0738eSEd Maste }
3934bb0738eSEd Maste 
GetArgs(ExecutionContext & exe_ctx,ArgItem * arg_list,size_t num_args)394435933ddSDimitry Andric bool GetArgs(ExecutionContext &exe_ctx, ArgItem *arg_list, size_t num_args) {
3954bb0738eSEd Maste   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
3964bb0738eSEd Maste 
3974bb0738eSEd Maste   // verify that we have a target
398435933ddSDimitry Andric   if (!exe_ctx.GetTargetPtr()) {
3994bb0738eSEd Maste     if (log)
4004bb0738eSEd Maste       log->Printf("%s - invalid target", __FUNCTION__);
4014bb0738eSEd Maste     return false;
4024bb0738eSEd Maste   }
4034bb0738eSEd Maste 
404435933ddSDimitry Andric   GetArgsCtx ctx = {exe_ctx.GetRegisterContext(), exe_ctx.GetProcessPtr()};
4054bb0738eSEd Maste   assert(ctx.reg_ctx && ctx.process);
4064bb0738eSEd Maste 
4074bb0738eSEd Maste   // dispatch based on architecture
408435933ddSDimitry Andric   switch (exe_ctx.GetTargetPtr()->GetArchitecture().GetMachine()) {
4094bb0738eSEd Maste   case llvm::Triple::ArchType::x86:
4104bb0738eSEd Maste     return GetArgsX86(ctx, arg_list, num_args);
4114bb0738eSEd Maste 
4124bb0738eSEd Maste   case llvm::Triple::ArchType::x86_64:
4134bb0738eSEd Maste     return GetArgsX86_64(ctx, arg_list, num_args);
4144bb0738eSEd Maste 
4154bb0738eSEd Maste   case llvm::Triple::ArchType::arm:
4164bb0738eSEd Maste     return GetArgsArm(ctx, arg_list, num_args);
4174bb0738eSEd Maste 
4184bb0738eSEd Maste   case llvm::Triple::ArchType::aarch64:
4194bb0738eSEd Maste     return GetArgsAarch64(ctx, arg_list, num_args);
4204bb0738eSEd Maste 
4214bb0738eSEd Maste   case llvm::Triple::ArchType::mipsel:
4224bb0738eSEd Maste     return GetArgsMipsel(ctx, arg_list, num_args);
4234bb0738eSEd Maste 
4244bb0738eSEd Maste   case llvm::Triple::ArchType::mips64el:
4254bb0738eSEd Maste     return GetArgsMips64el(ctx, arg_list, num_args);
4264bb0738eSEd Maste 
4274bb0738eSEd Maste   default:
4284bb0738eSEd Maste     // unsupported architecture
429435933ddSDimitry Andric     if (log) {
430435933ddSDimitry Andric       log->Printf(
431435933ddSDimitry Andric           "%s - architecture not supported: '%s'", __FUNCTION__,
432435933ddSDimitry Andric           exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
4334bb0738eSEd Maste     }
4344bb0738eSEd Maste     return false;
4354bb0738eSEd Maste   }
4364bb0738eSEd Maste }
437435933ddSDimitry Andric 
IsRenderScriptScriptModule(ModuleSP module)438435933ddSDimitry Andric bool IsRenderScriptScriptModule(ModuleSP module) {
439435933ddSDimitry Andric   if (!module)
440435933ddSDimitry Andric     return false;
441435933ddSDimitry Andric   return module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
442435933ddSDimitry Andric                                                 eSymbolTypeData) != nullptr;
443435933ddSDimitry Andric }
444435933ddSDimitry Andric 
ParseCoordinate(llvm::StringRef coord_s,RSCoordinate & coord)445435933ddSDimitry Andric bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
4464ba319b5SDimitry Andric   // takes an argument of the form 'num[,num][,num]'. Where 'coord_s' is a
4474ba319b5SDimitry Andric   // comma separated 1,2 or 3-dimensional coordinate with the whitespace
4484ba319b5SDimitry Andric   // trimmed. Missing coordinates are defaulted to zero. If parsing of any
4494ba319b5SDimitry Andric   // elements fails the contents of &coord are undefined and `false` is
4504ba319b5SDimitry Andric   // returned, `true` otherwise
451435933ddSDimitry Andric 
452435933ddSDimitry Andric   RegularExpression regex;
453435933ddSDimitry Andric   RegularExpression::Match regex_match(3);
454435933ddSDimitry Andric 
455435933ddSDimitry Andric   bool matched = false;
456435933ddSDimitry Andric   if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+),([0-9]+)$")) &&
457435933ddSDimitry Andric       regex.Execute(coord_s, &regex_match))
458435933ddSDimitry Andric     matched = true;
459435933ddSDimitry Andric   else if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+)$")) &&
460435933ddSDimitry Andric            regex.Execute(coord_s, &regex_match))
461435933ddSDimitry Andric     matched = true;
462435933ddSDimitry Andric   else if (regex.Compile(llvm::StringRef("^([0-9]+)$")) &&
463435933ddSDimitry Andric            regex.Execute(coord_s, &regex_match))
464435933ddSDimitry Andric     matched = true;
465435933ddSDimitry Andric 
466435933ddSDimitry Andric   if (!matched)
467435933ddSDimitry Andric     return false;
468435933ddSDimitry Andric 
469435933ddSDimitry Andric   auto get_index = [&](int idx, uint32_t &i) -> bool {
470435933ddSDimitry Andric     std::string group;
471435933ddSDimitry Andric     errno = 0;
472435933ddSDimitry Andric     if (regex_match.GetMatchAtIndex(coord_s.str().c_str(), idx + 1, group))
473435933ddSDimitry Andric       return !llvm::StringRef(group).getAsInteger<uint32_t>(10, i);
474435933ddSDimitry Andric     return true;
475435933ddSDimitry Andric   };
476435933ddSDimitry Andric 
477435933ddSDimitry Andric   return get_index(0, coord.x) && get_index(1, coord.y) &&
478435933ddSDimitry Andric          get_index(2, coord.z);
479435933ddSDimitry Andric }
480435933ddSDimitry Andric 
SkipPrologue(lldb::ModuleSP & module,Address & addr)481435933ddSDimitry Andric bool SkipPrologue(lldb::ModuleSP &module, Address &addr) {
482435933ddSDimitry Andric   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
483435933ddSDimitry Andric   SymbolContext sc;
484435933ddSDimitry Andric   uint32_t resolved_flags =
485435933ddSDimitry Andric       module->ResolveSymbolContextForAddress(addr, eSymbolContextFunction, sc);
486435933ddSDimitry Andric   if (resolved_flags & eSymbolContextFunction) {
487435933ddSDimitry Andric     if (sc.function) {
488435933ddSDimitry Andric       const uint32_t offset = sc.function->GetPrologueByteSize();
489435933ddSDimitry Andric       ConstString name = sc.GetFunctionName();
490435933ddSDimitry Andric       if (offset)
491435933ddSDimitry Andric         addr.Slide(offset);
492435933ddSDimitry Andric       if (log)
493435933ddSDimitry Andric         log->Printf("%s: Prologue offset for %s is %" PRIu32, __FUNCTION__,
494435933ddSDimitry Andric                     name.AsCString(), offset);
495435933ddSDimitry Andric     }
496435933ddSDimitry Andric     return true;
497435933ddSDimitry Andric   } else
498435933ddSDimitry Andric     return false;
499435933ddSDimitry Andric }
5009f2f44ceSEd Maste } // anonymous namespace
5019f2f44ceSEd Maste 
502435933ddSDimitry Andric // The ScriptDetails class collects data associated with a single script
503435933ddSDimitry Andric // instance.
504435933ddSDimitry Andric struct RenderScriptRuntime::ScriptDetails {
5059f2f44ceSEd Maste   ~ScriptDetails() = default;
5069f2f44ceSEd Maste 
507435933ddSDimitry Andric   enum ScriptType { eScript, eScriptC };
5089f2f44ceSEd Maste 
5099f2f44ceSEd Maste   // The derived type of the script.
5109f2f44ceSEd Maste   empirical_type<ScriptType> type;
5119f2f44ceSEd Maste   // The name of the original source file.
512435933ddSDimitry Andric   empirical_type<std::string> res_name;
5139f2f44ceSEd Maste   // Path to script .so file on the device.
514435933ddSDimitry Andric   empirical_type<std::string> shared_lib;
5159f2f44ceSEd Maste   // Directory where kernel objects are cached on device.
516435933ddSDimitry Andric   empirical_type<std::string> cache_dir;
5179f2f44ceSEd Maste   // Pointer to the context which owns this script.
5189f2f44ceSEd Maste   empirical_type<lldb::addr_t> context;
5199f2f44ceSEd Maste   // Pointer to the script object itself.
5209f2f44ceSEd Maste   empirical_type<lldb::addr_t> script;
5219f2f44ceSEd Maste };
5229f2f44ceSEd Maste 
523435933ddSDimitry Andric // This Element class represents the Element object in RS, defining the type
524435933ddSDimitry Andric // associated with an Allocation.
525435933ddSDimitry Andric struct RenderScriptRuntime::Element {
5269f2f44ceSEd Maste   // Taken from rsDefines.h
527435933ddSDimitry Andric   enum DataKind {
5289f2f44ceSEd Maste     RS_KIND_USER,
5299f2f44ceSEd Maste     RS_KIND_PIXEL_L = 7,
5309f2f44ceSEd Maste     RS_KIND_PIXEL_A,
5319f2f44ceSEd Maste     RS_KIND_PIXEL_LA,
5329f2f44ceSEd Maste     RS_KIND_PIXEL_RGB,
5339f2f44ceSEd Maste     RS_KIND_PIXEL_RGBA,
5349f2f44ceSEd Maste     RS_KIND_PIXEL_DEPTH,
5359f2f44ceSEd Maste     RS_KIND_PIXEL_YUV,
5369f2f44ceSEd Maste     RS_KIND_INVALID = 100
5379f2f44ceSEd Maste   };
5389f2f44ceSEd Maste 
5399f2f44ceSEd Maste   // Taken from rsDefines.h
540435933ddSDimitry Andric   enum DataType {
5419f2f44ceSEd Maste     RS_TYPE_NONE = 0,
5429f2f44ceSEd Maste     RS_TYPE_FLOAT_16,
5439f2f44ceSEd Maste     RS_TYPE_FLOAT_32,
5449f2f44ceSEd Maste     RS_TYPE_FLOAT_64,
5459f2f44ceSEd Maste     RS_TYPE_SIGNED_8,
5469f2f44ceSEd Maste     RS_TYPE_SIGNED_16,
5479f2f44ceSEd Maste     RS_TYPE_SIGNED_32,
5489f2f44ceSEd Maste     RS_TYPE_SIGNED_64,
5499f2f44ceSEd Maste     RS_TYPE_UNSIGNED_8,
5509f2f44ceSEd Maste     RS_TYPE_UNSIGNED_16,
5519f2f44ceSEd Maste     RS_TYPE_UNSIGNED_32,
5529f2f44ceSEd Maste     RS_TYPE_UNSIGNED_64,
5539f2f44ceSEd Maste     RS_TYPE_BOOLEAN,
5549f2f44ceSEd Maste 
5559f2f44ceSEd Maste     RS_TYPE_UNSIGNED_5_6_5,
5569f2f44ceSEd Maste     RS_TYPE_UNSIGNED_5_5_5_1,
5579f2f44ceSEd Maste     RS_TYPE_UNSIGNED_4_4_4_4,
5589f2f44ceSEd Maste 
5599f2f44ceSEd Maste     RS_TYPE_MATRIX_4X4,
5609f2f44ceSEd Maste     RS_TYPE_MATRIX_3X3,
5619f2f44ceSEd Maste     RS_TYPE_MATRIX_2X2,
5629f2f44ceSEd Maste 
5639f2f44ceSEd Maste     RS_TYPE_ELEMENT = 1000,
5649f2f44ceSEd Maste     RS_TYPE_TYPE,
5659f2f44ceSEd Maste     RS_TYPE_ALLOCATION,
5669f2f44ceSEd Maste     RS_TYPE_SAMPLER,
5679f2f44ceSEd Maste     RS_TYPE_SCRIPT,
5689f2f44ceSEd Maste     RS_TYPE_MESH,
5699f2f44ceSEd Maste     RS_TYPE_PROGRAM_FRAGMENT,
5709f2f44ceSEd Maste     RS_TYPE_PROGRAM_VERTEX,
5719f2f44ceSEd Maste     RS_TYPE_PROGRAM_RASTER,
5729f2f44ceSEd Maste     RS_TYPE_PROGRAM_STORE,
5739f2f44ceSEd Maste     RS_TYPE_FONT,
5749f2f44ceSEd Maste 
5759f2f44ceSEd Maste     RS_TYPE_INVALID = 10000
5769f2f44ceSEd Maste   };
5779f2f44ceSEd Maste 
5789f2f44ceSEd Maste   std::vector<Element> children; // Child Element fields for structs
579435933ddSDimitry Andric   empirical_type<lldb::addr_t>
580435933ddSDimitry Andric       element_ptr; // Pointer to the RS Element of the Type
581435933ddSDimitry Andric   empirical_type<DataType>
582435933ddSDimitry Andric       type; // Type of each data pointer stored by the allocation
583435933ddSDimitry Andric   empirical_type<DataKind>
584435933ddSDimitry Andric       type_kind; // Defines pixel type if Allocation is created from an image
585435933ddSDimitry Andric   empirical_type<uint32_t>
586435933ddSDimitry Andric       type_vec_size; // Vector size of each data point, e.g '4' for uchar4
5879f2f44ceSEd Maste   empirical_type<uint32_t> field_count; // Number of Subelements
5889f2f44ceSEd Maste   empirical_type<uint32_t> datum_size;  // Size of a single Element with padding
5899f2f44ceSEd Maste   empirical_type<uint32_t> padding;     // Number of padding bytes
590435933ddSDimitry Andric   empirical_type<uint32_t>
5914ba319b5SDimitry Andric       array_size;        // Number of items in array, only needed for structs
5929f2f44ceSEd Maste   ConstString type_name; // Name of type, only needed for structs
5939f2f44ceSEd Maste 
5944bb0738eSEd Maste   static const ConstString &
5954bb0738eSEd Maste   GetFallbackStructName(); // Print this as the type name of a struct Element
5969f2f44ceSEd Maste                            // If we can't resolve the actual struct name
5979f2f44ceSEd Maste 
ShouldRefreshRenderScriptRuntime::Element598435933ddSDimitry Andric   bool ShouldRefresh() const {
5999f2f44ceSEd Maste     const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
600435933ddSDimitry Andric     const bool valid_type =
601435933ddSDimitry Andric         type.isValid() && type_vec_size.isValid() && type_kind.isValid();
6029f2f44ceSEd Maste     return !valid_ptr || !valid_type || !datum_size.isValid();
6039f2f44ceSEd Maste   }
6049f2f44ceSEd Maste };
6059f2f44ceSEd Maste 
6069f2f44ceSEd Maste // This AllocationDetails class collects data associated with a single
6079f2f44ceSEd Maste // allocation instance.
608435933ddSDimitry Andric struct RenderScriptRuntime::AllocationDetails {
609435933ddSDimitry Andric   struct Dimension {
6109f2f44ceSEd Maste     uint32_t dim_1;
6119f2f44ceSEd Maste     uint32_t dim_2;
6129f2f44ceSEd Maste     uint32_t dim_3;
613435933ddSDimitry Andric     uint32_t cube_map;
6149f2f44ceSEd Maste 
DimensionRenderScriptRuntime::AllocationDetails::Dimension615435933ddSDimitry Andric     Dimension() {
6169f2f44ceSEd Maste       dim_1 = 0;
6179f2f44ceSEd Maste       dim_2 = 0;
6189f2f44ceSEd Maste       dim_3 = 0;
619435933ddSDimitry Andric       cube_map = 0;
6209f2f44ceSEd Maste     }
6219f2f44ceSEd Maste   };
6229f2f44ceSEd Maste 
623435933ddSDimitry Andric   // The FileHeader struct specifies the header we use for writing allocations
624435933ddSDimitry Andric   // to a binary file. Our format begins with the ASCII characters "RSAD",
625435933ddSDimitry Andric   // identifying the file as an allocation dump. Member variables dims and
626435933ddSDimitry Andric   // hdr_size are then written consecutively, immediately followed by an
627435933ddSDimitry Andric   // instance of the ElementHeader struct. Because Elements can contain
628435933ddSDimitry Andric   // subelements, there may be more than one instance of the ElementHeader
629435933ddSDimitry Andric   // struct. With this first instance being the root element, and the other
630435933ddSDimitry Andric   // instances being the root's descendants. To identify which instances are an
6314ba319b5SDimitry Andric   // ElementHeader's children, each struct is immediately followed by a
6324ba319b5SDimitry Andric   // sequence of consecutive offsets to the start of its child structs. These
6334ba319b5SDimitry Andric   // offsets are
634435933ddSDimitry Andric   // 4 bytes in size, and the 0 offset signifies no more children.
635435933ddSDimitry Andric   struct FileHeader {
6369f2f44ceSEd Maste     uint8_t ident[4];  // ASCII 'RSAD' identifying the file
637444ed5c5SDimitry Andric     uint32_t dims[3];  // Dimensions
638444ed5c5SDimitry Andric     uint16_t hdr_size; // Header size in bytes, including all element headers
639444ed5c5SDimitry Andric   };
640444ed5c5SDimitry Andric 
641435933ddSDimitry Andric   struct ElementHeader {
6429f2f44ceSEd Maste     uint16_t type;         // DataType enum
6439f2f44ceSEd Maste     uint32_t kind;         // DataKind enum
6449f2f44ceSEd Maste     uint32_t element_size; // Size of a single element, including padding
645444ed5c5SDimitry Andric     uint16_t vector_size;  // Vector width
646444ed5c5SDimitry Andric     uint32_t array_size;   // Number of elements in array
6479f2f44ceSEd Maste   };
6489f2f44ceSEd Maste 
6499f2f44ceSEd Maste   // Monotonically increasing from 1
6504bb0738eSEd Maste   static uint32_t ID;
6519f2f44ceSEd Maste 
6524ba319b5SDimitry Andric   // Maps Allocation DataType enum and vector size to printable strings using
6534ba319b5SDimitry Andric   // mapping from RenderScript numerical types summary documentation
6549f2f44ceSEd Maste   static const char *RsDataTypeToString[][4];
6559f2f44ceSEd Maste 
6569f2f44ceSEd Maste   // Maps Allocation DataKind enum to printable strings
6579f2f44ceSEd Maste   static const char *RsDataKindToString[];
6589f2f44ceSEd Maste 
6599f2f44ceSEd Maste   // Maps allocation types to format sizes for printing.
6604bb0738eSEd Maste   static const uint32_t RSTypeToFormat[][3];
6619f2f44ceSEd Maste 
6629f2f44ceSEd Maste   // Give each allocation an ID as a way
6639f2f44ceSEd Maste   // for commands to reference it.
6644bb0738eSEd Maste   const uint32_t id;
6659f2f44ceSEd Maste 
666435933ddSDimitry Andric   // Allocation Element type
667435933ddSDimitry Andric   RenderScriptRuntime::Element element;
668435933ddSDimitry Andric   // Dimensions of the Allocation
669435933ddSDimitry Andric   empirical_type<Dimension> dimension;
670435933ddSDimitry Andric   // Pointer to address of the RS Allocation
671435933ddSDimitry Andric   empirical_type<lldb::addr_t> address;
672435933ddSDimitry Andric   // Pointer to the data held by the Allocation
673435933ddSDimitry Andric   empirical_type<lldb::addr_t> data_ptr;
674435933ddSDimitry Andric   // Pointer to the RS Type of the Allocation
675435933ddSDimitry Andric   empirical_type<lldb::addr_t> type_ptr;
676435933ddSDimitry Andric   // Pointer to the RS Context of the Allocation
677435933ddSDimitry Andric   empirical_type<lldb::addr_t> context;
678435933ddSDimitry Andric   // Size of the allocation
679435933ddSDimitry Andric   empirical_type<uint32_t> size;
680435933ddSDimitry Andric   // Stride between rows of the allocation
681435933ddSDimitry Andric   empirical_type<uint32_t> stride;
6829f2f44ceSEd Maste 
6839f2f44ceSEd Maste   // Give each allocation an id, so we can reference it in user commands.
AllocationDetailsRenderScriptRuntime::AllocationDetails6844bb0738eSEd Maste   AllocationDetails() : id(ID++) {}
6859f2f44ceSEd Maste 
ShouldRefreshRenderScriptRuntime::AllocationDetails686435933ddSDimitry Andric   bool ShouldRefresh() const {
6879f2f44ceSEd Maste     bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
6889f2f44ceSEd Maste     valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
689435933ddSDimitry Andric     return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
690435933ddSDimitry Andric            element.ShouldRefresh();
6919f2f44ceSEd Maste   }
6929f2f44ceSEd Maste };
6939f2f44ceSEd Maste 
GetFallbackStructName()694435933ddSDimitry Andric const ConstString &RenderScriptRuntime::Element::GetFallbackStructName() {
6959f2f44ceSEd Maste   static const ConstString FallbackStructName("struct");
6969f2f44ceSEd Maste   return FallbackStructName;
6979f2f44ceSEd Maste }
6989f2f44ceSEd Maste 
6994bb0738eSEd Maste uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
7009f2f44ceSEd Maste 
7014bb0738eSEd Maste const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
702435933ddSDimitry Andric     "User",       "Undefined",   "Undefined", "Undefined",
703435933ddSDimitry Andric     "Undefined",  "Undefined",   "Undefined", // Enum jumps from 0 to 7
7044bb0738eSEd Maste     "L Pixel",    "A Pixel",     "LA Pixel",  "RGB Pixel",
7054bb0738eSEd Maste     "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
7069f2f44ceSEd Maste 
7074bb0738eSEd Maste const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
7089f2f44ceSEd Maste     {"None", "None", "None", "None"},
7099f2f44ceSEd Maste     {"half", "half2", "half3", "half4"},
7109f2f44ceSEd Maste     {"float", "float2", "float3", "float4"},
7119f2f44ceSEd Maste     {"double", "double2", "double3", "double4"},
7129f2f44ceSEd Maste     {"char", "char2", "char3", "char4"},
7139f2f44ceSEd Maste     {"short", "short2", "short3", "short4"},
7149f2f44ceSEd Maste     {"int", "int2", "int3", "int4"},
7159f2f44ceSEd Maste     {"long", "long2", "long3", "long4"},
7169f2f44ceSEd Maste     {"uchar", "uchar2", "uchar3", "uchar4"},
7179f2f44ceSEd Maste     {"ushort", "ushort2", "ushort3", "ushort4"},
7189f2f44ceSEd Maste     {"uint", "uint2", "uint3", "uint4"},
7199f2f44ceSEd Maste     {"ulong", "ulong2", "ulong3", "ulong4"},
7209f2f44ceSEd Maste     {"bool", "bool2", "bool3", "bool4"},
7219f2f44ceSEd Maste     {"packed_565", "packed_565", "packed_565", "packed_565"},
7229f2f44ceSEd Maste     {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
7239f2f44ceSEd Maste     {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
7249f2f44ceSEd Maste     {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
7259f2f44ceSEd Maste     {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
7269f2f44ceSEd Maste     {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
7279f2f44ceSEd Maste 
7289f2f44ceSEd Maste     // Handlers
7299f2f44ceSEd Maste     {"RS Element", "RS Element", "RS Element", "RS Element"},
7309f2f44ceSEd Maste     {"RS Type", "RS Type", "RS Type", "RS Type"},
7319f2f44ceSEd Maste     {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
7329f2f44ceSEd Maste     {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
7339f2f44ceSEd Maste     {"RS Script", "RS Script", "RS Script", "RS Script"},
7349f2f44ceSEd Maste 
7359f2f44ceSEd Maste     // Deprecated
7369f2f44ceSEd Maste     {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
737435933ddSDimitry Andric     {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
738435933ddSDimitry Andric      "RS Program Fragment"},
739435933ddSDimitry Andric     {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
740435933ddSDimitry Andric      "RS Program Vertex"},
741435933ddSDimitry Andric     {"RS Program Raster", "RS Program Raster", "RS Program Raster",
742435933ddSDimitry Andric      "RS Program Raster"},
743435933ddSDimitry Andric     {"RS Program Store", "RS Program Store", "RS Program Store",
744435933ddSDimitry Andric      "RS Program Store"},
7454bb0738eSEd Maste     {"RS Font", "RS Font", "RS Font", "RS Font"}};
7469f2f44ceSEd Maste 
7479f2f44ceSEd Maste // Used as an index into the RSTypeToFormat array elements
748435933ddSDimitry Andric enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
7499f2f44ceSEd Maste 
750435933ddSDimitry Andric // { format enum of single element, format enum of element vector, size of
751435933ddSDimitry Andric // element}
7524bb0738eSEd Maste const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
753435933ddSDimitry Andric     // RS_TYPE_NONE
754435933ddSDimitry Andric     {eFormatHex, eFormatHex, 1},
755435933ddSDimitry Andric     // RS_TYPE_FLOAT_16
756435933ddSDimitry Andric     {eFormatFloat, eFormatVectorOfFloat16, 2},
757435933ddSDimitry Andric     // RS_TYPE_FLOAT_32
758435933ddSDimitry Andric     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
759435933ddSDimitry Andric     // RS_TYPE_FLOAT_64
760435933ddSDimitry Andric     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
761435933ddSDimitry Andric     // RS_TYPE_SIGNED_8
762435933ddSDimitry Andric     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
763435933ddSDimitry Andric     // RS_TYPE_SIGNED_16
764435933ddSDimitry Andric     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
765435933ddSDimitry Andric     // RS_TYPE_SIGNED_32
766435933ddSDimitry Andric     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
767435933ddSDimitry Andric     // RS_TYPE_SIGNED_64
768435933ddSDimitry Andric     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
769435933ddSDimitry Andric     // RS_TYPE_UNSIGNED_8
770435933ddSDimitry Andric     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
771435933ddSDimitry Andric     // RS_TYPE_UNSIGNED_16
772435933ddSDimitry Andric     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
773435933ddSDimitry Andric     // RS_TYPE_UNSIGNED_32
774435933ddSDimitry Andric     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
775435933ddSDimitry Andric     // RS_TYPE_UNSIGNED_64
776435933ddSDimitry Andric     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
777435933ddSDimitry Andric     // RS_TYPE_BOOL
778435933ddSDimitry Andric     {eFormatBoolean, eFormatBoolean, 1},
779435933ddSDimitry Andric     // RS_TYPE_UNSIGNED_5_6_5
780435933ddSDimitry Andric     {eFormatHex, eFormatHex, sizeof(uint16_t)},
781435933ddSDimitry Andric     // RS_TYPE_UNSIGNED_5_5_5_1
782435933ddSDimitry Andric     {eFormatHex, eFormatHex, sizeof(uint16_t)},
783435933ddSDimitry Andric     // RS_TYPE_UNSIGNED_4_4_4_4
784435933ddSDimitry Andric     {eFormatHex, eFormatHex, sizeof(uint16_t)},
785435933ddSDimitry Andric     // RS_TYPE_MATRIX_4X4
786435933ddSDimitry Andric     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
787435933ddSDimitry Andric     // RS_TYPE_MATRIX_3X3
788435933ddSDimitry Andric     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
789435933ddSDimitry Andric     // RS_TYPE_MATRIX_2X2
790435933ddSDimitry Andric     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
7911c3bbb01SEd Maste 
7921c3bbb01SEd Maste //------------------------------------------------------------------
7931c3bbb01SEd Maste // Static Functions
7941c3bbb01SEd Maste //------------------------------------------------------------------
7951c3bbb01SEd Maste LanguageRuntime *
CreateInstance(Process * process,lldb::LanguageType language)796435933ddSDimitry Andric RenderScriptRuntime::CreateInstance(Process *process,
797435933ddSDimitry Andric                                     lldb::LanguageType language) {
7981c3bbb01SEd Maste 
7991c3bbb01SEd Maste   if (language == eLanguageTypeExtRenderScript)
8001c3bbb01SEd Maste     return new RenderScriptRuntime(process);
8011c3bbb01SEd Maste   else
8024bb0738eSEd Maste     return nullptr;
8031c3bbb01SEd Maste }
8041c3bbb01SEd Maste 
805435933ddSDimitry Andric // Callback with a module to search for matching symbols. We first check that
806435933ddSDimitry Andric // the module contains RS kernels. Then look for a symbol which matches our
807435933ddSDimitry Andric // kernel name. The breakpoint address is finally set using the address of this
808435933ddSDimitry Andric // symbol.
8099f2f44ceSEd Maste Searcher::CallbackReturn
SearchCallback(SearchFilter & filter,SymbolContext & context,Address *,bool)810435933ddSDimitry Andric RSBreakpointResolver::SearchCallback(SearchFilter &filter,
811435933ddSDimitry Andric                                      SymbolContext &context, Address *, bool) {
8129f2f44ceSEd Maste   ModuleSP module = context.module_sp;
8139f2f44ceSEd Maste 
814435933ddSDimitry Andric   if (!module || !IsRenderScriptScriptModule(module))
8159f2f44ceSEd Maste     return Searcher::eCallbackReturnContinue;
8169f2f44ceSEd Maste 
817435933ddSDimitry Andric   // Attempt to set a breakpoint on the kernel name symbol within the module
818435933ddSDimitry Andric   // library. If it's not found, it's likely debug info is unavailable - try to
819435933ddSDimitry Andric   // set a breakpoint on <name>.expand.
820435933ddSDimitry Andric   const Symbol *kernel_sym =
821435933ddSDimitry Andric       module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
822435933ddSDimitry Andric   if (!kernel_sym) {
8239f2f44ceSEd Maste     std::string kernel_name_expanded(m_kernel_name.AsCString());
8249f2f44ceSEd Maste     kernel_name_expanded.append(".expand");
825435933ddSDimitry Andric     kernel_sym = module->FindFirstSymbolWithNameAndType(
826435933ddSDimitry Andric         ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
8279f2f44ceSEd Maste   }
8289f2f44ceSEd Maste 
829435933ddSDimitry Andric   if (kernel_sym) {
8309f2f44ceSEd Maste     Address bp_addr = kernel_sym->GetAddress();
8319f2f44ceSEd Maste     if (filter.AddressPasses(bp_addr))
8329f2f44ceSEd Maste       m_breakpoint->AddLocation(bp_addr);
8339f2f44ceSEd Maste   }
8349f2f44ceSEd Maste 
8359f2f44ceSEd Maste   return Searcher::eCallbackReturnContinue;
8369f2f44ceSEd Maste }
8379f2f44ceSEd Maste 
838435933ddSDimitry Andric Searcher::CallbackReturn
SearchCallback(lldb_private::SearchFilter & filter,lldb_private::SymbolContext & context,Address *,bool)839435933ddSDimitry Andric RSReduceBreakpointResolver::SearchCallback(lldb_private::SearchFilter &filter,
840435933ddSDimitry Andric                                            lldb_private::SymbolContext &context,
841435933ddSDimitry Andric                                            Address *, bool) {
842435933ddSDimitry Andric   // We need to have access to the list of reductions currently parsed, as
8434ba319b5SDimitry Andric   // reduce names don't actually exist as symbols in a module. They are only
8444ba319b5SDimitry Andric   // identifiable by parsing the .rs.info packet, or finding the expand symbol.
8454ba319b5SDimitry Andric   // We therefore need access to the list of parsed rs modules to properly
8464ba319b5SDimitry Andric   // resolve reduction names.
847435933ddSDimitry Andric   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
848435933ddSDimitry Andric   ModuleSP module = context.module_sp;
849435933ddSDimitry Andric 
850435933ddSDimitry Andric   if (!module || !IsRenderScriptScriptModule(module))
851435933ddSDimitry Andric     return Searcher::eCallbackReturnContinue;
852435933ddSDimitry Andric 
853435933ddSDimitry Andric   if (!m_rsmodules)
854435933ddSDimitry Andric     return Searcher::eCallbackReturnContinue;
855435933ddSDimitry Andric 
856435933ddSDimitry Andric   for (const auto &module_desc : *m_rsmodules) {
857435933ddSDimitry Andric     if (module_desc->m_module != module)
858435933ddSDimitry Andric       continue;
859435933ddSDimitry Andric 
860435933ddSDimitry Andric     for (const auto &reduction : module_desc->m_reductions) {
861435933ddSDimitry Andric       if (reduction.m_reduce_name != m_reduce_name)
862435933ddSDimitry Andric         continue;
863435933ddSDimitry Andric 
864435933ddSDimitry Andric       std::array<std::pair<ConstString, int>, 5> funcs{
865435933ddSDimitry Andric           {{reduction.m_init_name, eKernelTypeInit},
866435933ddSDimitry Andric            {reduction.m_accum_name, eKernelTypeAccum},
867435933ddSDimitry Andric            {reduction.m_comb_name, eKernelTypeComb},
868435933ddSDimitry Andric            {reduction.m_outc_name, eKernelTypeOutC},
869435933ddSDimitry Andric            {reduction.m_halter_name, eKernelTypeHalter}}};
870435933ddSDimitry Andric 
871435933ddSDimitry Andric       for (const auto &kernel : funcs) {
872435933ddSDimitry Andric         // Skip constituent functions that don't match our spec
873435933ddSDimitry Andric         if (!(m_kernel_types & kernel.second))
874435933ddSDimitry Andric           continue;
875435933ddSDimitry Andric 
876435933ddSDimitry Andric         const auto kernel_name = kernel.first;
877435933ddSDimitry Andric         const auto symbol = module->FindFirstSymbolWithNameAndType(
878435933ddSDimitry Andric             kernel_name, eSymbolTypeCode);
879435933ddSDimitry Andric         if (!symbol)
880435933ddSDimitry Andric           continue;
881435933ddSDimitry Andric 
882435933ddSDimitry Andric         auto address = symbol->GetAddress();
883435933ddSDimitry Andric         if (filter.AddressPasses(address)) {
884435933ddSDimitry Andric           bool new_bp;
885435933ddSDimitry Andric           if (!SkipPrologue(module, address)) {
886435933ddSDimitry Andric             if (log)
887435933ddSDimitry Andric               log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
888435933ddSDimitry Andric           }
889435933ddSDimitry Andric           m_breakpoint->AddLocation(address, &new_bp);
890435933ddSDimitry Andric           if (log)
891435933ddSDimitry Andric             log->Printf("%s: %s reduction breakpoint on %s in %s", __FUNCTION__,
892435933ddSDimitry Andric                         new_bp ? "new" : "existing", kernel_name.GetCString(),
893435933ddSDimitry Andric                         address.GetModule()->GetFileSpec().GetCString());
894435933ddSDimitry Andric         }
895435933ddSDimitry Andric       }
896435933ddSDimitry Andric     }
897435933ddSDimitry Andric   }
898435933ddSDimitry Andric   return eCallbackReturnContinue;
899435933ddSDimitry Andric }
900435933ddSDimitry Andric 
SearchCallback(SearchFilter & filter,SymbolContext & context,Address * addr,bool containing)901435933ddSDimitry Andric Searcher::CallbackReturn RSScriptGroupBreakpointResolver::SearchCallback(
902435933ddSDimitry Andric     SearchFilter &filter, SymbolContext &context, Address *addr,
903435933ddSDimitry Andric     bool containing) {
904435933ddSDimitry Andric 
905435933ddSDimitry Andric   if (!m_breakpoint)
906435933ddSDimitry Andric     return eCallbackReturnContinue;
907435933ddSDimitry Andric 
908435933ddSDimitry Andric   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
909435933ddSDimitry Andric   ModuleSP &module = context.module_sp;
910435933ddSDimitry Andric 
911435933ddSDimitry Andric   if (!module || !IsRenderScriptScriptModule(module))
912435933ddSDimitry Andric     return Searcher::eCallbackReturnContinue;
913435933ddSDimitry Andric 
914435933ddSDimitry Andric   std::vector<std::string> names;
915435933ddSDimitry Andric   m_breakpoint->GetNames(names);
916435933ddSDimitry Andric   if (names.empty())
917435933ddSDimitry Andric     return eCallbackReturnContinue;
918435933ddSDimitry Andric 
919435933ddSDimitry Andric   for (auto &name : names) {
920435933ddSDimitry Andric     const RSScriptGroupDescriptorSP sg = FindScriptGroup(ConstString(name));
921435933ddSDimitry Andric     if (!sg) {
922435933ddSDimitry Andric       if (log)
923435933ddSDimitry Andric         log->Printf("%s: could not find script group for %s", __FUNCTION__,
924435933ddSDimitry Andric                     name.c_str());
925435933ddSDimitry Andric       continue;
926435933ddSDimitry Andric     }
927435933ddSDimitry Andric 
928435933ddSDimitry Andric     if (log)
929435933ddSDimitry Andric       log->Printf("%s: Found ScriptGroup for %s", __FUNCTION__, name.c_str());
930435933ddSDimitry Andric 
931435933ddSDimitry Andric     for (const RSScriptGroupDescriptor::Kernel &k : sg->m_kernels) {
932435933ddSDimitry Andric       if (log) {
933435933ddSDimitry Andric         log->Printf("%s: Adding breakpoint for %s", __FUNCTION__,
934435933ddSDimitry Andric                     k.m_name.AsCString());
935435933ddSDimitry Andric         log->Printf("%s: Kernel address 0x%" PRIx64, __FUNCTION__, k.m_addr);
936435933ddSDimitry Andric       }
937435933ddSDimitry Andric 
938435933ddSDimitry Andric       const lldb_private::Symbol *sym =
939435933ddSDimitry Andric           module->FindFirstSymbolWithNameAndType(k.m_name, eSymbolTypeCode);
940435933ddSDimitry Andric       if (!sym) {
941435933ddSDimitry Andric         if (log)
942435933ddSDimitry Andric           log->Printf("%s: Unable to find symbol for %s", __FUNCTION__,
943435933ddSDimitry Andric                       k.m_name.AsCString());
944435933ddSDimitry Andric         continue;
945435933ddSDimitry Andric       }
946435933ddSDimitry Andric 
947435933ddSDimitry Andric       if (log) {
948435933ddSDimitry Andric         log->Printf("%s: Found symbol name is %s", __FUNCTION__,
949435933ddSDimitry Andric                     sym->GetName().AsCString());
950435933ddSDimitry Andric       }
951435933ddSDimitry Andric 
952435933ddSDimitry Andric       auto address = sym->GetAddress();
953435933ddSDimitry Andric       if (!SkipPrologue(module, address)) {
954435933ddSDimitry Andric         if (log)
955435933ddSDimitry Andric           log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
956435933ddSDimitry Andric       }
957435933ddSDimitry Andric 
958435933ddSDimitry Andric       bool new_bp;
959435933ddSDimitry Andric       m_breakpoint->AddLocation(address, &new_bp);
960435933ddSDimitry Andric 
961435933ddSDimitry Andric       if (log)
962435933ddSDimitry Andric         log->Printf("%s: Placed %sbreakpoint on %s", __FUNCTION__,
963435933ddSDimitry Andric                     new_bp ? "new " : "", k.m_name.AsCString());
964435933ddSDimitry Andric 
9654ba319b5SDimitry Andric       // exit after placing the first breakpoint if we do not intend to stop on
9664ba319b5SDimitry Andric       // all kernels making up this script group
967435933ddSDimitry Andric       if (!m_stop_on_all)
968435933ddSDimitry Andric         break;
969435933ddSDimitry Andric     }
970435933ddSDimitry Andric   }
971435933ddSDimitry Andric 
972435933ddSDimitry Andric   return eCallbackReturnContinue;
973435933ddSDimitry Andric }
974435933ddSDimitry Andric 
Initialize()975435933ddSDimitry Andric void RenderScriptRuntime::Initialize() {
976435933ddSDimitry Andric   PluginManager::RegisterPlugin(GetPluginNameStatic(),
977435933ddSDimitry Andric                                 "RenderScript language support", CreateInstance,
9784bb0738eSEd Maste                                 GetCommandObject);
9791c3bbb01SEd Maste }
9801c3bbb01SEd Maste 
Terminate()981435933ddSDimitry Andric void RenderScriptRuntime::Terminate() {
9821c3bbb01SEd Maste   PluginManager::UnregisterPlugin(CreateInstance);
9831c3bbb01SEd Maste }
9841c3bbb01SEd Maste 
GetPluginNameStatic()985435933ddSDimitry Andric lldb_private::ConstString RenderScriptRuntime::GetPluginNameStatic() {
986435933ddSDimitry Andric   static ConstString plugin_name("renderscript");
987435933ddSDimitry Andric   return plugin_name;
9881c3bbb01SEd Maste }
9891c3bbb01SEd Maste 
9901c3bbb01SEd Maste RenderScriptRuntime::ModuleKind
GetModuleKind(const lldb::ModuleSP & module_sp)991435933ddSDimitry Andric RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
992435933ddSDimitry Andric   if (module_sp) {
993435933ddSDimitry Andric     if (IsRenderScriptScriptModule(module_sp))
9941c3bbb01SEd Maste       return eModuleKindKernelObj;
9951c3bbb01SEd Maste 
9961c3bbb01SEd Maste     // Is this the main RS runtime library
9971c3bbb01SEd Maste     const ConstString rs_lib("libRS.so");
998435933ddSDimitry Andric     if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
9991c3bbb01SEd Maste       return eModuleKindLibRS;
10001c3bbb01SEd Maste     }
10011c3bbb01SEd Maste 
10021c3bbb01SEd Maste     const ConstString rs_driverlib("libRSDriver.so");
1003435933ddSDimitry Andric     if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
10041c3bbb01SEd Maste       return eModuleKindDriver;
10051c3bbb01SEd Maste     }
10061c3bbb01SEd Maste 
10079f2f44ceSEd Maste     const ConstString rs_cpureflib("libRSCpuRef.so");
1008435933ddSDimitry Andric     if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
10091c3bbb01SEd Maste       return eModuleKindImpl;
10101c3bbb01SEd Maste     }
10111c3bbb01SEd Maste   }
10121c3bbb01SEd Maste   return eModuleKindIgnored;
10131c3bbb01SEd Maste }
10141c3bbb01SEd Maste 
IsRenderScriptModule(const lldb::ModuleSP & module_sp)1015435933ddSDimitry Andric bool RenderScriptRuntime::IsRenderScriptModule(
1016435933ddSDimitry Andric     const lldb::ModuleSP &module_sp) {
10171c3bbb01SEd Maste   return GetModuleKind(module_sp) != eModuleKindIgnored;
10181c3bbb01SEd Maste }
10191c3bbb01SEd Maste 
ModulesDidLoad(const ModuleList & module_list)1020435933ddSDimitry Andric void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
10214bb0738eSEd Maste   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
10221c3bbb01SEd Maste 
10231c3bbb01SEd Maste   size_t num_modules = module_list.GetSize();
1024435933ddSDimitry Andric   for (size_t i = 0; i < num_modules; i++) {
10251c3bbb01SEd Maste     auto mod = module_list.GetModuleAtIndex(i);
1026435933ddSDimitry Andric     if (IsRenderScriptModule(mod)) {
10271c3bbb01SEd Maste       LoadModule(mod);
10281c3bbb01SEd Maste     }
10291c3bbb01SEd Maste   }
10301c3bbb01SEd Maste }
10311c3bbb01SEd Maste 
10321c3bbb01SEd Maste //------------------------------------------------------------------
10331c3bbb01SEd Maste // PluginInterface protocol
10341c3bbb01SEd Maste //------------------------------------------------------------------
GetPluginName()1035435933ddSDimitry Andric lldb_private::ConstString RenderScriptRuntime::GetPluginName() {
10361c3bbb01SEd Maste   return GetPluginNameStatic();
10371c3bbb01SEd Maste }
10381c3bbb01SEd Maste 
GetPluginVersion()1039435933ddSDimitry Andric uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; }
10401c3bbb01SEd Maste 
IsVTableName(const char * name)1041435933ddSDimitry Andric bool RenderScriptRuntime::IsVTableName(const char *name) { return false; }
10421c3bbb01SEd Maste 
GetDynamicTypeAndAddress(ValueObject & in_value,lldb::DynamicValueType use_dynamic,TypeAndOrName & class_type_or_name,Address & address,Value::ValueType & value_type)1043435933ddSDimitry Andric bool RenderScriptRuntime::GetDynamicTypeAndAddress(
1044435933ddSDimitry Andric     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
10459f2f44ceSEd Maste     TypeAndOrName &class_type_or_name, Address &address,
1046435933ddSDimitry Andric     Value::ValueType &value_type) {
10471c3bbb01SEd Maste   return false;
10481c3bbb01SEd Maste }
10491c3bbb01SEd Maste 
10509f2f44ceSEd Maste TypeAndOrName
FixUpDynamicType(const TypeAndOrName & type_and_or_name,ValueObject & static_value)1051435933ddSDimitry Andric RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
1052435933ddSDimitry Andric                                       ValueObject &static_value) {
10539f2f44ceSEd Maste   return type_and_or_name;
10549f2f44ceSEd Maste }
10559f2f44ceSEd Maste 
CouldHaveDynamicValue(ValueObject & in_value)1056435933ddSDimitry Andric bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
10571c3bbb01SEd Maste   return false;
10581c3bbb01SEd Maste }
10591c3bbb01SEd Maste 
10601c3bbb01SEd Maste lldb::BreakpointResolverSP
CreateExceptionResolver(Breakpoint * bp,bool catch_bp,bool throw_bp)1061435933ddSDimitry Andric RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bp, bool catch_bp,
1062435933ddSDimitry Andric                                              bool throw_bp) {
10631c3bbb01SEd Maste   BreakpointResolverSP resolver_sp;
10641c3bbb01SEd Maste   return resolver_sp;
10651c3bbb01SEd Maste }
10661c3bbb01SEd Maste 
1067435933ddSDimitry Andric const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
1068435933ddSDimitry Andric     {
10691c3bbb01SEd Maste         // rsdScript
1070435933ddSDimitry Andric         {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
1071435933ddSDimitry Andric                           "NS0_7ScriptCEPKcS7_PKhjj",
1072435933ddSDimitry Andric          "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
1073435933ddSDimitry Andric          "7ScriptCEPKcS7_PKhmj",
1074435933ddSDimitry Andric          0, RenderScriptRuntime::eModuleKindDriver,
1075435933ddSDimitry Andric          &lldb_private::RenderScriptRuntime::CaptureScriptInit},
1076435933ddSDimitry Andric         {"rsdScriptInvokeForEachMulti",
1077435933ddSDimitry Andric          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1078435933ddSDimitry Andric          "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
1079435933ddSDimitry Andric          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1080435933ddSDimitry Andric          "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
1081435933ddSDimitry Andric          0, RenderScriptRuntime::eModuleKindDriver,
1082435933ddSDimitry Andric          &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
1083435933ddSDimitry Andric         {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
1084435933ddSDimitry Andric                                   "script7ContextEPKNS0_6ScriptEjPvj",
1085435933ddSDimitry Andric          "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
1086435933ddSDimitry Andric          "6ScriptEjPvm",
1087435933ddSDimitry Andric          0, RenderScriptRuntime::eModuleKindDriver,
1088435933ddSDimitry Andric          &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
10891c3bbb01SEd Maste 
10901c3bbb01SEd Maste         // rsdAllocation
1091435933ddSDimitry Andric         {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
1092435933ddSDimitry Andric                               "ontextEPNS0_10AllocationEb",
1093435933ddSDimitry Andric          "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
1094435933ddSDimitry Andric          "10AllocationEb",
1095435933ddSDimitry Andric          0, RenderScriptRuntime::eModuleKindDriver,
1096435933ddSDimitry Andric          &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
1097435933ddSDimitry Andric         {"rsdAllocationRead2D",
1098435933ddSDimitry Andric          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1099435933ddSDimitry Andric          "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1100435933ddSDimitry Andric          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1101435933ddSDimitry Andric          "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1102435933ddSDimitry Andric          0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1103435933ddSDimitry Andric         {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1104435933ddSDimitry Andric                                  "ript7ContextEPNS0_10AllocationE",
1105435933ddSDimitry Andric          "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1106435933ddSDimitry Andric          "10AllocationE",
1107435933ddSDimitry Andric          0, RenderScriptRuntime::eModuleKindDriver,
1108435933ddSDimitry Andric          &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
11091c3bbb01SEd Maste 
1110435933ddSDimitry Andric         // renderscript script groups
1111435933ddSDimitry Andric         {"rsdDebugHintScriptGroup2", "_ZN7android12renderscript21debugHintScrip"
1112435933ddSDimitry Andric                                      "tGroup2EPKcjPKPFvPK24RsExpandKernelDriver"
1113435933ddSDimitry Andric                                      "InfojjjEj",
1114435933ddSDimitry Andric          "_ZN7android12renderscript21debugHintScriptGroup2EPKcjPKPFvPK24RsExpan"
1115435933ddSDimitry Andric          "dKernelDriverInfojjjEj",
1116435933ddSDimitry Andric          0, RenderScriptRuntime::eModuleKindImpl,
1117435933ddSDimitry Andric          &lldb_private::RenderScriptRuntime::CaptureDebugHintScriptGroup2}};
11181c3bbb01SEd Maste 
1119435933ddSDimitry Andric const size_t RenderScriptRuntime::s_runtimeHookCount =
1120435933ddSDimitry Andric     sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
1121435933ddSDimitry Andric 
HookCallback(void * baton,StoppointCallbackContext * ctx,lldb::user_id_t break_id,lldb::user_id_t break_loc_id)1122435933ddSDimitry Andric bool RenderScriptRuntime::HookCallback(void *baton,
1123435933ddSDimitry Andric                                        StoppointCallbackContext *ctx,
1124435933ddSDimitry Andric                                        lldb::user_id_t break_id,
1125435933ddSDimitry Andric                                        lldb::user_id_t break_loc_id) {
1126435933ddSDimitry Andric   RuntimeHook *hook = (RuntimeHook *)baton;
1127435933ddSDimitry Andric   ExecutionContext exe_ctx(ctx->exe_ctx_ref);
11281c3bbb01SEd Maste 
11294bb0738eSEd Maste   RenderScriptRuntime *lang_rt =
1130435933ddSDimitry Andric       (RenderScriptRuntime *)exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1131435933ddSDimitry Andric           eLanguageTypeExtRenderScript);
11321c3bbb01SEd Maste 
1133435933ddSDimitry Andric   lang_rt->HookCallback(hook, exe_ctx);
11341c3bbb01SEd Maste 
11351c3bbb01SEd Maste   return false;
11361c3bbb01SEd Maste }
11371c3bbb01SEd Maste 
HookCallback(RuntimeHook * hook,ExecutionContext & exe_ctx)1138435933ddSDimitry Andric void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
1139435933ddSDimitry Andric                                        ExecutionContext &exe_ctx) {
11401c3bbb01SEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11411c3bbb01SEd Maste 
11421c3bbb01SEd Maste   if (log)
1143435933ddSDimitry Andric     log->Printf("%s - '%s'", __FUNCTION__, hook->defn->name);
11441c3bbb01SEd Maste 
1145435933ddSDimitry Andric   if (hook->defn->grabber) {
1146435933ddSDimitry Andric     (this->*(hook->defn->grabber))(hook, exe_ctx);
11471c3bbb01SEd Maste   }
11481c3bbb01SEd Maste }
11491c3bbb01SEd Maste 
CaptureDebugHintScriptGroup2(RuntimeHook * hook_info,ExecutionContext & context)1150435933ddSDimitry Andric void RenderScriptRuntime::CaptureDebugHintScriptGroup2(
1151435933ddSDimitry Andric     RuntimeHook *hook_info, ExecutionContext &context) {
11529f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11531c3bbb01SEd Maste 
1154435933ddSDimitry Andric   enum {
1155435933ddSDimitry Andric     eGroupName = 0,
1156435933ddSDimitry Andric     eGroupNameSize,
1157435933ddSDimitry Andric     eKernel,
1158435933ddSDimitry Andric     eKernelCount,
1159435933ddSDimitry Andric   };
1160435933ddSDimitry Andric 
1161435933ddSDimitry Andric   std::array<ArgItem, 4> args{{
1162435933ddSDimitry Andric       {ArgItem::ePointer, 0}, // const char         *groupName
1163435933ddSDimitry Andric       {ArgItem::eInt32, 0},   // const uint32_t      groupNameSize
1164435933ddSDimitry Andric       {ArgItem::ePointer, 0}, // const ExpandFuncTy *kernel
1165435933ddSDimitry Andric       {ArgItem::eInt32, 0},   // const uint32_t      kernelCount
1166435933ddSDimitry Andric   }};
1167435933ddSDimitry Andric 
1168435933ddSDimitry Andric   if (!GetArgs(context, args.data(), args.size())) {
1169435933ddSDimitry Andric     if (log)
1170435933ddSDimitry Andric       log->Printf("%s - Error while reading the function parameters",
1171435933ddSDimitry Andric                   __FUNCTION__);
1172435933ddSDimitry Andric     return;
1173435933ddSDimitry Andric   } else if (log) {
1174435933ddSDimitry Andric     log->Printf("%s - groupName    : 0x%" PRIx64, __FUNCTION__,
1175435933ddSDimitry Andric                 addr_t(args[eGroupName]));
1176435933ddSDimitry Andric     log->Printf("%s - groupNameSize: %" PRIu64, __FUNCTION__,
1177435933ddSDimitry Andric                 uint64_t(args[eGroupNameSize]));
1178435933ddSDimitry Andric     log->Printf("%s - kernel       : 0x%" PRIx64, __FUNCTION__,
1179435933ddSDimitry Andric                 addr_t(args[eKernel]));
1180435933ddSDimitry Andric     log->Printf("%s - kernelCount  : %" PRIu64, __FUNCTION__,
1181435933ddSDimitry Andric                 uint64_t(args[eKernelCount]));
1182435933ddSDimitry Andric   }
1183435933ddSDimitry Andric 
1184435933ddSDimitry Andric   // parse script group name
1185435933ddSDimitry Andric   ConstString group_name;
11869f2f44ceSEd Maste   {
11875517e702SDimitry Andric     Status err;
1188435933ddSDimitry Andric     const uint64_t len = uint64_t(args[eGroupNameSize]);
1189435933ddSDimitry Andric     std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]);
1190435933ddSDimitry Andric     m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err);
1191435933ddSDimitry Andric     buffer.get()[len] = '\0';
1192435933ddSDimitry Andric     if (!err.Success()) {
1193435933ddSDimitry Andric       if (log)
1194435933ddSDimitry Andric         log->Printf("Error reading scriptgroup name from target");
1195435933ddSDimitry Andric       return;
1196435933ddSDimitry Andric     } else {
1197435933ddSDimitry Andric       if (log)
1198435933ddSDimitry Andric         log->Printf("Extracted scriptgroup name %s", buffer.get());
1199435933ddSDimitry Andric     }
1200435933ddSDimitry Andric     // write back the script group name
1201435933ddSDimitry Andric     group_name.SetCString(buffer.get());
1202435933ddSDimitry Andric   }
1203435933ddSDimitry Andric 
1204435933ddSDimitry Andric   // create or access existing script group
1205435933ddSDimitry Andric   RSScriptGroupDescriptorSP group;
1206435933ddSDimitry Andric   {
1207435933ddSDimitry Andric     // search for existing script group
1208435933ddSDimitry Andric     for (auto sg : m_scriptGroups) {
1209435933ddSDimitry Andric       if (sg->m_name == group_name) {
1210435933ddSDimitry Andric         group = sg;
1211435933ddSDimitry Andric         break;
1212435933ddSDimitry Andric       }
1213435933ddSDimitry Andric     }
1214435933ddSDimitry Andric     if (!group) {
1215435933ddSDimitry Andric       group.reset(new RSScriptGroupDescriptor);
1216435933ddSDimitry Andric       group->m_name = group_name;
1217435933ddSDimitry Andric       m_scriptGroups.push_back(group);
1218435933ddSDimitry Andric     } else {
1219435933ddSDimitry Andric       // already have this script group
1220435933ddSDimitry Andric       if (log)
1221435933ddSDimitry Andric         log->Printf("Attempt to add duplicate script group %s",
1222435933ddSDimitry Andric                     group_name.AsCString());
1223435933ddSDimitry Andric       return;
1224435933ddSDimitry Andric     }
1225435933ddSDimitry Andric   }
1226435933ddSDimitry Andric   assert(group);
1227435933ddSDimitry Andric 
1228435933ddSDimitry Andric   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1229435933ddSDimitry Andric   std::vector<addr_t> kernels;
1230435933ddSDimitry Andric   // parse kernel addresses in script group
1231435933ddSDimitry Andric   for (uint64_t i = 0; i < uint64_t(args[eKernelCount]); ++i) {
1232435933ddSDimitry Andric     RSScriptGroupDescriptor::Kernel kernel;
1233435933ddSDimitry Andric     // extract script group kernel addresses from the target
1234435933ddSDimitry Andric     const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size;
1235435933ddSDimitry Andric     uint64_t kernel_addr = 0;
12365517e702SDimitry Andric     Status err;
1237435933ddSDimitry Andric     size_t read =
1238435933ddSDimitry Andric         m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err);
1239435933ddSDimitry Andric     if (!err.Success() || read != target_ptr_size) {
1240435933ddSDimitry Andric       if (log)
1241435933ddSDimitry Andric         log->Printf("Error parsing kernel address %" PRIu64 " in script group",
1242435933ddSDimitry Andric                     i);
1243435933ddSDimitry Andric       return;
1244435933ddSDimitry Andric     }
1245435933ddSDimitry Andric     if (log)
1246435933ddSDimitry Andric       log->Printf("Extracted scriptgroup kernel address - 0x%" PRIx64,
1247435933ddSDimitry Andric                   kernel_addr);
1248435933ddSDimitry Andric     kernel.m_addr = kernel_addr;
1249435933ddSDimitry Andric 
1250435933ddSDimitry Andric     // try to resolve the associated kernel name
1251435933ddSDimitry Andric     if (!ResolveKernelName(kernel.m_addr, kernel.m_name)) {
1252435933ddSDimitry Andric       if (log)
1253435933ddSDimitry Andric         log->Printf("Parsed scriptgroup kernel %" PRIu64 " - 0x%" PRIx64, i,
1254435933ddSDimitry Andric                     kernel_addr);
1255435933ddSDimitry Andric       return;
1256435933ddSDimitry Andric     }
1257435933ddSDimitry Andric 
1258435933ddSDimitry Andric     // try to find the non '.expand' function
1259435933ddSDimitry Andric     {
1260435933ddSDimitry Andric       const llvm::StringRef expand(".expand");
1261435933ddSDimitry Andric       const llvm::StringRef name_ref = kernel.m_name.GetStringRef();
1262435933ddSDimitry Andric       if (name_ref.endswith(expand)) {
1263435933ddSDimitry Andric         const ConstString base_kernel(name_ref.drop_back(expand.size()));
1264435933ddSDimitry Andric         // verify this function is a valid kernel
1265435933ddSDimitry Andric         if (IsKnownKernel(base_kernel)) {
1266435933ddSDimitry Andric           kernel.m_name = base_kernel;
1267435933ddSDimitry Andric           if (log)
1268435933ddSDimitry Andric             log->Printf("%s - found non expand version '%s'", __FUNCTION__,
1269435933ddSDimitry Andric                         base_kernel.GetCString());
1270435933ddSDimitry Andric         }
1271435933ddSDimitry Andric       }
1272435933ddSDimitry Andric     }
1273435933ddSDimitry Andric     // add to a list of script group kernels we know about
1274435933ddSDimitry Andric     group->m_kernels.push_back(kernel);
1275435933ddSDimitry Andric   }
1276435933ddSDimitry Andric 
1277435933ddSDimitry Andric   // Resolve any pending scriptgroup breakpoints
1278435933ddSDimitry Andric   {
1279435933ddSDimitry Andric     Target &target = m_process->GetTarget();
1280435933ddSDimitry Andric     const BreakpointList &list = target.GetBreakpointList();
1281435933ddSDimitry Andric     const size_t num_breakpoints = list.GetSize();
1282435933ddSDimitry Andric     if (log)
1283435933ddSDimitry Andric       log->Printf("Resolving %zu breakpoints", num_breakpoints);
1284435933ddSDimitry Andric     for (size_t i = 0; i < num_breakpoints; ++i) {
1285435933ddSDimitry Andric       const BreakpointSP bp = list.GetBreakpointAtIndex(i);
1286435933ddSDimitry Andric       if (bp) {
1287435933ddSDimitry Andric         if (bp->MatchesName(group_name.AsCString())) {
1288435933ddSDimitry Andric           if (log)
1289435933ddSDimitry Andric             log->Printf("Found breakpoint with name %s",
1290435933ddSDimitry Andric                         group_name.AsCString());
1291435933ddSDimitry Andric           bp->ResolveBreakpoint();
1292435933ddSDimitry Andric         }
1293435933ddSDimitry Andric       }
1294435933ddSDimitry Andric     }
1295435933ddSDimitry Andric   }
1296435933ddSDimitry Andric }
1297435933ddSDimitry Andric 
CaptureScriptInvokeForEachMulti(RuntimeHook * hook,ExecutionContext & exe_ctx)1298435933ddSDimitry Andric void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
1299435933ddSDimitry Andric     RuntimeHook *hook, ExecutionContext &exe_ctx) {
1300435933ddSDimitry Andric   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1301435933ddSDimitry Andric 
1302435933ddSDimitry Andric   enum {
13034bb0738eSEd Maste     eRsContext = 0,
13044bb0738eSEd Maste     eRsScript,
13054bb0738eSEd Maste     eRsSlot,
13064bb0738eSEd Maste     eRsAIns,
13074bb0738eSEd Maste     eRsInLen,
13084bb0738eSEd Maste     eRsAOut,
13094bb0738eSEd Maste     eRsUsr,
13104bb0738eSEd Maste     eRsUsrLen,
13114bb0738eSEd Maste     eRsSc,
13124bb0738eSEd Maste   };
13139f2f44ceSEd Maste 
13144bb0738eSEd Maste   std::array<ArgItem, 9> args{{
13154bb0738eSEd Maste       ArgItem{ArgItem::ePointer, 0}, // const Context       *rsc
13164bb0738eSEd Maste       ArgItem{ArgItem::ePointer, 0}, // Script              *s
13174bb0738eSEd Maste       ArgItem{ArgItem::eInt32, 0},   // uint32_t             slot
13184bb0738eSEd Maste       ArgItem{ArgItem::ePointer, 0}, // const Allocation   **aIns
13194bb0738eSEd Maste       ArgItem{ArgItem::eInt32, 0},   // size_t               inLen
13204bb0738eSEd Maste       ArgItem{ArgItem::ePointer, 0}, // Allocation          *aout
13214bb0738eSEd Maste       ArgItem{ArgItem::ePointer, 0}, // const void          *usr
13224bb0738eSEd Maste       ArgItem{ArgItem::eInt32, 0},   // size_t               usrLen
13234bb0738eSEd Maste       ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall  *sc
13244bb0738eSEd Maste   }};
13259f2f44ceSEd Maste 
1326435933ddSDimitry Andric   bool success = GetArgs(exe_ctx, &args[0], args.size());
1327435933ddSDimitry Andric   if (!success) {
13289f2f44ceSEd Maste     if (log)
1329435933ddSDimitry Andric       log->Printf("%s - Error while reading the function parameters",
1330435933ddSDimitry Andric                   __FUNCTION__);
13314bb0738eSEd Maste     return;
13329f2f44ceSEd Maste   }
13334bb0738eSEd Maste 
13344bb0738eSEd Maste   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
13355517e702SDimitry Andric   Status err;
13364bb0738eSEd Maste   std::vector<uint64_t> allocs;
13374bb0738eSEd Maste 
13384bb0738eSEd Maste   // traverse allocation list
1339435933ddSDimitry Andric   for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
13404bb0738eSEd Maste     // calculate offest to allocation pointer
13414bb0738eSEd Maste     const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
13424bb0738eSEd Maste 
1343435933ddSDimitry Andric     // Note: due to little endian layout, reading 32bits or 64bits into res
1344435933ddSDimitry Andric     // will give the correct results.
1345435933ddSDimitry Andric     uint64_t result = 0;
1346435933ddSDimitry Andric     size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
1347435933ddSDimitry Andric     if (read != target_ptr_size || !err.Success()) {
13484bb0738eSEd Maste       if (log)
1349435933ddSDimitry Andric         log->Printf(
1350435933ddSDimitry Andric             "%s - Error while reading allocation list argument %" PRIu64,
1351435933ddSDimitry Andric             __FUNCTION__, i);
1352435933ddSDimitry Andric     } else {
1353435933ddSDimitry Andric       allocs.push_back(result);
13544bb0738eSEd Maste     }
13554bb0738eSEd Maste   }
13564bb0738eSEd Maste 
13574bb0738eSEd Maste   // if there is an output allocation track it
1358435933ddSDimitry Andric   if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
1359435933ddSDimitry Andric     allocs.push_back(alloc_out);
13604bb0738eSEd Maste   }
13614bb0738eSEd Maste 
13624bb0738eSEd Maste   // for all allocations we have found
1363435933ddSDimitry Andric   for (const uint64_t alloc_addr : allocs) {
1364435933ddSDimitry Andric     AllocationDetails *alloc = LookUpAllocation(alloc_addr);
1365435933ddSDimitry Andric     if (!alloc)
1366435933ddSDimitry Andric       alloc = CreateAllocation(alloc_addr);
1367435933ddSDimitry Andric 
1368435933ddSDimitry Andric     if (alloc) {
13694bb0738eSEd Maste       // save the allocation address
1370435933ddSDimitry Andric       if (alloc->address.isValid()) {
13714bb0738eSEd Maste         // check the allocation address we already have matches
13724bb0738eSEd Maste         assert(*alloc->address.get() == alloc_addr);
1373435933ddSDimitry Andric       } else {
13744bb0738eSEd Maste         alloc->address = alloc_addr;
13754bb0738eSEd Maste       }
13764bb0738eSEd Maste 
13774bb0738eSEd Maste       // save the context
1378435933ddSDimitry Andric       if (log) {
1379435933ddSDimitry Andric         if (alloc->context.isValid() &&
1380435933ddSDimitry Andric             *alloc->context.get() != addr_t(args[eRsContext]))
1381435933ddSDimitry Andric           log->Printf("%s - Allocation used by multiple contexts",
1382435933ddSDimitry Andric                       __FUNCTION__);
13834bb0738eSEd Maste       }
13844bb0738eSEd Maste       alloc->context = addr_t(args[eRsContext]);
13854bb0738eSEd Maste     }
13864bb0738eSEd Maste   }
13874bb0738eSEd Maste 
13884bb0738eSEd Maste   // make sure we track this script object
1389435933ddSDimitry Andric   if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1390435933ddSDimitry Andric           LookUpScript(addr_t(args[eRsScript]), true)) {
1391435933ddSDimitry Andric     if (log) {
1392435933ddSDimitry Andric       if (script->context.isValid() &&
1393435933ddSDimitry Andric           *script->context.get() != addr_t(args[eRsContext]))
13944bb0738eSEd Maste         log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
13954bb0738eSEd Maste     }
13964bb0738eSEd Maste     script->context = addr_t(args[eRsContext]);
13974bb0738eSEd Maste   }
13981c3bbb01SEd Maste }
13991c3bbb01SEd Maste 
CaptureSetGlobalVar(RuntimeHook * hook,ExecutionContext & context)1400435933ddSDimitry Andric void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1401435933ddSDimitry Andric                                               ExecutionContext &context) {
14021c3bbb01SEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14031c3bbb01SEd Maste 
1404435933ddSDimitry Andric   enum {
14054bb0738eSEd Maste     eRsContext,
14064bb0738eSEd Maste     eRsScript,
14074bb0738eSEd Maste     eRsId,
14084bb0738eSEd Maste     eRsData,
14094bb0738eSEd Maste     eRsLength,
14104bb0738eSEd Maste   };
14111c3bbb01SEd Maste 
14124bb0738eSEd Maste   std::array<ArgItem, 5> args{{
14134bb0738eSEd Maste       ArgItem{ArgItem::ePointer, 0}, // eRsContext
14144bb0738eSEd Maste       ArgItem{ArgItem::ePointer, 0}, // eRsScript
14154bb0738eSEd Maste       ArgItem{ArgItem::eInt32, 0},   // eRsId
14164bb0738eSEd Maste       ArgItem{ArgItem::ePointer, 0}, // eRsData
14174bb0738eSEd Maste       ArgItem{ArgItem::eInt32, 0},   // eRsLength
14184bb0738eSEd Maste   }};
14191c3bbb01SEd Maste 
14204bb0738eSEd Maste   bool success = GetArgs(context, &args[0], args.size());
1421435933ddSDimitry Andric   if (!success) {
14229f2f44ceSEd Maste     if (log)
14234bb0738eSEd Maste       log->Printf("%s - error reading the function parameters.", __FUNCTION__);
14249f2f44ceSEd Maste     return;
14259f2f44ceSEd Maste   }
14261c3bbb01SEd Maste 
1427435933ddSDimitry Andric   if (log) {
1428435933ddSDimitry Andric     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1429435933ddSDimitry Andric                 ":%" PRIu64 "bytes.",
1430435933ddSDimitry Andric                 __FUNCTION__, uint64_t(args[eRsContext]),
1431435933ddSDimitry Andric                 uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
14324bb0738eSEd Maste                 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
14331c3bbb01SEd Maste 
14344bb0738eSEd Maste     addr_t script_addr = addr_t(args[eRsScript]);
1435435933ddSDimitry Andric     if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
14361c3bbb01SEd Maste       auto rsm = m_scriptMappings[script_addr];
1437435933ddSDimitry Andric       if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
14384bb0738eSEd Maste         auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1439435933ddSDimitry Andric         log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__,
1440435933ddSDimitry Andric                     rsg.m_name.AsCString(),
14411c3bbb01SEd Maste                     rsm->m_module->GetFileSpec().GetFilename().AsCString());
14421c3bbb01SEd Maste       }
14431c3bbb01SEd Maste     }
14441c3bbb01SEd Maste   }
14451c3bbb01SEd Maste }
14461c3bbb01SEd Maste 
CaptureAllocationInit(RuntimeHook * hook,ExecutionContext & exe_ctx)1447435933ddSDimitry Andric void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
1448435933ddSDimitry Andric                                                 ExecutionContext &exe_ctx) {
14491c3bbb01SEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14501c3bbb01SEd Maste 
1451435933ddSDimitry Andric   enum { eRsContext, eRsAlloc, eRsForceZero };
14521c3bbb01SEd Maste 
14534bb0738eSEd Maste   std::array<ArgItem, 3> args{{
14544bb0738eSEd Maste       ArgItem{ArgItem::ePointer, 0}, // eRsContext
14554bb0738eSEd Maste       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
14564bb0738eSEd Maste       ArgItem{ArgItem::eBool, 0},    // eRsForceZero
14574bb0738eSEd Maste   }};
14581c3bbb01SEd Maste 
1459435933ddSDimitry Andric   bool success = GetArgs(exe_ctx, &args[0], args.size());
1460435933ddSDimitry Andric   if (!success) {
14619f2f44ceSEd Maste     if (log)
1462435933ddSDimitry Andric       log->Printf("%s - error while reading the function parameters",
1463435933ddSDimitry Andric                   __FUNCTION__);
1464435933ddSDimitry Andric     return;
14659f2f44ceSEd Maste   }
14661c3bbb01SEd Maste 
14671c3bbb01SEd Maste   if (log)
1468435933ddSDimitry Andric     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1469435933ddSDimitry Andric                 __FUNCTION__, uint64_t(args[eRsContext]),
14704bb0738eSEd Maste                 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
14719f2f44ceSEd Maste 
1472435933ddSDimitry Andric   AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
14739f2f44ceSEd Maste   if (alloc)
14744bb0738eSEd Maste     alloc->context = uint64_t(args[eRsContext]);
14759f2f44ceSEd Maste }
14769f2f44ceSEd Maste 
CaptureAllocationDestroy(RuntimeHook * hook,ExecutionContext & exe_ctx)1477435933ddSDimitry Andric void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
1478435933ddSDimitry Andric                                                    ExecutionContext &exe_ctx) {
14799f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14809f2f44ceSEd Maste 
1481435933ddSDimitry Andric   enum {
14824bb0738eSEd Maste     eRsContext,
14834bb0738eSEd Maste     eRsAlloc,
14844bb0738eSEd Maste   };
14859f2f44ceSEd Maste 
14864bb0738eSEd Maste   std::array<ArgItem, 2> args{{
14874bb0738eSEd Maste       ArgItem{ArgItem::ePointer, 0}, // eRsContext
14884bb0738eSEd Maste       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
14894bb0738eSEd Maste   }};
14904bb0738eSEd Maste 
1491435933ddSDimitry Andric   bool success = GetArgs(exe_ctx, &args[0], args.size());
1492435933ddSDimitry Andric   if (!success) {
14939f2f44ceSEd Maste     if (log)
1494435933ddSDimitry Andric       log->Printf("%s - error while reading the function parameters.",
1495435933ddSDimitry Andric                   __FUNCTION__);
14964bb0738eSEd Maste     return;
14979f2f44ceSEd Maste   }
14989f2f44ceSEd Maste 
14999f2f44ceSEd Maste   if (log)
1500435933ddSDimitry Andric     log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1501435933ddSDimitry Andric                 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
15029f2f44ceSEd Maste 
1503435933ddSDimitry Andric   for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
15049f2f44ceSEd Maste     auto &allocation_ap = *iter; // get the unique pointer
1505435933ddSDimitry Andric     if (allocation_ap->address.isValid() &&
1506435933ddSDimitry Andric         *allocation_ap->address.get() == addr_t(args[eRsAlloc])) {
15079f2f44ceSEd Maste       m_allocations.erase(iter);
15089f2f44ceSEd Maste       if (log)
15094bb0738eSEd Maste         log->Printf("%s - deleted allocation entry.", __FUNCTION__);
15109f2f44ceSEd Maste       return;
15119f2f44ceSEd Maste     }
15129f2f44ceSEd Maste   }
15139f2f44ceSEd Maste 
15149f2f44ceSEd Maste   if (log)
15154bb0738eSEd Maste     log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
15161c3bbb01SEd Maste }
15171c3bbb01SEd Maste 
CaptureScriptInit(RuntimeHook * hook,ExecutionContext & exe_ctx)1518435933ddSDimitry Andric void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
1519435933ddSDimitry Andric                                             ExecutionContext &exe_ctx) {
15201c3bbb01SEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
15211c3bbb01SEd Maste 
15225517e702SDimitry Andric   Status err;
1523435933ddSDimitry Andric   Process *process = exe_ctx.GetProcessPtr();
15241c3bbb01SEd Maste 
1525435933ddSDimitry Andric   enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
15261c3bbb01SEd Maste 
1527435933ddSDimitry Andric   std::array<ArgItem, 4> args{
1528435933ddSDimitry Andric       {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
15294bb0738eSEd Maste        ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
1530435933ddSDimitry Andric   bool success = GetArgs(exe_ctx, &args[0], args.size());
1531435933ddSDimitry Andric   if (!success) {
15329f2f44ceSEd Maste     if (log)
1533435933ddSDimitry Andric       log->Printf("%s - error while reading the function parameters.",
1534435933ddSDimitry Andric                   __FUNCTION__);
15359f2f44ceSEd Maste     return;
15369f2f44ceSEd Maste   }
15379f2f44ceSEd Maste 
1538435933ddSDimitry Andric   std::string res_name;
1539435933ddSDimitry Andric   process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
1540435933ddSDimitry Andric   if (err.Fail()) {
15411c3bbb01SEd Maste     if (log)
1542435933ddSDimitry Andric       log->Printf("%s - error reading res_name: %s.", __FUNCTION__,
1543435933ddSDimitry Andric                   err.AsCString());
15441c3bbb01SEd Maste   }
15451c3bbb01SEd Maste 
1546435933ddSDimitry Andric   std::string cache_dir;
1547435933ddSDimitry Andric   process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
1548435933ddSDimitry Andric   if (err.Fail()) {
15491c3bbb01SEd Maste     if (log)
1550435933ddSDimitry Andric       log->Printf("%s - error reading cache_dir: %s.", __FUNCTION__,
1551435933ddSDimitry Andric                   err.AsCString());
15521c3bbb01SEd Maste   }
15531c3bbb01SEd Maste 
15541c3bbb01SEd Maste   if (log)
1555435933ddSDimitry Andric     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1556435933ddSDimitry Andric                 __FUNCTION__, uint64_t(args[eRsContext]),
1557435933ddSDimitry Andric                 uint64_t(args[eRsScript]), res_name.c_str(), cache_dir.c_str());
15581c3bbb01SEd Maste 
1559435933ddSDimitry Andric   if (res_name.size() > 0) {
15601c3bbb01SEd Maste     StreamString strm;
1561435933ddSDimitry Andric     strm.Printf("librs.%s.so", res_name.c_str());
15621c3bbb01SEd Maste 
15634bb0738eSEd Maste     ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1564435933ddSDimitry Andric     if (script) {
15659f2f44ceSEd Maste       script->type = ScriptDetails::eScriptC;
1566435933ddSDimitry Andric       script->cache_dir = cache_dir;
1567435933ddSDimitry Andric       script->res_name = res_name;
1568435933ddSDimitry Andric       script->shared_lib = strm.GetString();
15694bb0738eSEd Maste       script->context = addr_t(args[eRsContext]);
15709f2f44ceSEd Maste     }
15711c3bbb01SEd Maste 
15721c3bbb01SEd Maste     if (log)
1573435933ddSDimitry Andric       log->Printf("%s - '%s' tagged with context 0x%" PRIx64
1574435933ddSDimitry Andric                   " and script 0x%" PRIx64 ".",
1575435933ddSDimitry Andric                   __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1576435933ddSDimitry Andric                   uint64_t(args[eRsScript]));
1577435933ddSDimitry Andric   } else if (log) {
15784bb0738eSEd Maste     log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
15791c3bbb01SEd Maste   }
15801c3bbb01SEd Maste }
15811c3bbb01SEd Maste 
LoadRuntimeHooks(lldb::ModuleSP module,ModuleKind kind)1582435933ddSDimitry Andric void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1583435933ddSDimitry Andric                                            ModuleKind kind) {
15841c3bbb01SEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
15851c3bbb01SEd Maste 
1586435933ddSDimitry Andric   if (!module) {
15871c3bbb01SEd Maste     return;
15881c3bbb01SEd Maste   }
15891c3bbb01SEd Maste 
15909f2f44ceSEd Maste   Target &target = GetProcess()->GetTarget();
1591435933ddSDimitry Andric   const llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
15929f2f44ceSEd Maste 
1593435933ddSDimitry Andric   if (machine != llvm::Triple::ArchType::x86 &&
1594435933ddSDimitry Andric       machine != llvm::Triple::ArchType::arm &&
1595435933ddSDimitry Andric       machine != llvm::Triple::ArchType::aarch64 &&
1596435933ddSDimitry Andric       machine != llvm::Triple::ArchType::mipsel &&
1597435933ddSDimitry Andric       machine != llvm::Triple::ArchType::mips64el &&
1598435933ddSDimitry Andric       machine != llvm::Triple::ArchType::x86_64) {
15991c3bbb01SEd Maste     if (log)
16004bb0738eSEd Maste       log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
16011c3bbb01SEd Maste     return;
16021c3bbb01SEd Maste   }
16031c3bbb01SEd Maste 
1604435933ddSDimitry Andric   const uint32_t target_ptr_size =
1605435933ddSDimitry Andric       target.GetArchitecture().GetAddressByteSize();
16061c3bbb01SEd Maste 
1607435933ddSDimitry Andric   std::array<bool, s_runtimeHookCount> hook_placed;
1608435933ddSDimitry Andric   hook_placed.fill(false);
1609435933ddSDimitry Andric 
1610435933ddSDimitry Andric   for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
16111c3bbb01SEd Maste     const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1612435933ddSDimitry Andric     if (hook_defn->kind != kind) {
16131c3bbb01SEd Maste       continue;
16141c3bbb01SEd Maste     }
16151c3bbb01SEd Maste 
1616435933ddSDimitry Andric     const char *symbol_name = (target_ptr_size == 4)
1617435933ddSDimitry Andric                                   ? hook_defn->symbol_name_m32
1618435933ddSDimitry Andric                                   : hook_defn->symbol_name_m64;
16199f2f44ceSEd Maste 
1620435933ddSDimitry Andric     const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1621435933ddSDimitry Andric         ConstString(symbol_name), eSymbolTypeCode);
1622435933ddSDimitry Andric     if (!sym) {
1623435933ddSDimitry Andric       if (log) {
16244bb0738eSEd Maste         log->Printf("%s - symbol '%s' related to the function %s not found",
16254bb0738eSEd Maste                     __FUNCTION__, symbol_name, hook_defn->name);
16269f2f44ceSEd Maste       }
16279f2f44ceSEd Maste       continue;
16289f2f44ceSEd Maste     }
16291c3bbb01SEd Maste 
16301c3bbb01SEd Maste     addr_t addr = sym->GetLoadAddress(&target);
1631435933ddSDimitry Andric     if (addr == LLDB_INVALID_ADDRESS) {
16321c3bbb01SEd Maste       if (log)
1633435933ddSDimitry Andric         log->Printf("%s - unable to resolve the address of hook function '%s' "
1634435933ddSDimitry Andric                     "with symbol '%s'.",
16354bb0738eSEd Maste                     __FUNCTION__, hook_defn->name, symbol_name);
16361c3bbb01SEd Maste       continue;
1637435933ddSDimitry Andric     } else {
16389f2f44ceSEd Maste       if (log)
16394bb0738eSEd Maste         log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
16404bb0738eSEd Maste                     __FUNCTION__, hook_defn->name, addr);
16419f2f44ceSEd Maste     }
16421c3bbb01SEd Maste 
16431c3bbb01SEd Maste     RuntimeHookSP hook(new RuntimeHook());
16441c3bbb01SEd Maste     hook->address = addr;
16451c3bbb01SEd Maste     hook->defn = hook_defn;
16461c3bbb01SEd Maste     hook->bp_sp = target.CreateBreakpoint(addr, true, false);
16471c3bbb01SEd Maste     hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
16481c3bbb01SEd Maste     m_runtimeHooks[addr] = hook;
1649435933ddSDimitry Andric     if (log) {
1650435933ddSDimitry Andric       log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64
1651435933ddSDimitry Andric                   " at 0x%" PRIx64 ".",
1652435933ddSDimitry Andric                   __FUNCTION__, hook_defn->name,
1653435933ddSDimitry Andric                   module->GetFileSpec().GetFilename().AsCString(),
16544bb0738eSEd Maste                   (uint64_t)hook_defn->version, (uint64_t)addr);
16551c3bbb01SEd Maste     }
1656435933ddSDimitry Andric     hook_placed[idx] = true;
1657435933ddSDimitry Andric   }
1658435933ddSDimitry Andric 
1659435933ddSDimitry Andric   // log any unhooked function
1660435933ddSDimitry Andric   if (log) {
1661435933ddSDimitry Andric     for (size_t i = 0; i < hook_placed.size(); ++i) {
1662435933ddSDimitry Andric       if (hook_placed[i])
1663435933ddSDimitry Andric         continue;
1664435933ddSDimitry Andric       const HookDefn &hook_defn = s_runtimeHookDefns[i];
1665435933ddSDimitry Andric       if (hook_defn.kind != kind)
1666435933ddSDimitry Andric         continue;
1667435933ddSDimitry Andric       log->Printf("%s - function %s was not hooked", __FUNCTION__,
1668435933ddSDimitry Andric                   hook_defn.name);
1669435933ddSDimitry Andric     }
16701c3bbb01SEd Maste   }
16711c3bbb01SEd Maste }
16721c3bbb01SEd Maste 
FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp)1673435933ddSDimitry Andric void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
16741c3bbb01SEd Maste   if (!rsmodule_sp)
16751c3bbb01SEd Maste     return;
16761c3bbb01SEd Maste 
16771c3bbb01SEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
16781c3bbb01SEd Maste 
16791c3bbb01SEd Maste   const ModuleSP module = rsmodule_sp->m_module;
16801c3bbb01SEd Maste   const FileSpec &file = module->GetPlatformFileSpec();
16811c3bbb01SEd Maste 
16824ba319b5SDimitry Andric   // Iterate over all of the scripts that we currently know of. Note: We cant
16834ba319b5SDimitry Andric   // push or pop to m_scripts here or it may invalidate rs_script.
1684435933ddSDimitry Andric   for (const auto &rs_script : m_scripts) {
16859f2f44ceSEd Maste     // Extract the expected .so file path for this script.
1686435933ddSDimitry Andric     std::string shared_lib;
1687435933ddSDimitry Andric     if (!rs_script->shared_lib.get(shared_lib))
16889f2f44ceSEd Maste       continue;
16899f2f44ceSEd Maste 
16909f2f44ceSEd Maste     // Only proceed if the module that has loaded corresponds to this script.
1691435933ddSDimitry Andric     if (file.GetFilename() != ConstString(shared_lib.c_str()))
16929f2f44ceSEd Maste       continue;
16939f2f44ceSEd Maste 
16949f2f44ceSEd Maste     // Obtain the script address which we use as a key.
16959f2f44ceSEd Maste     lldb::addr_t script;
16969f2f44ceSEd Maste     if (!rs_script->script.get(script))
16979f2f44ceSEd Maste       continue;
16989f2f44ceSEd Maste 
16999f2f44ceSEd Maste     // If we have a script mapping for the current script.
1700435933ddSDimitry Andric     if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
17019f2f44ceSEd Maste       // if the module we have stored is different to the one we just received.
1702435933ddSDimitry Andric       if (m_scriptMappings[script] != rsmodule_sp) {
17031c3bbb01SEd Maste         if (log)
1704435933ddSDimitry Andric           log->Printf(
1705435933ddSDimitry Andric               "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1706435933ddSDimitry Andric               __FUNCTION__, (uint64_t)script,
1707435933ddSDimitry Andric               rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
17081c3bbb01SEd Maste       }
17091c3bbb01SEd Maste     }
17109f2f44ceSEd Maste     // We don't have a script mapping for the current script.
1711435933ddSDimitry Andric     else {
17129f2f44ceSEd Maste       // Obtain the script resource name.
1713435933ddSDimitry Andric       std::string res_name;
1714435933ddSDimitry Andric       if (rs_script->res_name.get(res_name))
17159f2f44ceSEd Maste         // Set the modules resource name.
1716435933ddSDimitry Andric         rsmodule_sp->m_resname = res_name;
17179f2f44ceSEd Maste       // Add Script/Module pair to map.
17189f2f44ceSEd Maste       m_scriptMappings[script] = rsmodule_sp;
17191c3bbb01SEd Maste       if (log)
1720435933ddSDimitry Andric         log->Printf(
1721435933ddSDimitry Andric             "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1722435933ddSDimitry Andric             __FUNCTION__, (uint64_t)script,
1723435933ddSDimitry Andric             rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
17241c3bbb01SEd Maste     }
17251c3bbb01SEd Maste   }
17261c3bbb01SEd Maste }
17271c3bbb01SEd Maste 
1728435933ddSDimitry Andric // Uses the Target API to evaluate the expression passed as a parameter to the
1729435933ddSDimitry Andric // function The result of that expression is returned an unsigned 64 bit int,
1730435933ddSDimitry Andric // via the result* parameter. Function returns true on success, and false on
1731435933ddSDimitry Andric // failure
EvalRSExpression(const char * expr,StackFrame * frame_ptr,uint64_t * result)1732435933ddSDimitry Andric bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1733435933ddSDimitry Andric                                            StackFrame *frame_ptr,
1734435933ddSDimitry Andric                                            uint64_t *result) {
17359f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
17369f2f44ceSEd Maste   if (log)
1737435933ddSDimitry Andric     log->Printf("%s(%s)", __FUNCTION__, expr);
17389f2f44ceSEd Maste 
17399f2f44ceSEd Maste   ValueObjectSP expr_result;
17404bb0738eSEd Maste   EvaluateExpressionOptions options;
17414bb0738eSEd Maste   options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
17429f2f44ceSEd Maste   // Perform the actual expression evaluation
1743435933ddSDimitry Andric   auto &target = GetProcess()->GetTarget();
1744435933ddSDimitry Andric   target.EvaluateExpression(expr, frame_ptr, expr_result, options);
17459f2f44ceSEd Maste 
1746435933ddSDimitry Andric   if (!expr_result) {
17479f2f44ceSEd Maste     if (log)
17484bb0738eSEd Maste       log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
17499f2f44ceSEd Maste     return false;
17509f2f44ceSEd Maste   }
17519f2f44ceSEd Maste 
17529f2f44ceSEd Maste   // The result of the expression is invalid
1753435933ddSDimitry Andric   if (!expr_result->GetError().Success()) {
17545517e702SDimitry Andric     Status err = expr_result->GetError();
1755435933ddSDimitry Andric     // Expression returned is void, so this is actually a success
1756435933ddSDimitry Andric     if (err.GetError() == UserExpression::kNoResult) {
17579f2f44ceSEd Maste       if (log)
17584bb0738eSEd Maste         log->Printf("%s - expression returned void.", __FUNCTION__);
17599f2f44ceSEd Maste 
17609f2f44ceSEd Maste       result = nullptr;
17619f2f44ceSEd Maste       return true;
17629f2f44ceSEd Maste     }
17639f2f44ceSEd Maste 
17649f2f44ceSEd Maste     if (log)
17654bb0738eSEd Maste       log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
17664bb0738eSEd Maste                   err.AsCString());
17679f2f44ceSEd Maste     return false;
17689f2f44ceSEd Maste   }
17699f2f44ceSEd Maste 
17709f2f44ceSEd Maste   bool success = false;
1771435933ddSDimitry Andric   // We only read the result as an uint32_t.
1772435933ddSDimitry Andric   *result = expr_result->GetValueAsUnsigned(0, &success);
17739f2f44ceSEd Maste 
1774435933ddSDimitry Andric   if (!success) {
17759f2f44ceSEd Maste     if (log)
1776435933ddSDimitry Andric       log->Printf("%s - couldn't convert expression result to uint32_t",
1777435933ddSDimitry Andric                   __FUNCTION__);
17789f2f44ceSEd Maste     return false;
17799f2f44ceSEd Maste   }
17809f2f44ceSEd Maste 
17819f2f44ceSEd Maste   return true;
17829f2f44ceSEd Maste }
17839f2f44ceSEd Maste 
1784435933ddSDimitry Andric namespace {
17854bb0738eSEd Maste // Used to index expression format strings
1786435933ddSDimitry Andric enum ExpressionStrings {
17874bb0738eSEd Maste   eExprGetOffsetPtr = 0,
17884bb0738eSEd Maste   eExprAllocGetType,
17894bb0738eSEd Maste   eExprTypeDimX,
17904bb0738eSEd Maste   eExprTypeDimY,
17914bb0738eSEd Maste   eExprTypeDimZ,
17924bb0738eSEd Maste   eExprTypeElemPtr,
17934bb0738eSEd Maste   eExprElementType,
17944bb0738eSEd Maste   eExprElementKind,
17954bb0738eSEd Maste   eExprElementVec,
17964bb0738eSEd Maste   eExprElementFieldCount,
17974bb0738eSEd Maste   eExprSubelementsId,
17984bb0738eSEd Maste   eExprSubelementsName,
17994bb0738eSEd Maste   eExprSubelementsArrSize,
18004bb0738eSEd Maste 
1801435933ddSDimitry Andric   _eExprLast // keep at the end, implicit size of the array runtime_expressions
18024bb0738eSEd Maste };
18034bb0738eSEd Maste 
18049f2f44ceSEd Maste // max length of an expanded expression
18054bb0738eSEd Maste const int jit_max_expr_size = 512;
18069f2f44ceSEd Maste 
18079f2f44ceSEd Maste // Retrieve the string to JIT for the given expression
18086bc11b14SDimitry Andric #define JIT_TEMPLATE_CONTEXT "void* ctxt = (void*)rsDebugGetContextWrapper(0x%" PRIx64 "); "
JITTemplate(ExpressionStrings e)1809435933ddSDimitry Andric const char *JITTemplate(ExpressionStrings e) {
18104bb0738eSEd Maste   // Format strings containing the expressions we may need to evaluate.
1811435933ddSDimitry Andric   static std::array<const char *, _eExprLast> runtime_expressions = {
1812435933ddSDimitry Andric       {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1813435933ddSDimitry Andric        "(int*)_"
1814435933ddSDimitry Andric        "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1815435933ddSDimitry Andric        "CubemapFace"
18166bc11b14SDimitry Andric        "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)", // eExprGetOffsetPtr
18179f2f44ceSEd Maste 
18184bb0738eSEd Maste        // Type* rsaAllocationGetType(Context*, Allocation*)
18196bc11b14SDimitry Andric        JIT_TEMPLATE_CONTEXT "(void*)rsaAllocationGetType(ctxt, 0x%" PRIx64 ")", // eExprAllocGetType
18209f2f44ceSEd Maste 
1821435933ddSDimitry Andric        // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
1822435933ddSDimitry Andric        // data in the following way mHal.state.dimX; mHal.state.dimY;
18234ba319b5SDimitry Andric        // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement;
18244ba319b5SDimitry Andric        // into typeData Need to specify 32 or 64 bit for uint_t since this
18254ba319b5SDimitry Andric        // differs between devices
18266bc11b14SDimitry Andric        JIT_TEMPLATE_CONTEXT
18276bc11b14SDimitry Andric        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
18286bc11b14SDimitry Andric        ", 0x%" PRIx64 ", data, 6); data[0]", // eExprTypeDimX
18296bc11b14SDimitry Andric        JIT_TEMPLATE_CONTEXT
18306bc11b14SDimitry Andric        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
18316bc11b14SDimitry Andric        ", 0x%" PRIx64 ", data, 6); data[1]", // eExprTypeDimY
18326bc11b14SDimitry Andric        JIT_TEMPLATE_CONTEXT
18336bc11b14SDimitry Andric        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
18346bc11b14SDimitry Andric        ", 0x%" PRIx64 ", data, 6); data[2]", // eExprTypeDimZ
18356bc11b14SDimitry Andric        JIT_TEMPLATE_CONTEXT
18366bc11b14SDimitry Andric        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
18376bc11b14SDimitry Andric        ", 0x%" PRIx64 ", data, 6); data[5]", // eExprTypeElemPtr
18389f2f44ceSEd Maste 
18394bb0738eSEd Maste        // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1840435933ddSDimitry Andric        // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1841435933ddSDimitry Andric        // elemData
18426bc11b14SDimitry Andric        JIT_TEMPLATE_CONTEXT
18436bc11b14SDimitry Andric        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
18446bc11b14SDimitry Andric        ", 0x%" PRIx64 ", data, 5); data[0]", // eExprElementType
18456bc11b14SDimitry Andric        JIT_TEMPLATE_CONTEXT
18466bc11b14SDimitry Andric        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
18476bc11b14SDimitry Andric        ", 0x%" PRIx64 ", data, 5); data[1]", // eExprElementKind
18486bc11b14SDimitry Andric        JIT_TEMPLATE_CONTEXT
18496bc11b14SDimitry Andric        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
18506bc11b14SDimitry Andric        ", 0x%" PRIx64 ", data, 5); data[3]", // eExprElementVec
18516bc11b14SDimitry Andric        JIT_TEMPLATE_CONTEXT
18526bc11b14SDimitry Andric        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
18536bc11b14SDimitry Andric        ", 0x%" PRIx64 ", data, 5); data[4]", // eExprElementFieldCount
18544bb0738eSEd Maste 
1855435933ddSDimitry Andric        // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
1856435933ddSDimitry Andric        // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1857435933ddSDimitry Andric        // Needed for Allocations of structs to gather details about
1858435933ddSDimitry Andric        // fields/Subelements Element* of field
18596bc11b14SDimitry Andric        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1860435933ddSDimitry Andric        "]; size_t arr_size[%" PRIu32 "];"
18616bc11b14SDimitry Andric        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
18626bc11b14SDimitry Andric        ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]", // eExprSubelementsId
18634bb0738eSEd Maste 
18644bb0738eSEd Maste        // Name of field
18656bc11b14SDimitry Andric        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1866435933ddSDimitry Andric        "]; size_t arr_size[%" PRIu32 "];"
18676bc11b14SDimitry Andric        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
18686bc11b14SDimitry Andric        ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]", // eExprSubelementsName
18694bb0738eSEd Maste 
18704bb0738eSEd Maste        // Array size of field
18716bc11b14SDimitry Andric        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1872435933ddSDimitry Andric        "]; size_t arr_size[%" PRIu32 "];"
18736bc11b14SDimitry Andric        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
18746bc11b14SDimitry Andric        ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}}; // eExprSubelementsArrSize
18754bb0738eSEd Maste 
1876435933ddSDimitry Andric   return runtime_expressions[e];
18779f2f44ceSEd Maste }
18784bb0738eSEd Maste } // end of the anonymous namespace
18799f2f44ceSEd Maste 
18804ba319b5SDimitry Andric // JITs the RS runtime for the internal data pointer of an allocation. Is
18814ba319b5SDimitry Andric // passed x,y,z coordinates for the pointer to a specific element. Then sets
18824ba319b5SDimitry Andric // the data_ptr member in Allocation with the result. Returns true on success,
18834ba319b5SDimitry Andric // false otherwise
JITDataPointer(AllocationDetails * alloc,StackFrame * frame_ptr,uint32_t x,uint32_t y,uint32_t z)1884435933ddSDimitry Andric bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1885435933ddSDimitry Andric                                          StackFrame *frame_ptr, uint32_t x,
1886435933ddSDimitry Andric                                          uint32_t y, uint32_t z) {
18879f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
18889f2f44ceSEd Maste 
1889435933ddSDimitry Andric   if (!alloc->address.isValid()) {
18909f2f44ceSEd Maste     if (log)
18914bb0738eSEd Maste       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
18929f2f44ceSEd Maste     return false;
18939f2f44ceSEd Maste   }
18949f2f44ceSEd Maste 
1895435933ddSDimitry Andric   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
1896435933ddSDimitry Andric   char expr_buf[jit_max_expr_size];
18979f2f44ceSEd Maste 
1898435933ddSDimitry Andric   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1899435933ddSDimitry Andric                          *alloc->address.get(), x, y, z);
1900435933ddSDimitry Andric   if (written < 0) {
19019f2f44ceSEd Maste     if (log)
19024bb0738eSEd Maste       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
19039f2f44ceSEd Maste     return false;
1904435933ddSDimitry Andric   } else if (written >= jit_max_expr_size) {
19059f2f44ceSEd Maste     if (log)
19064bb0738eSEd Maste       log->Printf("%s - expression too long.", __FUNCTION__);
19079f2f44ceSEd Maste     return false;
19089f2f44ceSEd Maste   }
19099f2f44ceSEd Maste 
19109f2f44ceSEd Maste   uint64_t result = 0;
1911435933ddSDimitry Andric   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
19129f2f44ceSEd Maste     return false;
19139f2f44ceSEd Maste 
1914435933ddSDimitry Andric   addr_t data_ptr = static_cast<lldb::addr_t>(result);
1915435933ddSDimitry Andric   alloc->data_ptr = data_ptr;
19169f2f44ceSEd Maste 
19179f2f44ceSEd Maste   return true;
19189f2f44ceSEd Maste }
19199f2f44ceSEd Maste 
19209f2f44ceSEd Maste // JITs the RS runtime for the internal pointer to the RS Type of an allocation
1921435933ddSDimitry Andric // Then sets the type_ptr member in Allocation with the result. Returns true on
1922435933ddSDimitry Andric // success, false otherwise
JITTypePointer(AllocationDetails * alloc,StackFrame * frame_ptr)1923435933ddSDimitry Andric bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1924435933ddSDimitry Andric                                          StackFrame *frame_ptr) {
19259f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
19269f2f44ceSEd Maste 
1927435933ddSDimitry Andric   if (!alloc->address.isValid() || !alloc->context.isValid()) {
19289f2f44ceSEd Maste     if (log)
19294bb0738eSEd Maste       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
19309f2f44ceSEd Maste     return false;
19319f2f44ceSEd Maste   }
19329f2f44ceSEd Maste 
1933435933ddSDimitry Andric   const char *fmt_str = JITTemplate(eExprAllocGetType);
1934435933ddSDimitry Andric   char expr_buf[jit_max_expr_size];
19359f2f44ceSEd Maste 
1936435933ddSDimitry Andric   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1937435933ddSDimitry Andric                          *alloc->context.get(), *alloc->address.get());
1938435933ddSDimitry Andric   if (written < 0) {
19399f2f44ceSEd Maste     if (log)
19404bb0738eSEd Maste       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
19419f2f44ceSEd Maste     return false;
1942435933ddSDimitry Andric   } else if (written >= jit_max_expr_size) {
19439f2f44ceSEd Maste     if (log)
19444bb0738eSEd Maste       log->Printf("%s - expression too long.", __FUNCTION__);
19459f2f44ceSEd Maste     return false;
19469f2f44ceSEd Maste   }
19479f2f44ceSEd Maste 
19489f2f44ceSEd Maste   uint64_t result = 0;
1949435933ddSDimitry Andric   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
19509f2f44ceSEd Maste     return false;
19519f2f44ceSEd Maste 
19529f2f44ceSEd Maste   addr_t type_ptr = static_cast<lldb::addr_t>(result);
1953435933ddSDimitry Andric   alloc->type_ptr = type_ptr;
19549f2f44ceSEd Maste 
19559f2f44ceSEd Maste   return true;
19569f2f44ceSEd Maste }
19579f2f44ceSEd Maste 
1958435933ddSDimitry Andric // JITs the RS runtime for information about the dimensions and type of an
19594ba319b5SDimitry Andric // allocation Then sets dimension and element_ptr members in Allocation with
19604ba319b5SDimitry Andric // the result. Returns true on success, false otherwise
JITTypePacked(AllocationDetails * alloc,StackFrame * frame_ptr)1961435933ddSDimitry Andric bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1962435933ddSDimitry Andric                                         StackFrame *frame_ptr) {
19639f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
19649f2f44ceSEd Maste 
1965435933ddSDimitry Andric   if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
19669f2f44ceSEd Maste     if (log)
19674bb0738eSEd Maste       log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
19689f2f44ceSEd Maste     return false;
19699f2f44ceSEd Maste   }
19709f2f44ceSEd Maste 
19719f2f44ceSEd Maste   // Expression is different depending on if device is 32 or 64 bit
1972435933ddSDimitry Andric   uint32_t target_ptr_size =
1973435933ddSDimitry Andric       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
1974435933ddSDimitry Andric   const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
19759f2f44ceSEd Maste 
19769f2f44ceSEd Maste   // We want 4 elements from packed data
19774bb0738eSEd Maste   const uint32_t num_exprs = 4;
1978435933ddSDimitry Andric   assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) &&
1979435933ddSDimitry Andric          "Invalid number of expressions");
19809f2f44ceSEd Maste 
1981435933ddSDimitry Andric   char expr_bufs[num_exprs][jit_max_expr_size];
19829f2f44ceSEd Maste   uint64_t results[num_exprs];
19839f2f44ceSEd Maste 
1984435933ddSDimitry Andric   for (uint32_t i = 0; i < num_exprs; ++i) {
1985435933ddSDimitry Andric     const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
19866bc11b14SDimitry Andric     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str,
19876bc11b14SDimitry Andric                            *alloc->context.get(), bits, *alloc->type_ptr.get());
1988435933ddSDimitry Andric     if (written < 0) {
19899f2f44ceSEd Maste       if (log)
19904bb0738eSEd Maste         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
19919f2f44ceSEd Maste       return false;
1992435933ddSDimitry Andric     } else if (written >= jit_max_expr_size) {
19939f2f44ceSEd Maste       if (log)
19944bb0738eSEd Maste         log->Printf("%s - expression too long.", __FUNCTION__);
19959f2f44ceSEd Maste       return false;
19969f2f44ceSEd Maste     }
19979f2f44ceSEd Maste 
19989f2f44ceSEd Maste     // Perform expression evaluation
1999435933ddSDimitry Andric     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
20009f2f44ceSEd Maste       return false;
20019f2f44ceSEd Maste   }
20029f2f44ceSEd Maste 
20039f2f44ceSEd Maste   // Assign results to allocation members
20049f2f44ceSEd Maste   AllocationDetails::Dimension dims;
20059f2f44ceSEd Maste   dims.dim_1 = static_cast<uint32_t>(results[0]);
20069f2f44ceSEd Maste   dims.dim_2 = static_cast<uint32_t>(results[1]);
20079f2f44ceSEd Maste   dims.dim_3 = static_cast<uint32_t>(results[2]);
2008435933ddSDimitry Andric   alloc->dimension = dims;
20099f2f44ceSEd Maste 
2010435933ddSDimitry Andric   addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
2011435933ddSDimitry Andric   alloc->element.element_ptr = element_ptr;
20129f2f44ceSEd Maste 
20139f2f44ceSEd Maste   if (log)
2014435933ddSDimitry Andric     log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
2015435933ddSDimitry Andric                 ") Element*: 0x%" PRIx64 ".",
2016435933ddSDimitry Andric                 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
20179f2f44ceSEd Maste 
20189f2f44ceSEd Maste   return true;
20199f2f44ceSEd Maste }
20209f2f44ceSEd Maste 
2021435933ddSDimitry Andric // JITs the RS runtime for information about the Element of an allocation Then
2022435933ddSDimitry Andric // sets type, type_vec_size, field_count and type_kind members in Element with
2023435933ddSDimitry Andric // the result. Returns true on success, false otherwise
JITElementPacked(Element & elem,const lldb::addr_t context,StackFrame * frame_ptr)2024435933ddSDimitry Andric bool RenderScriptRuntime::JITElementPacked(Element &elem,
2025435933ddSDimitry Andric                                            const lldb::addr_t context,
2026435933ddSDimitry Andric                                            StackFrame *frame_ptr) {
20279f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
20289f2f44ceSEd Maste 
2029435933ddSDimitry Andric   if (!elem.element_ptr.isValid()) {
20309f2f44ceSEd Maste     if (log)
20314bb0738eSEd Maste       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
20329f2f44ceSEd Maste     return false;
20339f2f44ceSEd Maste   }
20349f2f44ceSEd Maste 
20359f2f44ceSEd Maste   // We want 4 elements from packed data
20364bb0738eSEd Maste   const uint32_t num_exprs = 4;
2037435933ddSDimitry Andric   assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) &&
2038435933ddSDimitry Andric          "Invalid number of expressions");
20399f2f44ceSEd Maste 
2040435933ddSDimitry Andric   char expr_bufs[num_exprs][jit_max_expr_size];
20419f2f44ceSEd Maste   uint64_t results[num_exprs];
20429f2f44ceSEd Maste 
2043435933ddSDimitry Andric   for (uint32_t i = 0; i < num_exprs; i++) {
2044435933ddSDimitry Andric     const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
2045435933ddSDimitry Andric     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
2046435933ddSDimitry Andric                            *elem.element_ptr.get());
2047435933ddSDimitry Andric     if (written < 0) {
20489f2f44ceSEd Maste       if (log)
20494bb0738eSEd Maste         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
20509f2f44ceSEd Maste       return false;
2051435933ddSDimitry Andric     } else if (written >= jit_max_expr_size) {
20529f2f44ceSEd Maste       if (log)
20534bb0738eSEd Maste         log->Printf("%s - expression too long.", __FUNCTION__);
20549f2f44ceSEd Maste       return false;
20559f2f44ceSEd Maste     }
20569f2f44ceSEd Maste 
20579f2f44ceSEd Maste     // Perform expression evaluation
2058435933ddSDimitry Andric     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
20599f2f44ceSEd Maste       return false;
20609f2f44ceSEd Maste   }
20619f2f44ceSEd Maste 
20629f2f44ceSEd Maste   // Assign results to allocation members
20639f2f44ceSEd Maste   elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
2064435933ddSDimitry Andric   elem.type_kind =
2065435933ddSDimitry Andric       static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
20669f2f44ceSEd Maste   elem.type_vec_size = static_cast<uint32_t>(results[2]);
20679f2f44ceSEd Maste   elem.field_count = static_cast<uint32_t>(results[3]);
20689f2f44ceSEd Maste 
20699f2f44ceSEd Maste   if (log)
2070435933ddSDimitry Andric     log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32
2071435933ddSDimitry Andric                 ", vector size %" PRIu32 ", field count %" PRIu32,
2072435933ddSDimitry Andric                 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
2073435933ddSDimitry Andric                 *elem.type_vec_size.get(), *elem.field_count.get());
20749f2f44ceSEd Maste 
2075435933ddSDimitry Andric   // If this Element has subelements then JIT rsaElementGetSubElements() for
2076435933ddSDimitry Andric   // details about its fields
2077*b5893f02SDimitry Andric   return !(*elem.field_count.get() > 0 &&
2078*b5893f02SDimitry Andric            !JITSubelements(elem, context, frame_ptr));
20799f2f44ceSEd Maste }
20809f2f44ceSEd Maste 
2081435933ddSDimitry Andric // JITs the RS runtime for information about the subelements/fields of a struct
2082435933ddSDimitry Andric // allocation This is necessary for infering the struct type so we can pretty
2083435933ddSDimitry Andric // print the allocation's contents. Returns true on success, false otherwise
JITSubelements(Element & elem,const lldb::addr_t context,StackFrame * frame_ptr)2084435933ddSDimitry Andric bool RenderScriptRuntime::JITSubelements(Element &elem,
2085435933ddSDimitry Andric                                          const lldb::addr_t context,
2086435933ddSDimitry Andric                                          StackFrame *frame_ptr) {
20879f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
20889f2f44ceSEd Maste 
2089435933ddSDimitry Andric   if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
20909f2f44ceSEd Maste     if (log)
20914bb0738eSEd Maste       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
20929f2f44ceSEd Maste     return false;
20939f2f44ceSEd Maste   }
20949f2f44ceSEd Maste 
20959f2f44ceSEd Maste   const short num_exprs = 3;
2096435933ddSDimitry Andric   assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) &&
2097435933ddSDimitry Andric          "Invalid number of expressions");
20989f2f44ceSEd Maste 
20999f2f44ceSEd Maste   char expr_buffer[jit_max_expr_size];
21009f2f44ceSEd Maste   uint64_t results;
21019f2f44ceSEd Maste 
21029f2f44ceSEd Maste   // Iterate over struct fields.
21039f2f44ceSEd Maste   const uint32_t field_count = *elem.field_count.get();
2104435933ddSDimitry Andric   for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
21059f2f44ceSEd Maste     Element child;
2106435933ddSDimitry Andric     for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
2107435933ddSDimitry Andric       const char *fmt_str =
2108435933ddSDimitry Andric           JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
2109435933ddSDimitry Andric       int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
21106bc11b14SDimitry Andric                              context, field_count, field_count, field_count,
2111435933ddSDimitry Andric                              *elem.element_ptr.get(), field_count, field_index);
2112435933ddSDimitry Andric       if (written < 0) {
21139f2f44ceSEd Maste         if (log)
21144bb0738eSEd Maste           log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
21159f2f44ceSEd Maste         return false;
2116435933ddSDimitry Andric       } else if (written >= jit_max_expr_size) {
21179f2f44ceSEd Maste         if (log)
21184bb0738eSEd Maste           log->Printf("%s - expression too long.", __FUNCTION__);
21199f2f44ceSEd Maste         return false;
21209f2f44ceSEd Maste       }
21219f2f44ceSEd Maste 
21229f2f44ceSEd Maste       // Perform expression evaluation
21239f2f44ceSEd Maste       if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
21249f2f44ceSEd Maste         return false;
21259f2f44ceSEd Maste 
21269f2f44ceSEd Maste       if (log)
21274bb0738eSEd Maste         log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
21289f2f44ceSEd Maste 
2129435933ddSDimitry Andric       switch (expr_index) {
21309f2f44ceSEd Maste       case 0: // Element* of child
21319f2f44ceSEd Maste         child.element_ptr = static_cast<addr_t>(results);
21329f2f44ceSEd Maste         break;
21339f2f44ceSEd Maste       case 1: // Name of child
21349f2f44ceSEd Maste       {
21359f2f44ceSEd Maste         lldb::addr_t address = static_cast<addr_t>(results);
21365517e702SDimitry Andric         Status err;
21379f2f44ceSEd Maste         std::string name;
21389f2f44ceSEd Maste         GetProcess()->ReadCStringFromMemory(address, name, err);
21399f2f44ceSEd Maste         if (!err.Fail())
21409f2f44ceSEd Maste           child.type_name = ConstString(name);
2141435933ddSDimitry Andric         else {
21429f2f44ceSEd Maste           if (log)
2143435933ddSDimitry Andric             log->Printf("%s - warning: Couldn't read field name.",
2144435933ddSDimitry Andric                         __FUNCTION__);
21459f2f44ceSEd Maste         }
21469f2f44ceSEd Maste         break;
21479f2f44ceSEd Maste       }
21489f2f44ceSEd Maste       case 2: // Array size of child
21499f2f44ceSEd Maste         child.array_size = static_cast<uint32_t>(results);
21509f2f44ceSEd Maste         break;
21519f2f44ceSEd Maste       }
21529f2f44ceSEd Maste     }
21539f2f44ceSEd Maste 
21549f2f44ceSEd Maste     // We need to recursively JIT each Element field of the struct since
21559f2f44ceSEd Maste     // structs can be nested inside structs.
21569f2f44ceSEd Maste     if (!JITElementPacked(child, context, frame_ptr))
21579f2f44ceSEd Maste       return false;
21589f2f44ceSEd Maste     elem.children.push_back(child);
21599f2f44ceSEd Maste   }
21609f2f44ceSEd Maste 
2161435933ddSDimitry Andric   // Try to infer the name of the struct type so we can pretty print the
2162435933ddSDimitry Andric   // allocation contents.
21639f2f44ceSEd Maste   FindStructTypeName(elem, frame_ptr);
21649f2f44ceSEd Maste 
21659f2f44ceSEd Maste   return true;
21669f2f44ceSEd Maste }
21679f2f44ceSEd Maste 
21689f2f44ceSEd Maste // JITs the RS runtime for the address of the last element in the allocation.
2169435933ddSDimitry Andric // The `elem_size` parameter represents the size of a single element, including
2170435933ddSDimitry Andric // padding. Which is needed as an offset from the last element pointer. Using
2171435933ddSDimitry Andric // this offset minus the starting address we can calculate the size of the
2172435933ddSDimitry Andric // allocation. Returns true on success, false otherwise
JITAllocationSize(AllocationDetails * alloc,StackFrame * frame_ptr)2173435933ddSDimitry Andric bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
2174435933ddSDimitry Andric                                             StackFrame *frame_ptr) {
21759f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
21769f2f44ceSEd Maste 
2177435933ddSDimitry Andric   if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
2178435933ddSDimitry Andric       !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
21799f2f44ceSEd Maste     if (log)
21804bb0738eSEd Maste       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
21819f2f44ceSEd Maste     return false;
21829f2f44ceSEd Maste   }
21839f2f44ceSEd Maste 
21849f2f44ceSEd Maste   // Find dimensions
2185435933ddSDimitry Andric   uint32_t dim_x = alloc->dimension.get()->dim_1;
2186435933ddSDimitry Andric   uint32_t dim_y = alloc->dimension.get()->dim_2;
2187435933ddSDimitry Andric   uint32_t dim_z = alloc->dimension.get()->dim_3;
21889f2f44ceSEd Maste 
2189435933ddSDimitry Andric   // Our plan of jitting the last element address doesn't seem to work for
2190435933ddSDimitry Andric   // struct Allocations` Instead try to infer the size ourselves without any
2191435933ddSDimitry Andric   // inter element padding.
2192435933ddSDimitry Andric   if (alloc->element.children.size() > 0) {
2193435933ddSDimitry Andric     if (dim_x == 0)
2194435933ddSDimitry Andric       dim_x = 1;
2195435933ddSDimitry Andric     if (dim_y == 0)
2196435933ddSDimitry Andric       dim_y = 1;
2197435933ddSDimitry Andric     if (dim_z == 0)
2198435933ddSDimitry Andric       dim_z = 1;
21999f2f44ceSEd Maste 
2200435933ddSDimitry Andric     alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
22019f2f44ceSEd Maste 
22029f2f44ceSEd Maste     if (log)
2203435933ddSDimitry Andric       log->Printf("%s - inferred size of struct allocation %" PRIu32 ".",
2204435933ddSDimitry Andric                   __FUNCTION__, *alloc->size.get());
22059f2f44ceSEd Maste     return true;
22069f2f44ceSEd Maste   }
22079f2f44ceSEd Maste 
2208435933ddSDimitry Andric   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2209435933ddSDimitry Andric   char expr_buf[jit_max_expr_size];
22109f2f44ceSEd Maste 
22119f2f44ceSEd Maste   // Calculate last element
22129f2f44ceSEd Maste   dim_x = dim_x == 0 ? 0 : dim_x - 1;
22139f2f44ceSEd Maste   dim_y = dim_y == 0 ? 0 : dim_y - 1;
22149f2f44ceSEd Maste   dim_z = dim_z == 0 ? 0 : dim_z - 1;
22159f2f44ceSEd Maste 
2216435933ddSDimitry Andric   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2217435933ddSDimitry Andric                          *alloc->address.get(), dim_x, dim_y, dim_z);
2218435933ddSDimitry Andric   if (written < 0) {
22199f2f44ceSEd Maste     if (log)
22204bb0738eSEd Maste       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
22219f2f44ceSEd Maste     return false;
2222435933ddSDimitry Andric   } else if (written >= jit_max_expr_size) {
22239f2f44ceSEd Maste     if (log)
22244bb0738eSEd Maste       log->Printf("%s - expression too long.", __FUNCTION__);
22259f2f44ceSEd Maste     return false;
22269f2f44ceSEd Maste   }
22279f2f44ceSEd Maste 
22289f2f44ceSEd Maste   uint64_t result = 0;
2229435933ddSDimitry Andric   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
22309f2f44ceSEd Maste     return false;
22319f2f44ceSEd Maste 
22329f2f44ceSEd Maste   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
22339f2f44ceSEd Maste   // Find pointer to last element and add on size of an element
2234435933ddSDimitry Andric   alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
2235435933ddSDimitry Andric                 *alloc->element.datum_size.get();
22369f2f44ceSEd Maste 
22379f2f44ceSEd Maste   return true;
22389f2f44ceSEd Maste }
22399f2f44ceSEd Maste 
2240435933ddSDimitry Andric // JITs the RS runtime for information about the stride between rows in the
22414ba319b5SDimitry Andric // allocation. This is done to detect padding, since allocated memory is
22424ba319b5SDimitry Andric // 16-byte aligned. Returns true on success, false otherwise
JITAllocationStride(AllocationDetails * alloc,StackFrame * frame_ptr)2243435933ddSDimitry Andric bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
2244435933ddSDimitry Andric                                               StackFrame *frame_ptr) {
22459f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
22469f2f44ceSEd Maste 
2247435933ddSDimitry Andric   if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
22489f2f44ceSEd Maste     if (log)
22494bb0738eSEd Maste       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
22509f2f44ceSEd Maste     return false;
22519f2f44ceSEd Maste   }
22529f2f44ceSEd Maste 
2253435933ddSDimitry Andric   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2254435933ddSDimitry Andric   char expr_buf[jit_max_expr_size];
22559f2f44ceSEd Maste 
2256435933ddSDimitry Andric   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2257435933ddSDimitry Andric                          *alloc->address.get(), 0, 1, 0);
2258435933ddSDimitry Andric   if (written < 0) {
22599f2f44ceSEd Maste     if (log)
22604bb0738eSEd Maste       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
22619f2f44ceSEd Maste     return false;
2262435933ddSDimitry Andric   } else if (written >= jit_max_expr_size) {
22639f2f44ceSEd Maste     if (log)
22644bb0738eSEd Maste       log->Printf("%s - expression too long.", __FUNCTION__);
22659f2f44ceSEd Maste     return false;
22669f2f44ceSEd Maste   }
22679f2f44ceSEd Maste 
22689f2f44ceSEd Maste   uint64_t result = 0;
2269435933ddSDimitry Andric   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
22709f2f44ceSEd Maste     return false;
22719f2f44ceSEd Maste 
22729f2f44ceSEd Maste   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2273435933ddSDimitry Andric   alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
22749f2f44ceSEd Maste 
22759f2f44ceSEd Maste   return true;
22769f2f44ceSEd Maste }
22779f2f44ceSEd Maste 
22789f2f44ceSEd Maste // JIT all the current runtime info regarding an allocation
RefreshAllocation(AllocationDetails * alloc,StackFrame * frame_ptr)2279435933ddSDimitry Andric bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2280435933ddSDimitry Andric                                             StackFrame *frame_ptr) {
22819f2f44ceSEd Maste   // GetOffsetPointer()
2282435933ddSDimitry Andric   if (!JITDataPointer(alloc, frame_ptr))
22839f2f44ceSEd Maste     return false;
22849f2f44ceSEd Maste 
22859f2f44ceSEd Maste   // rsaAllocationGetType()
2286435933ddSDimitry Andric   if (!JITTypePointer(alloc, frame_ptr))
22879f2f44ceSEd Maste     return false;
22889f2f44ceSEd Maste 
22899f2f44ceSEd Maste   // rsaTypeGetNativeData()
2290435933ddSDimitry Andric   if (!JITTypePacked(alloc, frame_ptr))
22919f2f44ceSEd Maste     return false;
22929f2f44ceSEd Maste 
22939f2f44ceSEd Maste   // rsaElementGetNativeData()
2294435933ddSDimitry Andric   if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
22959f2f44ceSEd Maste     return false;
22969f2f44ceSEd Maste 
22979f2f44ceSEd Maste   // Sets the datum_size member in Element
2298435933ddSDimitry Andric   SetElementSize(alloc->element);
22999f2f44ceSEd Maste 
23009f2f44ceSEd Maste   // Use GetOffsetPointer() to infer size of the allocation
2301*b5893f02SDimitry Andric   return JITAllocationSize(alloc, frame_ptr);
23029f2f44ceSEd Maste }
23039f2f44ceSEd Maste 
2304435933ddSDimitry Andric // Function attempts to set the type_name member of the paramaterised Element
23054ba319b5SDimitry Andric // object. This string should be the name of the struct type the Element
23064ba319b5SDimitry Andric // represents. We need this string for pretty printing the Element to users.
FindStructTypeName(Element & elem,StackFrame * frame_ptr)2307435933ddSDimitry Andric void RenderScriptRuntime::FindStructTypeName(Element &elem,
2308435933ddSDimitry Andric                                              StackFrame *frame_ptr) {
23099f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
23109f2f44ceSEd Maste 
23119f2f44ceSEd Maste   if (!elem.type_name.IsEmpty()) // Name already set
23129f2f44ceSEd Maste     return;
23139f2f44ceSEd Maste   else
2314435933ddSDimitry Andric     elem.type_name = Element::GetFallbackStructName(); // Default type name if
2315435933ddSDimitry Andric                                                        // we don't succeed
23169f2f44ceSEd Maste 
23179f2f44ceSEd Maste   // Find all the global variables from the script rs modules
2318435933ddSDimitry Andric   VariableList var_list;
23199f2f44ceSEd Maste   for (auto module_sp : m_rsmodules)
2320435933ddSDimitry Andric     module_sp->m_module->FindGlobalVariables(
23214ba319b5SDimitry Andric         RegularExpression(llvm::StringRef(".")), UINT32_MAX, var_list);
23229f2f44ceSEd Maste 
2323435933ddSDimitry Andric   // Iterate over all the global variables looking for one with a matching type
23244ba319b5SDimitry Andric   // to the Element. We make the assumption a match exists since there needs to
23254ba319b5SDimitry Andric   // be a global variable to reflect the struct type back into java host code.
2326435933ddSDimitry Andric   for (uint32_t i = 0; i < var_list.GetSize(); ++i) {
2327435933ddSDimitry Andric     const VariableSP var_sp(var_list.GetVariableAtIndex(i));
23289f2f44ceSEd Maste     if (!var_sp)
23299f2f44ceSEd Maste       continue;
23309f2f44ceSEd Maste 
23319f2f44ceSEd Maste     ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
23329f2f44ceSEd Maste     if (!valobj_sp)
23339f2f44ceSEd Maste       continue;
23349f2f44ceSEd Maste 
23359f2f44ceSEd Maste     // Find the number of variable fields.
2336435933ddSDimitry Andric     // If it has no fields, or more fields than our Element, then it can't be
23374ba319b5SDimitry Andric     // the struct we're looking for. Don't check for equality since RS can add
23384ba319b5SDimitry Andric     // extra struct members for padding.
23399f2f44ceSEd Maste     size_t num_children = valobj_sp->GetNumChildren();
23409f2f44ceSEd Maste     if (num_children > elem.children.size() || num_children == 0)
23419f2f44ceSEd Maste       continue;
23429f2f44ceSEd Maste 
23434ba319b5SDimitry Andric     // Iterate over children looking for members with matching field names. If
23444ba319b5SDimitry Andric     // all the field names match, this is likely the struct we want.
2345435933ddSDimitry Andric     //   TODO: This could be made more robust by also checking children data
2346435933ddSDimitry Andric     //   sizes, or array size
23479f2f44ceSEd Maste     bool found = true;
2348435933ddSDimitry Andric     for (size_t i = 0; i < num_children; ++i) {
2349435933ddSDimitry Andric       ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
2350435933ddSDimitry Andric       if (!child || (child->GetName() != elem.children[i].type_name)) {
23519f2f44ceSEd Maste         found = false;
23529f2f44ceSEd Maste         break;
23539f2f44ceSEd Maste       }
23549f2f44ceSEd Maste     }
23559f2f44ceSEd Maste 
2356435933ddSDimitry Andric     // RS can add extra struct members for padding in the format
2357435933ddSDimitry Andric     // '#rs_padding_[0-9]+'
2358435933ddSDimitry Andric     if (found && num_children < elem.children.size()) {
23594bb0738eSEd Maste       const uint32_t size_diff = elem.children.size() - num_children;
23609f2f44ceSEd Maste       if (log)
2361435933ddSDimitry Andric         log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2362435933ddSDimitry Andric                     size_diff);
23639f2f44ceSEd Maste 
2364435933ddSDimitry Andric       for (uint32_t i = 0; i < size_diff; ++i) {
2365435933ddSDimitry Andric         const ConstString &name = elem.children[num_children + i].type_name;
23669f2f44ceSEd Maste         if (strcmp(name.AsCString(), "#rs_padding") < 0)
23679f2f44ceSEd Maste           found = false;
23689f2f44ceSEd Maste       }
23699f2f44ceSEd Maste     }
23709f2f44ceSEd Maste 
2371435933ddSDimitry Andric     // We've found a global variable with matching type
2372435933ddSDimitry Andric     if (found) {
23739f2f44ceSEd Maste       // Dereference since our Element type isn't a pointer.
2374435933ddSDimitry Andric       if (valobj_sp->IsPointerType()) {
23755517e702SDimitry Andric         Status err;
23769f2f44ceSEd Maste         ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
23779f2f44ceSEd Maste         if (!err.Fail())
23789f2f44ceSEd Maste           valobj_sp = deref_valobj;
23799f2f44ceSEd Maste       }
23809f2f44ceSEd Maste 
23819f2f44ceSEd Maste       // Save name of variable in Element.
23829f2f44ceSEd Maste       elem.type_name = valobj_sp->GetTypeName();
23839f2f44ceSEd Maste       if (log)
2384435933ddSDimitry Andric         log->Printf("%s - element name set to %s", __FUNCTION__,
2385435933ddSDimitry Andric                     elem.type_name.AsCString());
23869f2f44ceSEd Maste 
23879f2f44ceSEd Maste       return;
23889f2f44ceSEd Maste     }
23899f2f44ceSEd Maste   }
23909f2f44ceSEd Maste }
23919f2f44ceSEd Maste 
2392435933ddSDimitry Andric // Function sets the datum_size member of Element. Representing the size of a
23934ba319b5SDimitry Andric // single instance including padding. Assumes the relevant allocation
23944ba319b5SDimitry Andric // information has already been jitted.
SetElementSize(Element & elem)2395435933ddSDimitry Andric void RenderScriptRuntime::SetElementSize(Element &elem) {
23969f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
23979f2f44ceSEd Maste   const Element::DataType type = *elem.type.get();
2398435933ddSDimitry Andric   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2399435933ddSDimitry Andric          "Invalid allocation type");
24009f2f44ceSEd Maste 
24014bb0738eSEd Maste   const uint32_t vec_size = *elem.type_vec_size.get();
24024bb0738eSEd Maste   uint32_t data_size = 0;
24034bb0738eSEd Maste   uint32_t padding = 0;
24049f2f44ceSEd Maste 
24059f2f44ceSEd Maste   // Element is of a struct type, calculate size recursively.
2406435933ddSDimitry Andric   if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2407435933ddSDimitry Andric     for (Element &child : elem.children) {
24089f2f44ceSEd Maste       SetElementSize(child);
2409435933ddSDimitry Andric       const uint32_t array_size =
2410435933ddSDimitry Andric           child.array_size.isValid() ? *child.array_size.get() : 1;
24119f2f44ceSEd Maste       data_size += *child.datum_size.get() * array_size;
24129f2f44ceSEd Maste     }
24139f2f44ceSEd Maste   }
24144bb0738eSEd Maste   // These have been packed already
24154bb0738eSEd Maste   else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
24164bb0738eSEd Maste            type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2417435933ddSDimitry Andric            type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
24189f2f44ceSEd Maste     data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2419435933ddSDimitry Andric   } else if (type < Element::RS_TYPE_ELEMENT) {
2420435933ddSDimitry Andric     data_size =
2421435933ddSDimitry Andric         vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
24229f2f44ceSEd Maste     if (vec_size == 3)
24239f2f44ceSEd Maste       padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2424435933ddSDimitry Andric   } else
2425435933ddSDimitry Andric     data_size =
2426435933ddSDimitry Andric         GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
24279f2f44ceSEd Maste 
24289f2f44ceSEd Maste   elem.padding = padding;
24299f2f44ceSEd Maste   elem.datum_size = data_size + padding;
24309f2f44ceSEd Maste   if (log)
2431435933ddSDimitry Andric     log->Printf("%s - element size set to %" PRIu32, __FUNCTION__,
2432435933ddSDimitry Andric                 data_size + padding);
24339f2f44ceSEd Maste }
24349f2f44ceSEd Maste 
24354ba319b5SDimitry Andric // Given an allocation, this function copies the allocation contents from
24364ba319b5SDimitry Andric // device into a buffer on the heap. Returning a shared pointer to the buffer
24374ba319b5SDimitry Andric // containing the data.
24389f2f44ceSEd Maste std::shared_ptr<uint8_t>
GetAllocationData(AllocationDetails * alloc,StackFrame * frame_ptr)2439435933ddSDimitry Andric RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2440435933ddSDimitry Andric                                        StackFrame *frame_ptr) {
24419f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
24429f2f44ceSEd Maste 
24439f2f44ceSEd Maste   // JIT all the allocation details
2444435933ddSDimitry Andric   if (alloc->ShouldRefresh()) {
24459f2f44ceSEd Maste     if (log)
2446435933ddSDimitry Andric       log->Printf("%s - allocation details not calculated yet, jitting info",
2447435933ddSDimitry Andric                   __FUNCTION__);
24489f2f44ceSEd Maste 
2449435933ddSDimitry Andric     if (!RefreshAllocation(alloc, frame_ptr)) {
24509f2f44ceSEd Maste       if (log)
24514bb0738eSEd Maste         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
24529f2f44ceSEd Maste       return nullptr;
24539f2f44ceSEd Maste     }
24549f2f44ceSEd Maste   }
24559f2f44ceSEd Maste 
2456435933ddSDimitry Andric   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2457435933ddSDimitry Andric          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
24584bb0738eSEd Maste          "Allocation information not available");
24599f2f44ceSEd Maste 
24609f2f44ceSEd Maste   // Allocate a buffer to copy data into
2461435933ddSDimitry Andric   const uint32_t size = *alloc->size.get();
24629f2f44ceSEd Maste   std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2463435933ddSDimitry Andric   if (!buffer) {
24649f2f44ceSEd Maste     if (log)
2465435933ddSDimitry Andric       log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer",
2466435933ddSDimitry Andric                   __FUNCTION__, size);
24679f2f44ceSEd Maste     return nullptr;
24689f2f44ceSEd Maste   }
24699f2f44ceSEd Maste 
24709f2f44ceSEd Maste   // Read the inferior memory
24715517e702SDimitry Andric   Status err;
2472435933ddSDimitry Andric   lldb::addr_t data_ptr = *alloc->data_ptr.get();
2473435933ddSDimitry Andric   GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
2474435933ddSDimitry Andric   if (err.Fail()) {
24759f2f44ceSEd Maste     if (log)
2476435933ddSDimitry Andric       log->Printf("%s - '%s' Couldn't read %" PRIu32
2477435933ddSDimitry Andric                   " bytes of allocation data from 0x%" PRIx64,
2478435933ddSDimitry Andric                   __FUNCTION__, err.AsCString(), size, data_ptr);
24799f2f44ceSEd Maste     return nullptr;
24809f2f44ceSEd Maste   }
24819f2f44ceSEd Maste 
24829f2f44ceSEd Maste   return buffer;
24839f2f44ceSEd Maste }
24849f2f44ceSEd Maste 
24854ba319b5SDimitry Andric // Function copies data from a binary file into an allocation. There is a
24864ba319b5SDimitry Andric // header at the start of the file, FileHeader, before the data content itself.
2487435933ddSDimitry Andric // Information from this header is used to display warnings to the user about
2488435933ddSDimitry Andric // incompatibilities
LoadAllocation(Stream & strm,const uint32_t alloc_id,const char * path,StackFrame * frame_ptr)2489435933ddSDimitry Andric bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
2490435933ddSDimitry Andric                                          const char *path,
2491435933ddSDimitry Andric                                          StackFrame *frame_ptr) {
24929f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
24939f2f44ceSEd Maste 
24949f2f44ceSEd Maste   // Find allocation with the given id
24959f2f44ceSEd Maste   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
24969f2f44ceSEd Maste   if (!alloc)
24979f2f44ceSEd Maste     return false;
24989f2f44ceSEd Maste 
24999f2f44ceSEd Maste   if (log)
2500435933ddSDimitry Andric     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2501435933ddSDimitry Andric                 *alloc->address.get());
25029f2f44ceSEd Maste 
25039f2f44ceSEd Maste   // JIT all the allocation details
2504435933ddSDimitry Andric   if (alloc->ShouldRefresh()) {
25059f2f44ceSEd Maste     if (log)
2506435933ddSDimitry Andric       log->Printf("%s - allocation details not calculated yet, jitting info.",
2507435933ddSDimitry Andric                   __FUNCTION__);
25089f2f44ceSEd Maste 
2509435933ddSDimitry Andric     if (!RefreshAllocation(alloc, frame_ptr)) {
25109f2f44ceSEd Maste       if (log)
25114bb0738eSEd Maste         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
25129f2f44ceSEd Maste       return false;
25139f2f44ceSEd Maste     }
25149f2f44ceSEd Maste   }
25159f2f44ceSEd Maste 
2516435933ddSDimitry Andric   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2517435933ddSDimitry Andric          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2518435933ddSDimitry Andric          alloc->element.datum_size.isValid() &&
2519435933ddSDimitry Andric          "Allocation information not available");
25209f2f44ceSEd Maste 
25219f2f44ceSEd Maste   // Check we can read from file
2522*b5893f02SDimitry Andric   FileSpec file(path);
2523*b5893f02SDimitry Andric   FileSystem::Instance().Resolve(file);
2524*b5893f02SDimitry Andric   if (!FileSystem::Instance().Exists(file)) {
2525435933ddSDimitry Andric     strm.Printf("Error: File %s does not exist", path);
25269f2f44ceSEd Maste     strm.EOL();
25279f2f44ceSEd Maste     return false;
25289f2f44ceSEd Maste   }
25299f2f44ceSEd Maste 
2530*b5893f02SDimitry Andric   if (!FileSystem::Instance().Readable(file)) {
2531435933ddSDimitry Andric     strm.Printf("Error: File %s does not have readable permissions", path);
25329f2f44ceSEd Maste     strm.EOL();
25339f2f44ceSEd Maste     return false;
25349f2f44ceSEd Maste   }
25359f2f44ceSEd Maste 
25369f2f44ceSEd Maste   // Read file into data buffer
2537*b5893f02SDimitry Andric   auto data_sp = FileSystem::Instance().CreateDataBuffer(file.GetPath());
25389f2f44ceSEd Maste 
25399f2f44ceSEd Maste   // Cast start of buffer to FileHeader and use pointer to read metadata
2540435933ddSDimitry Andric   void *file_buf = data_sp->GetBytes();
2541435933ddSDimitry Andric   if (file_buf == nullptr ||
2542435933ddSDimitry Andric       data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2543435933ddSDimitry Andric                                 sizeof(AllocationDetails::ElementHeader))) {
2544435933ddSDimitry Andric     strm.Printf("Error: File %s does not contain enough data for header", path);
2545444ed5c5SDimitry Andric     strm.EOL();
2546444ed5c5SDimitry Andric     return false;
2547444ed5c5SDimitry Andric   }
2548435933ddSDimitry Andric   const AllocationDetails::FileHeader *file_header =
2549435933ddSDimitry Andric       static_cast<AllocationDetails::FileHeader *>(file_buf);
25509f2f44ceSEd Maste 
2551444ed5c5SDimitry Andric   // Check file starts with ascii characters "RSAD"
2552435933ddSDimitry Andric   if (memcmp(file_header->ident, "RSAD", 4)) {
2553435933ddSDimitry Andric     strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2554435933ddSDimitry Andric                 "dump. Are you sure this is the correct file?");
2555444ed5c5SDimitry Andric     strm.EOL();
2556444ed5c5SDimitry Andric     return false;
2557444ed5c5SDimitry Andric   }
2558444ed5c5SDimitry Andric 
2559444ed5c5SDimitry Andric   // Look at the type of the root element in the header
2560435933ddSDimitry Andric   AllocationDetails::ElementHeader root_el_hdr;
2561435933ddSDimitry Andric   memcpy(&root_el_hdr, static_cast<uint8_t *>(file_buf) +
2562435933ddSDimitry Andric                            sizeof(AllocationDetails::FileHeader),
2563444ed5c5SDimitry Andric          sizeof(AllocationDetails::ElementHeader));
25649f2f44ceSEd Maste 
25659f2f44ceSEd Maste   if (log)
2566435933ddSDimitry Andric     log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32,
2567435933ddSDimitry Andric                 __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
25689f2f44ceSEd Maste 
2569435933ddSDimitry Andric   // Check if the target allocation and file both have the same number of bytes
2570435933ddSDimitry Andric   // for an Element
2571435933ddSDimitry Andric   if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2572435933ddSDimitry Andric     strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2573435933ddSDimitry Andric                 " bytes, allocation %" PRIu32 " bytes",
2574435933ddSDimitry Andric                 root_el_hdr.element_size, *alloc->element.datum_size.get());
25759f2f44ceSEd Maste     strm.EOL();
25769f2f44ceSEd Maste   }
25779f2f44ceSEd Maste 
2578444ed5c5SDimitry Andric   // Check if the target allocation and file both have the same type
25794bb0738eSEd Maste   const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
2580435933ddSDimitry Andric   const uint32_t file_type = root_el_hdr.type;
2581444ed5c5SDimitry Andric 
2582435933ddSDimitry Andric   if (file_type > Element::RS_TYPE_FONT) {
2583444ed5c5SDimitry Andric     strm.Printf("Warning: File has unknown allocation type");
2584444ed5c5SDimitry Andric     strm.EOL();
2585435933ddSDimitry Andric   } else if (alloc_type != file_type) {
2586435933ddSDimitry Andric     // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2587435933ddSDimitry Andric     // array
2588435933ddSDimitry Andric     uint32_t target_type_name_idx = alloc_type;
2589435933ddSDimitry Andric     uint32_t head_type_name_idx = file_type;
2590435933ddSDimitry Andric     if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2591435933ddSDimitry Andric         alloc_type <= Element::RS_TYPE_FONT)
2592435933ddSDimitry Andric       target_type_name_idx = static_cast<Element::DataType>(
2593435933ddSDimitry Andric           (alloc_type - Element::RS_TYPE_ELEMENT) +
25944bb0738eSEd Maste           Element::RS_TYPE_MATRIX_2X2 + 1);
25959f2f44ceSEd Maste 
2596435933ddSDimitry Andric     if (file_type >= Element::RS_TYPE_ELEMENT &&
2597435933ddSDimitry Andric         file_type <= Element::RS_TYPE_FONT)
2598435933ddSDimitry Andric       head_type_name_idx = static_cast<Element::DataType>(
2599435933ddSDimitry Andric           (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2600435933ddSDimitry Andric           1);
26019f2f44ceSEd Maste 
2602435933ddSDimitry Andric     const char *head_type_name =
2603435933ddSDimitry Andric         AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
2604435933ddSDimitry Andric     const char *target_type_name =
2605435933ddSDimitry Andric         AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
26069f2f44ceSEd Maste 
2607435933ddSDimitry Andric     strm.Printf(
2608435933ddSDimitry Andric         "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
2609435933ddSDimitry Andric         head_type_name, target_type_name);
26109f2f44ceSEd Maste     strm.EOL();
26119f2f44ceSEd Maste   }
26129f2f44ceSEd Maste 
2613444ed5c5SDimitry Andric   // Advance buffer past header
2614435933ddSDimitry Andric   file_buf = static_cast<uint8_t *>(file_buf) + file_header->hdr_size;
2615444ed5c5SDimitry Andric 
26169f2f44ceSEd Maste   // Calculate size of allocation data in file
2617435933ddSDimitry Andric   size_t size = data_sp->GetByteSize() - file_header->hdr_size;
26189f2f44ceSEd Maste 
26194ba319b5SDimitry Andric   // Check if the target allocation and file both have the same total data
26204ba319b5SDimitry Andric   // size.
26214bb0738eSEd Maste   const uint32_t alloc_size = *alloc->size.get();
2622435933ddSDimitry Andric   if (alloc_size != size) {
2623435933ddSDimitry Andric     strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2624435933ddSDimitry Andric                 " bytes, allocation 0x%" PRIx32 " bytes",
2625435933ddSDimitry Andric                 (uint64_t)size, alloc_size);
26269f2f44ceSEd Maste     strm.EOL();
2627435933ddSDimitry Andric     // Set length to copy to minimum
2628435933ddSDimitry Andric     size = alloc_size < size ? alloc_size : size;
26299f2f44ceSEd Maste   }
26309f2f44ceSEd Maste 
26319f2f44ceSEd Maste   // Copy file data from our buffer into the target allocation.
26329f2f44ceSEd Maste   lldb::addr_t alloc_data = *alloc->data_ptr.get();
26335517e702SDimitry Andric   Status err;
2634435933ddSDimitry Andric   size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
2635435933ddSDimitry Andric   if (!err.Success() || written != size) {
2636435933ddSDimitry Andric     strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
26379f2f44ceSEd Maste     strm.EOL();
26389f2f44ceSEd Maste     return false;
26399f2f44ceSEd Maste   }
26409f2f44ceSEd Maste 
2641435933ddSDimitry Andric   strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2642435933ddSDimitry Andric               alloc->id);
26439f2f44ceSEd Maste   strm.EOL();
26449f2f44ceSEd Maste 
26459f2f44ceSEd Maste   return true;
26469f2f44ceSEd Maste }
26479f2f44ceSEd Maste 
2648435933ddSDimitry Andric // Function takes as parameters a byte buffer, which will eventually be written
2649435933ddSDimitry Andric // to file as the element header, an offset into that buffer, and an Element
26504ba319b5SDimitry Andric // that will be saved into the buffer at the parametrised offset. Return value
26514ba319b5SDimitry Andric // is the new offset after writing the element into the buffer. Elements are
26524ba319b5SDimitry Andric // saved to the file as the ElementHeader struct followed by offsets to the
26534ba319b5SDimitry Andric // structs of all the element's children.
PopulateElementHeaders(const std::shared_ptr<uint8_t> header_buffer,size_t offset,const Element & elem)2654435933ddSDimitry Andric size_t RenderScriptRuntime::PopulateElementHeaders(
2655435933ddSDimitry Andric     const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2656435933ddSDimitry Andric     const Element &elem) {
26574ba319b5SDimitry Andric   // File struct for an element header with all the relevant details copied
26584ba319b5SDimitry Andric   // from elem. We assume members are valid already.
2659444ed5c5SDimitry Andric   AllocationDetails::ElementHeader elem_header;
2660444ed5c5SDimitry Andric   elem_header.type = *elem.type.get();
2661444ed5c5SDimitry Andric   elem_header.kind = *elem.type_kind.get();
2662444ed5c5SDimitry Andric   elem_header.element_size = *elem.datum_size.get();
2663444ed5c5SDimitry Andric   elem_header.vector_size = *elem.type_vec_size.get();
2664435933ddSDimitry Andric   elem_header.array_size =
2665435933ddSDimitry Andric       elem.array_size.isValid() ? *elem.array_size.get() : 0;
2666444ed5c5SDimitry Andric   const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
2667444ed5c5SDimitry Andric 
26684ba319b5SDimitry Andric   // Copy struct into buffer and advance offset We assume that header_buffer
26694ba319b5SDimitry Andric   // has been checked for nullptr before this method is called
2670444ed5c5SDimitry Andric   memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
2671444ed5c5SDimitry Andric   offset += elem_header_size;
2672444ed5c5SDimitry Andric 
2673444ed5c5SDimitry Andric   // Starting offset of child ElementHeader struct
2674435933ddSDimitry Andric   size_t child_offset =
2675435933ddSDimitry Andric       offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2676435933ddSDimitry Andric   for (const RenderScriptRuntime::Element &child : elem.children) {
2677435933ddSDimitry Andric     // Recursively populate the buffer with the element header structs of
2678435933ddSDimitry Andric     // children. Then save the offsets where they were set after the parent
2679435933ddSDimitry Andric     // element header.
2680444ed5c5SDimitry Andric     memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
2681444ed5c5SDimitry Andric     offset += sizeof(uint32_t);
2682444ed5c5SDimitry Andric 
2683444ed5c5SDimitry Andric     child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
2684444ed5c5SDimitry Andric   }
2685444ed5c5SDimitry Andric 
2686444ed5c5SDimitry Andric   // Zero indicates no more children
2687444ed5c5SDimitry Andric   memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
2688444ed5c5SDimitry Andric 
2689444ed5c5SDimitry Andric   return child_offset;
2690444ed5c5SDimitry Andric }
2691444ed5c5SDimitry Andric 
2692435933ddSDimitry Andric // Given an Element object this function returns the total size needed in the
2693435933ddSDimitry Andric // file header to store the element's details. Taking into account the size of
2694435933ddSDimitry Andric // the element header struct, plus the offsets to all the element's children.
2695435933ddSDimitry Andric // Function is recursive so that the size of all ancestors is taken into
2696435933ddSDimitry Andric // account.
CalculateElementHeaderSize(const Element & elem)2697435933ddSDimitry Andric size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
2698435933ddSDimitry Andric   // Offsets to children plus zero terminator
2699435933ddSDimitry Andric   size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
2700435933ddSDimitry Andric   // Size of header struct with type details
2701435933ddSDimitry Andric   size += sizeof(AllocationDetails::ElementHeader);
2702444ed5c5SDimitry Andric 
2703444ed5c5SDimitry Andric   // Calculate recursively for all descendants
2704444ed5c5SDimitry Andric   for (const Element &child : elem.children)
2705444ed5c5SDimitry Andric     size += CalculateElementHeaderSize(child);
2706444ed5c5SDimitry Andric 
2707444ed5c5SDimitry Andric   return size;
2708444ed5c5SDimitry Andric }
2709444ed5c5SDimitry Andric 
27104ba319b5SDimitry Andric // Function copies allocation contents into a binary file. This file can then
27114ba319b5SDimitry Andric // be loaded later into a different allocation. There is a header, FileHeader,
2712435933ddSDimitry Andric // before the allocation data containing meta-data.
SaveAllocation(Stream & strm,const uint32_t alloc_id,const char * path,StackFrame * frame_ptr)2713435933ddSDimitry Andric bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
2714435933ddSDimitry Andric                                          const char *path,
2715435933ddSDimitry Andric                                          StackFrame *frame_ptr) {
27169f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
27179f2f44ceSEd Maste 
27189f2f44ceSEd Maste   // Find allocation with the given id
27199f2f44ceSEd Maste   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
27209f2f44ceSEd Maste   if (!alloc)
27219f2f44ceSEd Maste     return false;
27229f2f44ceSEd Maste 
27239f2f44ceSEd Maste   if (log)
2724435933ddSDimitry Andric     log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2725435933ddSDimitry Andric                 *alloc->address.get());
27269f2f44ceSEd Maste 
27279f2f44ceSEd Maste   // JIT all the allocation details
2728435933ddSDimitry Andric   if (alloc->ShouldRefresh()) {
27299f2f44ceSEd Maste     if (log)
2730435933ddSDimitry Andric       log->Printf("%s - allocation details not calculated yet, jitting info.",
2731435933ddSDimitry Andric                   __FUNCTION__);
27329f2f44ceSEd Maste 
2733435933ddSDimitry Andric     if (!RefreshAllocation(alloc, frame_ptr)) {
27349f2f44ceSEd Maste       if (log)
27354bb0738eSEd Maste         log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
27369f2f44ceSEd Maste       return false;
27379f2f44ceSEd Maste     }
27389f2f44ceSEd Maste   }
27399f2f44ceSEd Maste 
2740435933ddSDimitry Andric   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2741435933ddSDimitry Andric          alloc->element.type_vec_size.isValid() &&
2742435933ddSDimitry Andric          alloc->element.datum_size.get() &&
2743435933ddSDimitry Andric          alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
27444bb0738eSEd Maste          "Allocation information not available");
27459f2f44ceSEd Maste 
27469f2f44ceSEd Maste   // Check we can create writable file
2747*b5893f02SDimitry Andric   FileSpec file_spec(path);
2748*b5893f02SDimitry Andric   FileSystem::Instance().Resolve(file_spec);
2749*b5893f02SDimitry Andric   File file;
2750*b5893f02SDimitry Andric   FileSystem::Instance().Open(file, file_spec,
2751*b5893f02SDimitry Andric                               File::eOpenOptionWrite |
2752*b5893f02SDimitry Andric                                   File::eOpenOptionCanCreate |
2753435933ddSDimitry Andric                                   File::eOpenOptionTruncate);
2754*b5893f02SDimitry Andric 
2755435933ddSDimitry Andric   if (!file) {
2756435933ddSDimitry Andric     strm.Printf("Error: Failed to open '%s' for writing", path);
27579f2f44ceSEd Maste     strm.EOL();
27589f2f44ceSEd Maste     return false;
27599f2f44ceSEd Maste   }
27609f2f44ceSEd Maste 
27619f2f44ceSEd Maste   // Read allocation into buffer of heap memory
27629f2f44ceSEd Maste   const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2763435933ddSDimitry Andric   if (!buffer) {
27649f2f44ceSEd Maste     strm.Printf("Error: Couldn't read allocation data into buffer");
27659f2f44ceSEd Maste     strm.EOL();
27669f2f44ceSEd Maste     return false;
27679f2f44ceSEd Maste   }
27689f2f44ceSEd Maste 
27699f2f44ceSEd Maste   // Create the file header
27709f2f44ceSEd Maste   AllocationDetails::FileHeader head;
27714bb0738eSEd Maste   memcpy(head.ident, "RSAD", 4);
27729f2f44ceSEd Maste   head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
27739f2f44ceSEd Maste   head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
27749f2f44ceSEd Maste   head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
2775444ed5c5SDimitry Andric 
2776444ed5c5SDimitry Andric   const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2777435933ddSDimitry Andric   assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2778435933ddSDimitry Andric              UINT16_MAX &&
2779435933ddSDimitry Andric          "Element header too large");
2780435933ddSDimitry Andric   head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2781435933ddSDimitry Andric                                         element_header_size);
27829f2f44ceSEd Maste 
27839f2f44ceSEd Maste   // Write the file header
27849f2f44ceSEd Maste   size_t num_bytes = sizeof(AllocationDetails::FileHeader);
2785444ed5c5SDimitry Andric   if (log)
2786435933ddSDimitry Andric     log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2787435933ddSDimitry Andric                 (uint64_t)num_bytes);
2788444ed5c5SDimitry Andric 
27895517e702SDimitry Andric   Status err = file.Write(&head, num_bytes);
2790435933ddSDimitry Andric   if (!err.Success()) {
2791435933ddSDimitry Andric     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2792444ed5c5SDimitry Andric     strm.EOL();
2793444ed5c5SDimitry Andric     return false;
2794444ed5c5SDimitry Andric   }
2795444ed5c5SDimitry Andric 
2796444ed5c5SDimitry Andric   // Create the headers describing the element type of the allocation.
2797435933ddSDimitry Andric   std::shared_ptr<uint8_t> element_header_buffer(
2798435933ddSDimitry Andric       new uint8_t[element_header_size]);
2799435933ddSDimitry Andric   if (element_header_buffer == nullptr) {
2800435933ddSDimitry Andric     strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2801435933ddSDimitry Andric                 " bytes on the heap",
2802435933ddSDimitry Andric                 (uint64_t)element_header_size);
2803444ed5c5SDimitry Andric     strm.EOL();
2804444ed5c5SDimitry Andric     return false;
2805444ed5c5SDimitry Andric   }
2806444ed5c5SDimitry Andric 
2807444ed5c5SDimitry Andric   PopulateElementHeaders(element_header_buffer, 0, alloc->element);
2808444ed5c5SDimitry Andric 
2809444ed5c5SDimitry Andric   // Write headers for allocation element type to file
2810444ed5c5SDimitry Andric   num_bytes = element_header_size;
2811444ed5c5SDimitry Andric   if (log)
2812435933ddSDimitry Andric     log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.",
2813435933ddSDimitry Andric                 __FUNCTION__, (uint64_t)num_bytes);
2814444ed5c5SDimitry Andric 
2815444ed5c5SDimitry Andric   err = file.Write(element_header_buffer.get(), num_bytes);
2816435933ddSDimitry Andric   if (!err.Success()) {
2817435933ddSDimitry Andric     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
28189f2f44ceSEd Maste     strm.EOL();
28199f2f44ceSEd Maste     return false;
28209f2f44ceSEd Maste   }
28219f2f44ceSEd Maste 
28229f2f44ceSEd Maste   // Write allocation data to file
28239f2f44ceSEd Maste   num_bytes = static_cast<size_t>(*alloc->size.get());
28249f2f44ceSEd Maste   if (log)
2825435933ddSDimitry Andric     log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2826435933ddSDimitry Andric                 (uint64_t)num_bytes);
28279f2f44ceSEd Maste 
28289f2f44ceSEd Maste   err = file.Write(buffer.get(), num_bytes);
2829435933ddSDimitry Andric   if (!err.Success()) {
2830435933ddSDimitry Andric     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
28319f2f44ceSEd Maste     strm.EOL();
28329f2f44ceSEd Maste     return false;
28339f2f44ceSEd Maste   }
28349f2f44ceSEd Maste 
2835435933ddSDimitry Andric   strm.Printf("Allocation written to file '%s'", path);
28369f2f44ceSEd Maste   strm.EOL();
28379f2f44ceSEd Maste   return true;
28381c3bbb01SEd Maste }
28391c3bbb01SEd Maste 
LoadModule(const lldb::ModuleSP & module_sp)2840435933ddSDimitry Andric bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
28411c3bbb01SEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
28421c3bbb01SEd Maste 
2843435933ddSDimitry Andric   if (module_sp) {
2844435933ddSDimitry Andric     for (const auto &rs_module : m_rsmodules) {
2845435933ddSDimitry Andric       if (rs_module->m_module == module_sp) {
28464ba319b5SDimitry Andric         // Check if the user has enabled automatically breaking on all RS
28474ba319b5SDimitry Andric         // kernels.
28489f2f44ceSEd Maste         if (m_breakAllKernels)
28499f2f44ceSEd Maste           BreakOnModuleKernels(rs_module);
28509f2f44ceSEd Maste 
28511c3bbb01SEd Maste         return false;
28521c3bbb01SEd Maste       }
28539f2f44ceSEd Maste     }
28541c3bbb01SEd Maste     bool module_loaded = false;
2855435933ddSDimitry Andric     switch (GetModuleKind(module_sp)) {
2856435933ddSDimitry Andric     case eModuleKindKernelObj: {
28571c3bbb01SEd Maste       RSModuleDescriptorSP module_desc;
28581c3bbb01SEd Maste       module_desc.reset(new RSModuleDescriptor(module_sp));
2859435933ddSDimitry Andric       if (module_desc->ParseRSInfo()) {
28601c3bbb01SEd Maste         m_rsmodules.push_back(module_desc);
28618e0f8b8cSDimitry Andric         module_desc->WarnIfVersionMismatch(GetProcess()
28628e0f8b8cSDimitry Andric                                                ->GetTarget()
28638e0f8b8cSDimitry Andric                                                .GetDebugger()
28648e0f8b8cSDimitry Andric                                                .GetAsyncOutputStream()
28658e0f8b8cSDimitry Andric                                                .get());
28661c3bbb01SEd Maste         module_loaded = true;
28671c3bbb01SEd Maste       }
2868435933ddSDimitry Andric       if (module_loaded) {
28691c3bbb01SEd Maste         FixupScriptDetails(module_desc);
28701c3bbb01SEd Maste       }
28711c3bbb01SEd Maste       break;
28721c3bbb01SEd Maste     }
2873435933ddSDimitry Andric     case eModuleKindDriver: {
2874435933ddSDimitry Andric       if (!m_libRSDriver) {
28751c3bbb01SEd Maste         m_libRSDriver = module_sp;
28761c3bbb01SEd Maste         LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
28771c3bbb01SEd Maste       }
28781c3bbb01SEd Maste       break;
28791c3bbb01SEd Maste     }
2880435933ddSDimitry Andric     case eModuleKindImpl: {
2881435933ddSDimitry Andric       if (!m_libRSCpuRef) {
28821c3bbb01SEd Maste         m_libRSCpuRef = module_sp;
2883435933ddSDimitry Andric         LoadRuntimeHooks(m_libRSCpuRef, RenderScriptRuntime::eModuleKindImpl);
2884435933ddSDimitry Andric       }
28851c3bbb01SEd Maste       break;
28861c3bbb01SEd Maste     }
2887435933ddSDimitry Andric     case eModuleKindLibRS: {
2888435933ddSDimitry Andric       if (!m_libRS) {
28891c3bbb01SEd Maste         m_libRS = module_sp;
28901c3bbb01SEd Maste         static ConstString gDbgPresentStr("gDebuggerPresent");
2891435933ddSDimitry Andric         const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2892435933ddSDimitry Andric             gDbgPresentStr, eSymbolTypeData);
2893435933ddSDimitry Andric         if (debug_present) {
28945517e702SDimitry Andric           Status err;
28951c3bbb01SEd Maste           uint32_t flag = 0x00000001U;
28961c3bbb01SEd Maste           Target &target = GetProcess()->GetTarget();
28971c3bbb01SEd Maste           addr_t addr = debug_present->GetLoadAddress(&target);
2898435933ddSDimitry Andric           GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
2899435933ddSDimitry Andric           if (err.Success()) {
29001c3bbb01SEd Maste             if (log)
2901435933ddSDimitry Andric               log->Printf("%s - debugger present flag set on debugee.",
2902435933ddSDimitry Andric                           __FUNCTION__);
29031c3bbb01SEd Maste 
29041c3bbb01SEd Maste             m_debuggerPresentFlagged = true;
2905435933ddSDimitry Andric           } else if (log) {
2906435933ddSDimitry Andric             log->Printf("%s - error writing debugger present flags '%s' ",
2907435933ddSDimitry Andric                         __FUNCTION__, err.AsCString());
29081c3bbb01SEd Maste           }
2909435933ddSDimitry Andric         } else if (log) {
2910435933ddSDimitry Andric           log->Printf(
2911435933ddSDimitry Andric               "%s - error writing debugger present flags - symbol not found",
2912435933ddSDimitry Andric               __FUNCTION__);
29131c3bbb01SEd Maste         }
29141c3bbb01SEd Maste       }
29151c3bbb01SEd Maste       break;
29161c3bbb01SEd Maste     }
29171c3bbb01SEd Maste     default:
29181c3bbb01SEd Maste       break;
29191c3bbb01SEd Maste     }
29201c3bbb01SEd Maste     if (module_loaded)
29211c3bbb01SEd Maste       Update();
29221c3bbb01SEd Maste     return module_loaded;
29231c3bbb01SEd Maste   }
29241c3bbb01SEd Maste   return false;
29251c3bbb01SEd Maste }
29261c3bbb01SEd Maste 
Update()2927435933ddSDimitry Andric void RenderScriptRuntime::Update() {
2928435933ddSDimitry Andric   if (m_rsmodules.size() > 0) {
2929435933ddSDimitry Andric     if (!m_initiated) {
29301c3bbb01SEd Maste       Initiate();
29311c3bbb01SEd Maste     }
29321c3bbb01SEd Maste   }
29331c3bbb01SEd Maste }
29341c3bbb01SEd Maste 
WarnIfVersionMismatch(lldb_private::Stream * s) const29358e0f8b8cSDimitry Andric void RSModuleDescriptor::WarnIfVersionMismatch(lldb_private::Stream *s) const {
29368e0f8b8cSDimitry Andric   if (!s)
29378e0f8b8cSDimitry Andric     return;
29388e0f8b8cSDimitry Andric 
29398e0f8b8cSDimitry Andric   if (m_slang_version.empty() || m_bcc_version.empty()) {
29408e0f8b8cSDimitry Andric     s->PutCString("WARNING: Unknown bcc or slang (llvm-rs-cc) version; debug "
29418e0f8b8cSDimitry Andric                   "experience may be unreliable");
29428e0f8b8cSDimitry Andric     s->EOL();
29438e0f8b8cSDimitry Andric   } else if (m_slang_version != m_bcc_version) {
29448e0f8b8cSDimitry Andric     s->Printf("WARNING: The debug info emitted by the slang frontend "
29458e0f8b8cSDimitry Andric               "(llvm-rs-cc) used to build this module (%s) does not match the "
29468e0f8b8cSDimitry Andric               "version of bcc used to generate the debug information (%s). "
29478e0f8b8cSDimitry Andric               "This is an unsupported configuration and may result in a poor "
29488e0f8b8cSDimitry Andric               "debugging experience; proceed with caution",
29498e0f8b8cSDimitry Andric               m_slang_version.c_str(), m_bcc_version.c_str());
29508e0f8b8cSDimitry Andric     s->EOL();
29518e0f8b8cSDimitry Andric   }
29528e0f8b8cSDimitry Andric }
29538e0f8b8cSDimitry Andric 
ParsePragmaCount(llvm::StringRef * lines,size_t n_lines)2954435933ddSDimitry Andric bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
2955435933ddSDimitry Andric                                           size_t n_lines) {
2956435933ddSDimitry Andric   // Skip the pragma prototype line
2957435933ddSDimitry Andric   ++lines;
2958435933ddSDimitry Andric   for (; n_lines--; ++lines) {
2959435933ddSDimitry Andric     const auto kv_pair = lines->split(" - ");
2960435933ddSDimitry Andric     m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
2961435933ddSDimitry Andric   }
2962435933ddSDimitry Andric   return true;
2963435933ddSDimitry Andric }
29641c3bbb01SEd Maste 
ParseExportReduceCount(llvm::StringRef * lines,size_t n_lines)2965435933ddSDimitry Andric bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
2966435933ddSDimitry Andric                                                 size_t n_lines) {
2967435933ddSDimitry Andric   // The list of reduction kernels in the `.rs.info` symbol is of the form
2968435933ddSDimitry Andric   // "signature - accumulatordatasize - reduction_name - initializer_name -
29694ba319b5SDimitry Andric   // accumulator_name - combiner_name - outconverter_name - halter_name" Where
29704ba319b5SDimitry Andric   // a function is not explicitly named by the user, or is not generated by the
29714ba319b5SDimitry Andric   // compiler, it is named "." so the dash separated list should always be 8
29724ba319b5SDimitry Andric   // items long
2973435933ddSDimitry Andric   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
2974435933ddSDimitry Andric   // Skip the exportReduceCount line
2975435933ddSDimitry Andric   ++lines;
2976435933ddSDimitry Andric   for (; n_lines--; ++lines) {
2977435933ddSDimitry Andric     llvm::SmallVector<llvm::StringRef, 8> spec;
2978435933ddSDimitry Andric     lines->split(spec, " - ");
2979435933ddSDimitry Andric     if (spec.size() != 8) {
2980435933ddSDimitry Andric       if (spec.size() < 8) {
2981435933ddSDimitry Andric         if (log)
2982435933ddSDimitry Andric           log->Error("Error parsing RenderScript reduction spec. wrong number "
2983435933ddSDimitry Andric                      "of fields");
2984435933ddSDimitry Andric         return false;
2985435933ddSDimitry Andric       } else if (log)
2986435933ddSDimitry Andric         log->Warning("Extraneous members in reduction spec: '%s'",
2987435933ddSDimitry Andric                      lines->str().c_str());
2988435933ddSDimitry Andric     }
2989435933ddSDimitry Andric 
2990435933ddSDimitry Andric     const auto sig_s = spec[0];
2991435933ddSDimitry Andric     uint32_t sig;
2992435933ddSDimitry Andric     if (sig_s.getAsInteger(10, sig)) {
2993435933ddSDimitry Andric       if (log)
2994435933ddSDimitry Andric         log->Error("Error parsing Renderscript reduction spec: invalid kernel "
2995435933ddSDimitry Andric                    "signature: '%s'",
2996435933ddSDimitry Andric                    sig_s.str().c_str());
2997435933ddSDimitry Andric       return false;
2998435933ddSDimitry Andric     }
2999435933ddSDimitry Andric 
3000435933ddSDimitry Andric     const auto accum_data_size_s = spec[1];
3001435933ddSDimitry Andric     uint32_t accum_data_size;
3002435933ddSDimitry Andric     if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
3003435933ddSDimitry Andric       if (log)
3004435933ddSDimitry Andric         log->Error("Error parsing Renderscript reduction spec: invalid "
3005435933ddSDimitry Andric                    "accumulator data size %s",
3006435933ddSDimitry Andric                    accum_data_size_s.str().c_str());
3007435933ddSDimitry Andric       return false;
3008435933ddSDimitry Andric     }
3009435933ddSDimitry Andric 
3010435933ddSDimitry Andric     if (log)
3011435933ddSDimitry Andric       log->Printf("Found RenderScript reduction '%s'", spec[2].str().c_str());
3012435933ddSDimitry Andric 
3013435933ddSDimitry Andric     m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
3014435933ddSDimitry Andric                                                  spec[2], spec[3], spec[4],
3015435933ddSDimitry Andric                                                  spec[5], spec[6], spec[7]));
3016435933ddSDimitry Andric   }
3017435933ddSDimitry Andric   return true;
3018435933ddSDimitry Andric }
3019435933ddSDimitry Andric 
ParseVersionInfo(llvm::StringRef * lines,size_t n_lines)30208e0f8b8cSDimitry Andric bool RSModuleDescriptor::ParseVersionInfo(llvm::StringRef *lines,
30218e0f8b8cSDimitry Andric                                           size_t n_lines) {
30228e0f8b8cSDimitry Andric   // Skip the versionInfo line
30238e0f8b8cSDimitry Andric   ++lines;
30248e0f8b8cSDimitry Andric   for (; n_lines--; ++lines) {
30258e0f8b8cSDimitry Andric     // We're only interested in bcc and slang versions, and ignore all other
30268e0f8b8cSDimitry Andric     // versionInfo lines
30278e0f8b8cSDimitry Andric     const auto kv_pair = lines->split(" - ");
30288e0f8b8cSDimitry Andric     if (kv_pair.first == "slang")
30298e0f8b8cSDimitry Andric       m_slang_version = kv_pair.second.str();
30308e0f8b8cSDimitry Andric     else if (kv_pair.first == "bcc")
30318e0f8b8cSDimitry Andric       m_bcc_version = kv_pair.second.str();
30328e0f8b8cSDimitry Andric   }
30338e0f8b8cSDimitry Andric   return true;
30348e0f8b8cSDimitry Andric }
30358e0f8b8cSDimitry Andric 
ParseExportForeachCount(llvm::StringRef * lines,size_t n_lines)3036435933ddSDimitry Andric bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
3037435933ddSDimitry Andric                                                  size_t n_lines) {
3038435933ddSDimitry Andric   // Skip the exportForeachCount line
3039435933ddSDimitry Andric   ++lines;
3040435933ddSDimitry Andric   for (; n_lines--; ++lines) {
3041435933ddSDimitry Andric     uint32_t slot;
3042435933ddSDimitry Andric     // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
3043435933ddSDimitry Andric     // pair per line
3044435933ddSDimitry Andric     const auto kv_pair = lines->split(" - ");
3045435933ddSDimitry Andric     if (kv_pair.first.getAsInteger(10, slot))
3046435933ddSDimitry Andric       return false;
3047435933ddSDimitry Andric     m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
3048435933ddSDimitry Andric   }
3049435933ddSDimitry Andric   return true;
3050435933ddSDimitry Andric }
3051435933ddSDimitry Andric 
ParseExportVarCount(llvm::StringRef * lines,size_t n_lines)3052435933ddSDimitry Andric bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
3053435933ddSDimitry Andric                                              size_t n_lines) {
3054435933ddSDimitry Andric   // Skip the ExportVarCount line
3055435933ddSDimitry Andric   ++lines;
3056435933ddSDimitry Andric   for (; n_lines--; ++lines)
3057435933ddSDimitry Andric     m_globals.push_back(RSGlobalDescriptor(this, *lines));
3058435933ddSDimitry Andric   return true;
3059435933ddSDimitry Andric }
3060435933ddSDimitry Andric 
3061435933ddSDimitry Andric // The .rs.info symbol in renderscript modules contains a string which needs to
30624ba319b5SDimitry Andric // be parsed. The string is basic and is parsed on a line by line basis.
ParseRSInfo()3063435933ddSDimitry Andric bool RSModuleDescriptor::ParseRSInfo() {
30644bb0738eSEd Maste   assert(m_module);
3065435933ddSDimitry Andric   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3066435933ddSDimitry Andric   const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
3067435933ddSDimitry Andric       ConstString(".rs.info"), eSymbolTypeData);
30684bb0738eSEd Maste   if (!info_sym)
30694bb0738eSEd Maste     return false;
30704bb0738eSEd Maste 
30711c3bbb01SEd Maste   const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
30724bb0738eSEd Maste   if (addr == LLDB_INVALID_ADDRESS)
30734bb0738eSEd Maste     return false;
30744bb0738eSEd Maste 
30751c3bbb01SEd Maste   const addr_t size = info_sym->GetByteSize();
30761c3bbb01SEd Maste   const FileSpec fs = m_module->GetFileSpec();
30771c3bbb01SEd Maste 
3078*b5893f02SDimitry Andric   auto buffer =
3079*b5893f02SDimitry Andric       FileSystem::Instance().CreateDataBuffer(fs.GetPath(), size, addr);
30801c3bbb01SEd Maste   if (!buffer)
30811c3bbb01SEd Maste     return false;
30821c3bbb01SEd Maste 
30834bb0738eSEd Maste   // split rs.info. contents into lines
3084435933ddSDimitry Andric   llvm::SmallVector<llvm::StringRef, 128> info_lines;
30851c3bbb01SEd Maste   {
3086435933ddSDimitry Andric     const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
3087435933ddSDimitry Andric     raw_rs_info.split(info_lines, '\n');
3088435933ddSDimitry Andric     if (log)
3089435933ddSDimitry Andric       log->Printf("'.rs.info symbol for '%s':\n%s",
3090435933ddSDimitry Andric                   m_module->GetFileSpec().GetCString(),
3091435933ddSDimitry Andric                   raw_rs_info.str().c_str());
30924bb0738eSEd Maste   }
30934bb0738eSEd Maste 
3094435933ddSDimitry Andric   enum {
3095435933ddSDimitry Andric     eExportVar,
3096435933ddSDimitry Andric     eExportForEach,
3097435933ddSDimitry Andric     eExportReduce,
3098435933ddSDimitry Andric     ePragma,
3099435933ddSDimitry Andric     eBuildChecksum,
31008e0f8b8cSDimitry Andric     eObjectSlot,
31018e0f8b8cSDimitry Andric     eVersionInfo,
3102435933ddSDimitry Andric   };
3103435933ddSDimitry Andric 
3104435933ddSDimitry Andric   const auto rs_info_handler = [](llvm::StringRef name) -> int {
3105435933ddSDimitry Andric     return llvm::StringSwitch<int>(name)
3106435933ddSDimitry Andric         // The number of visible global variables in the script
3107435933ddSDimitry Andric         .Case("exportVarCount", eExportVar)
3108435933ddSDimitry Andric         // The number of RenderScrip `forEach` kernels __attribute__((kernel))
3109435933ddSDimitry Andric         .Case("exportForEachCount", eExportForEach)
3110435933ddSDimitry Andric         // The number of generalreductions: This marked in the script by
3111435933ddSDimitry Andric         // `#pragma reduce()`
3112435933ddSDimitry Andric         .Case("exportReduceCount", eExportReduce)
3113435933ddSDimitry Andric         // Total count of all RenderScript specific `#pragmas` used in the
3114435933ddSDimitry Andric         // script
3115435933ddSDimitry Andric         .Case("pragmaCount", ePragma)
3116435933ddSDimitry Andric         .Case("objectSlotCount", eObjectSlot)
31178e0f8b8cSDimitry Andric         .Case("versionInfo", eVersionInfo)
3118435933ddSDimitry Andric         .Default(-1);
3119435933ddSDimitry Andric   };
31204bb0738eSEd Maste 
31214bb0738eSEd Maste   // parse all text lines of .rs.info
3122435933ddSDimitry Andric   for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
3123435933ddSDimitry Andric     const auto kv_pair = line->split(": ");
3124435933ddSDimitry Andric     const auto key = kv_pair.first;
3125435933ddSDimitry Andric     const auto val = kv_pair.second.trim();
3126435933ddSDimitry Andric 
3127435933ddSDimitry Andric     const auto handler = rs_info_handler(key);
3128435933ddSDimitry Andric     if (handler == -1)
3129435933ddSDimitry Andric       continue;
31304ba319b5SDimitry Andric     // getAsInteger returns `true` on an error condition - we're only
31314ba319b5SDimitry Andric     // interested in numeric fields at the moment
3132435933ddSDimitry Andric     uint64_t n_lines;
3133435933ddSDimitry Andric     if (val.getAsInteger(10, n_lines)) {
3134f678e45dSDimitry Andric       LLDB_LOGV(log, "Failed to parse non-numeric '.rs.info' section {0}",
3135f678e45dSDimitry Andric                 line->str());
3136435933ddSDimitry Andric       continue;
3137435933ddSDimitry Andric     }
3138435933ddSDimitry Andric     if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
3139435933ddSDimitry Andric       return false;
3140435933ddSDimitry Andric 
3141435933ddSDimitry Andric     bool success = false;
3142435933ddSDimitry Andric     switch (handler) {
3143435933ddSDimitry Andric     case eExportVar:
3144435933ddSDimitry Andric       success = ParseExportVarCount(line, n_lines);
3145435933ddSDimitry Andric       break;
3146435933ddSDimitry Andric     case eExportForEach:
3147435933ddSDimitry Andric       success = ParseExportForeachCount(line, n_lines);
3148435933ddSDimitry Andric       break;
3149435933ddSDimitry Andric     case eExportReduce:
3150435933ddSDimitry Andric       success = ParseExportReduceCount(line, n_lines);
3151435933ddSDimitry Andric       break;
3152435933ddSDimitry Andric     case ePragma:
3153435933ddSDimitry Andric       success = ParsePragmaCount(line, n_lines);
3154435933ddSDimitry Andric       break;
31558e0f8b8cSDimitry Andric     case eVersionInfo:
31568e0f8b8cSDimitry Andric       success = ParseVersionInfo(line, n_lines);
31578e0f8b8cSDimitry Andric       break;
3158435933ddSDimitry Andric     default: {
3159435933ddSDimitry Andric       if (log)
3160435933ddSDimitry Andric         log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__,
3161435933ddSDimitry Andric                     line->str().c_str());
3162435933ddSDimitry Andric       continue;
31634bb0738eSEd Maste     }
31644bb0738eSEd Maste     }
3165435933ddSDimitry Andric     if (!success)
3166435933ddSDimitry Andric       return false;
3167435933ddSDimitry Andric     line += n_lines;
3168435933ddSDimitry Andric   }
3169435933ddSDimitry Andric   return info_lines.size() > 0;
31701c3bbb01SEd Maste }
31711c3bbb01SEd Maste 
DumpStatus(Stream & strm) const31725517e702SDimitry Andric void RenderScriptRuntime::DumpStatus(Stream &strm) const {
3173435933ddSDimitry Andric   if (m_libRS) {
31741c3bbb01SEd Maste     strm.Printf("Runtime Library discovered.");
31751c3bbb01SEd Maste     strm.EOL();
31761c3bbb01SEd Maste   }
3177435933ddSDimitry Andric   if (m_libRSDriver) {
31781c3bbb01SEd Maste     strm.Printf("Runtime Driver discovered.");
31791c3bbb01SEd Maste     strm.EOL();
31801c3bbb01SEd Maste   }
3181435933ddSDimitry Andric   if (m_libRSCpuRef) {
31821c3bbb01SEd Maste     strm.Printf("CPU Reference Implementation discovered.");
31831c3bbb01SEd Maste     strm.EOL();
31841c3bbb01SEd Maste   }
31851c3bbb01SEd Maste 
3186435933ddSDimitry Andric   if (m_runtimeHooks.size()) {
31871c3bbb01SEd Maste     strm.Printf("Runtime functions hooked:");
31881c3bbb01SEd Maste     strm.EOL();
3189435933ddSDimitry Andric     for (auto b : m_runtimeHooks) {
31901c3bbb01SEd Maste       strm.Indent(b.second->defn->name);
31911c3bbb01SEd Maste       strm.EOL();
31921c3bbb01SEd Maste     }
3193435933ddSDimitry Andric   } else {
31941c3bbb01SEd Maste     strm.Printf("Runtime is not hooked.");
31951c3bbb01SEd Maste     strm.EOL();
31961c3bbb01SEd Maste   }
31971c3bbb01SEd Maste }
31981c3bbb01SEd Maste 
DumpContexts(Stream & strm) const3199435933ddSDimitry Andric void RenderScriptRuntime::DumpContexts(Stream &strm) const {
32001c3bbb01SEd Maste   strm.Printf("Inferred RenderScript Contexts:");
32011c3bbb01SEd Maste   strm.EOL();
32021c3bbb01SEd Maste   strm.IndentMore();
32031c3bbb01SEd Maste 
32041c3bbb01SEd Maste   std::map<addr_t, uint64_t> contextReferences;
32051c3bbb01SEd Maste 
32064ba319b5SDimitry Andric   // Iterate over all of the currently discovered scripts. Note: We cant push
32074ba319b5SDimitry Andric   // or pop from m_scripts inside this loop or it may invalidate script.
3208435933ddSDimitry Andric   for (const auto &script : m_scripts) {
32099f2f44ceSEd Maste     if (!script->context.isValid())
32109f2f44ceSEd Maste       continue;
32119f2f44ceSEd Maste     lldb::addr_t context = *script->context;
32129f2f44ceSEd Maste 
3213435933ddSDimitry Andric     if (contextReferences.find(context) != contextReferences.end()) {
32149f2f44ceSEd Maste       contextReferences[context]++;
3215435933ddSDimitry Andric     } else {
32169f2f44ceSEd Maste       contextReferences[context] = 1;
32171c3bbb01SEd Maste     }
32181c3bbb01SEd Maste   }
32191c3bbb01SEd Maste 
3220435933ddSDimitry Andric   for (const auto &cRef : contextReferences) {
3221435933ddSDimitry Andric     strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
3222435933ddSDimitry Andric                 cRef.first, cRef.second);
32231c3bbb01SEd Maste     strm.EOL();
32241c3bbb01SEd Maste   }
32251c3bbb01SEd Maste   strm.IndentLess();
32261c3bbb01SEd Maste }
32271c3bbb01SEd Maste 
DumpKernels(Stream & strm) const3228435933ddSDimitry Andric void RenderScriptRuntime::DumpKernels(Stream &strm) const {
32291c3bbb01SEd Maste   strm.Printf("RenderScript Kernels:");
32301c3bbb01SEd Maste   strm.EOL();
32311c3bbb01SEd Maste   strm.IndentMore();
3232435933ddSDimitry Andric   for (const auto &module : m_rsmodules) {
32331c3bbb01SEd Maste     strm.Printf("Resource '%s':", module->m_resname.c_str());
32341c3bbb01SEd Maste     strm.EOL();
3235435933ddSDimitry Andric     for (const auto &kernel : module->m_kernels) {
32361c3bbb01SEd Maste       strm.Indent(kernel.m_name.AsCString());
32371c3bbb01SEd Maste       strm.EOL();
32381c3bbb01SEd Maste     }
32391c3bbb01SEd Maste   }
32401c3bbb01SEd Maste   strm.IndentLess();
32411c3bbb01SEd Maste }
32421c3bbb01SEd Maste 
32439f2f44ceSEd Maste RenderScriptRuntime::AllocationDetails *
FindAllocByID(Stream & strm,const uint32_t alloc_id)3244435933ddSDimitry Andric RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
32459f2f44ceSEd Maste   AllocationDetails *alloc = nullptr;
32469f2f44ceSEd Maste 
32479f2f44ceSEd Maste   // See if we can find allocation using id as an index;
3248435933ddSDimitry Andric   if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
3249435933ddSDimitry Andric       m_allocations[alloc_id - 1]->id == alloc_id) {
32509f2f44ceSEd Maste     alloc = m_allocations[alloc_id - 1].get();
32519f2f44ceSEd Maste     return alloc;
32529f2f44ceSEd Maste   }
32539f2f44ceSEd Maste 
32549f2f44ceSEd Maste   // Fallback to searching
3255435933ddSDimitry Andric   for (const auto &a : m_allocations) {
3256435933ddSDimitry Andric     if (a->id == alloc_id) {
32579f2f44ceSEd Maste       alloc = a.get();
32589f2f44ceSEd Maste       break;
32599f2f44ceSEd Maste     }
32609f2f44ceSEd Maste   }
32619f2f44ceSEd Maste 
3262435933ddSDimitry Andric   if (alloc == nullptr) {
3263435933ddSDimitry Andric     strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
3264435933ddSDimitry Andric                 alloc_id);
32659f2f44ceSEd Maste     strm.EOL();
32669f2f44ceSEd Maste   }
32679f2f44ceSEd Maste 
32689f2f44ceSEd Maste   return alloc;
32699f2f44ceSEd Maste }
32709f2f44ceSEd Maste 
3271435933ddSDimitry Andric // Prints the contents of an allocation to the output stream, which may be a
3272435933ddSDimitry Andric // file
DumpAllocation(Stream & strm,StackFrame * frame_ptr,const uint32_t id)3273435933ddSDimitry Andric bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
3274435933ddSDimitry Andric                                          const uint32_t id) {
32759f2f44ceSEd Maste   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
32769f2f44ceSEd Maste 
32779f2f44ceSEd Maste   // Check we can find the desired allocation
32789f2f44ceSEd Maste   AllocationDetails *alloc = FindAllocByID(strm, id);
32799f2f44ceSEd Maste   if (!alloc)
32809f2f44ceSEd Maste     return false; // FindAllocByID() will print error message for us here
32819f2f44ceSEd Maste 
32829f2f44ceSEd Maste   if (log)
3283435933ddSDimitry Andric     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
3284435933ddSDimitry Andric                 *alloc->address.get());
32859f2f44ceSEd Maste 
32869f2f44ceSEd Maste   // Check we have information about the allocation, if not calculate it
3287435933ddSDimitry Andric   if (alloc->ShouldRefresh()) {
32889f2f44ceSEd Maste     if (log)
3289435933ddSDimitry Andric       log->Printf("%s - allocation details not calculated yet, jitting info.",
3290435933ddSDimitry Andric                   __FUNCTION__);
32919f2f44ceSEd Maste 
32929f2f44ceSEd Maste     // JIT all the allocation information
3293435933ddSDimitry Andric     if (!RefreshAllocation(alloc, frame_ptr)) {
32949f2f44ceSEd Maste       strm.Printf("Error: Couldn't JIT allocation details");
32959f2f44ceSEd Maste       strm.EOL();
32969f2f44ceSEd Maste       return false;
32979f2f44ceSEd Maste     }
32989f2f44ceSEd Maste   }
32999f2f44ceSEd Maste 
33009f2f44ceSEd Maste   // Establish format and size of each data element
33014bb0738eSEd Maste   const uint32_t vec_size = *alloc->element.type_vec_size.get();
33029f2f44ceSEd Maste   const Element::DataType type = *alloc->element.type.get();
33039f2f44ceSEd Maste 
3304435933ddSDimitry Andric   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
3305435933ddSDimitry Andric          "Invalid allocation type");
33069f2f44ceSEd Maste 
33079f2f44ceSEd Maste   lldb::Format format;
33089f2f44ceSEd Maste   if (type >= Element::RS_TYPE_ELEMENT)
33099f2f44ceSEd Maste     format = eFormatHex;
33109f2f44ceSEd Maste   else
3311435933ddSDimitry Andric     format = vec_size == 1
3312435933ddSDimitry Andric                  ? static_cast<lldb::Format>(
3313435933ddSDimitry Andric                        AllocationDetails::RSTypeToFormat[type][eFormatSingle])
3314435933ddSDimitry Andric                  : static_cast<lldb::Format>(
3315435933ddSDimitry Andric                        AllocationDetails::RSTypeToFormat[type][eFormatVector]);
33169f2f44ceSEd Maste 
33174bb0738eSEd Maste   const uint32_t data_size = *alloc->element.datum_size.get();
33189f2f44ceSEd Maste 
33199f2f44ceSEd Maste   if (log)
3320435933ddSDimitry Andric     log->Printf("%s - element size %" PRIu32 " bytes, including padding",
3321435933ddSDimitry Andric                 __FUNCTION__, data_size);
33229f2f44ceSEd Maste 
33239f2f44ceSEd Maste   // Allocate a buffer to copy data into
33249f2f44ceSEd Maste   std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3325435933ddSDimitry Andric   if (!buffer) {
33269f2f44ceSEd Maste     strm.Printf("Error: Couldn't read allocation data");
33279f2f44ceSEd Maste     strm.EOL();
33289f2f44ceSEd Maste     return false;
33299f2f44ceSEd Maste   }
33309f2f44ceSEd Maste 
33319f2f44ceSEd Maste   // Calculate stride between rows as there may be padding at end of rows since
33329f2f44ceSEd Maste   // allocated memory is 16-byte aligned
3333435933ddSDimitry Andric   if (!alloc->stride.isValid()) {
33349f2f44ceSEd Maste     if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
33359f2f44ceSEd Maste       alloc->stride = 0;
3336435933ddSDimitry Andric     else if (!JITAllocationStride(alloc, frame_ptr)) {
33379f2f44ceSEd Maste       strm.Printf("Error: Couldn't calculate allocation row stride");
33389f2f44ceSEd Maste       strm.EOL();
33399f2f44ceSEd Maste       return false;
33409f2f44ceSEd Maste     }
33419f2f44ceSEd Maste   }
33424bb0738eSEd Maste   const uint32_t stride = *alloc->stride.get();
33434bb0738eSEd Maste   const uint32_t size = *alloc->size.get(); // Size of whole allocation
3344435933ddSDimitry Andric   const uint32_t padding =
3345435933ddSDimitry Andric       alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
33469f2f44ceSEd Maste   if (log)
3347435933ddSDimitry Andric     log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32
3348435933ddSDimitry Andric                 " bytes, padding %" PRIu32,
33494bb0738eSEd Maste                 __FUNCTION__, stride, size, padding);
33509f2f44ceSEd Maste 
33519f2f44ceSEd Maste   // Find dimensions used to index loops, so need to be non-zero
33524bb0738eSEd Maste   uint32_t dim_x = alloc->dimension.get()->dim_1;
33539f2f44ceSEd Maste   dim_x = dim_x == 0 ? 1 : dim_x;
33549f2f44ceSEd Maste 
33554bb0738eSEd Maste   uint32_t dim_y = alloc->dimension.get()->dim_2;
33569f2f44ceSEd Maste   dim_y = dim_y == 0 ? 1 : dim_y;
33579f2f44ceSEd Maste 
33584bb0738eSEd Maste   uint32_t dim_z = alloc->dimension.get()->dim_3;
33599f2f44ceSEd Maste   dim_z = dim_z == 0 ? 1 : dim_z;
33609f2f44ceSEd Maste 
33619f2f44ceSEd Maste   // Use data extractor to format output
3362435933ddSDimitry Andric   const uint32_t target_ptr_size =
3363435933ddSDimitry Andric       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3364435933ddSDimitry Andric   DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
3365435933ddSDimitry Andric                            target_ptr_size);
33669f2f44ceSEd Maste 
33674bb0738eSEd Maste   uint32_t offset = 0;   // Offset in buffer to next element to be printed
33684bb0738eSEd Maste   uint32_t prev_row = 0; // Offset to the start of the previous row
33699f2f44ceSEd Maste 
33709f2f44ceSEd Maste   // Iterate over allocation dimensions, printing results to user
33719f2f44ceSEd Maste   strm.Printf("Data (X, Y, Z):");
3372435933ddSDimitry Andric   for (uint32_t z = 0; z < dim_z; ++z) {
3373435933ddSDimitry Andric     for (uint32_t y = 0; y < dim_y; ++y) {
33749f2f44ceSEd Maste       // Use stride to index start of next row.
33759f2f44ceSEd Maste       if (!(y == 0 && z == 0))
33769f2f44ceSEd Maste         offset = prev_row + stride;
33779f2f44ceSEd Maste       prev_row = offset;
33789f2f44ceSEd Maste 
33799f2f44ceSEd Maste       // Print each element in the row individually
3380435933ddSDimitry Andric       for (uint32_t x = 0; x < dim_x; ++x) {
33814bb0738eSEd Maste         strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3382435933ddSDimitry Andric         if ((type == Element::RS_TYPE_NONE) &&
3383435933ddSDimitry Andric             (alloc->element.children.size() > 0) &&
3384435933ddSDimitry Andric             (alloc->element.type_name != Element::GetFallbackStructName())) {
33854ba319b5SDimitry Andric           // Here we are dumping an Element of struct type. This is done using
33864ba319b5SDimitry Andric           // expression evaluation with the name of the struct type and pointer
33874ba319b5SDimitry Andric           // to element. Don't print the name of the resulting expression,
33884ba319b5SDimitry Andric           // since this will be '$[0-9]+'
33899f2f44ceSEd Maste           DumpValueObjectOptions expr_options;
33909f2f44ceSEd Maste           expr_options.SetHideName(true);
33919f2f44ceSEd Maste 
33924ba319b5SDimitry Andric           // Setup expression as dereferencing a pointer cast to element
33934ba319b5SDimitry Andric           // address.
33949f2f44ceSEd Maste           char expr_char_buffer[jit_max_expr_size];
3395435933ddSDimitry Andric           int written =
3396435933ddSDimitry Andric               snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3397435933ddSDimitry Andric                        alloc->element.type_name.AsCString(),
3398435933ddSDimitry Andric                        *alloc->data_ptr.get() + offset);
33999f2f44ceSEd Maste 
3400435933ddSDimitry Andric           if (written < 0 || written >= jit_max_expr_size) {
34019f2f44ceSEd Maste             if (log)
34024bb0738eSEd Maste               log->Printf("%s - error in snprintf().", __FUNCTION__);
34039f2f44ceSEd Maste             continue;
34049f2f44ceSEd Maste           }
34059f2f44ceSEd Maste 
34069f2f44ceSEd Maste           // Evaluate expression
34079f2f44ceSEd Maste           ValueObjectSP expr_result;
3408435933ddSDimitry Andric           GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3409435933ddSDimitry Andric                                                        frame_ptr, expr_result);
34109f2f44ceSEd Maste 
34119f2f44ceSEd Maste           // Print the results to our stream.
34129f2f44ceSEd Maste           expr_result->Dump(strm, expr_options);
3413435933ddSDimitry Andric         } else {
3414f678e45dSDimitry Andric           DumpDataExtractor(alloc_data, &strm, offset, format,
3415f678e45dSDimitry Andric                             data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0,
3416f678e45dSDimitry Andric                             0);
34179f2f44ceSEd Maste         }
34189f2f44ceSEd Maste         offset += data_size;
34199f2f44ceSEd Maste       }
34209f2f44ceSEd Maste     }
34219f2f44ceSEd Maste   }
34229f2f44ceSEd Maste   strm.EOL();
34239f2f44ceSEd Maste 
34249f2f44ceSEd Maste   return true;
34259f2f44ceSEd Maste }
34269f2f44ceSEd Maste 
34274ba319b5SDimitry Andric // Function recalculates all our cached information about allocations by
34284ba319b5SDimitry Andric // jitting the RS runtime regarding each allocation we know about. Returns true
34294ba319b5SDimitry Andric // if all allocations could be recomputed, false otherwise.
RecomputeAllAllocations(Stream & strm,StackFrame * frame_ptr)3430435933ddSDimitry Andric bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3431435933ddSDimitry Andric                                                   StackFrame *frame_ptr) {
34324bb0738eSEd Maste   bool success = true;
3433435933ddSDimitry Andric   for (auto &alloc : m_allocations) {
34344bb0738eSEd Maste     // JIT current allocation information
3435435933ddSDimitry Andric     if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3436435933ddSDimitry Andric       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3437435933ddSDimitry Andric                   "\n",
3438435933ddSDimitry Andric                   alloc->id);
34394bb0738eSEd Maste       success = false;
34404bb0738eSEd Maste     }
34414bb0738eSEd Maste   }
34424bb0738eSEd Maste 
34434bb0738eSEd Maste   if (success)
34444bb0738eSEd Maste     strm.Printf("All allocations successfully recomputed");
34454bb0738eSEd Maste   strm.EOL();
34464bb0738eSEd Maste 
34474bb0738eSEd Maste   return success;
34484bb0738eSEd Maste }
34494bb0738eSEd Maste 
3450435933ddSDimitry Andric // Prints information regarding currently loaded allocations. These details are
3451435933ddSDimitry Andric // gathered by jitting the runtime, which has as latency. Index parameter
3452435933ddSDimitry Andric // specifies a single allocation ID to print, or a zero value to print them all
ListAllocations(Stream & strm,StackFrame * frame_ptr,const uint32_t index)3453435933ddSDimitry Andric void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3454435933ddSDimitry Andric                                           const uint32_t index) {
34559f2f44ceSEd Maste   strm.Printf("RenderScript Allocations:");
34569f2f44ceSEd Maste   strm.EOL();
34579f2f44ceSEd Maste   strm.IndentMore();
34589f2f44ceSEd Maste 
3459435933ddSDimitry Andric   for (auto &alloc : m_allocations) {
34604bb0738eSEd Maste     // index will only be zero if we want to print all allocations
34614bb0738eSEd Maste     if (index != 0 && index != alloc->id)
34624bb0738eSEd Maste       continue;
34639f2f44ceSEd Maste 
34649f2f44ceSEd Maste     // JIT current allocation information
3465435933ddSDimitry Andric     if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3466435933ddSDimitry Andric       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3467435933ddSDimitry Andric                   alloc->id);
34684bb0738eSEd Maste       strm.EOL();
34699f2f44ceSEd Maste       continue;
34709f2f44ceSEd Maste     }
34719f2f44ceSEd Maste 
34724bb0738eSEd Maste     strm.Printf("%" PRIu32 ":", alloc->id);
34734bb0738eSEd Maste     strm.EOL();
34749f2f44ceSEd Maste     strm.IndentMore();
34759f2f44ceSEd Maste 
34769f2f44ceSEd Maste     strm.Indent("Context: ");
34779f2f44ceSEd Maste     if (!alloc->context.isValid())
34789f2f44ceSEd Maste       strm.Printf("unknown\n");
34799f2f44ceSEd Maste     else
34809f2f44ceSEd Maste       strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
34819f2f44ceSEd Maste 
34829f2f44ceSEd Maste     strm.Indent("Address: ");
34839f2f44ceSEd Maste     if (!alloc->address.isValid())
34849f2f44ceSEd Maste       strm.Printf("unknown\n");
34859f2f44ceSEd Maste     else
34869f2f44ceSEd Maste       strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
34879f2f44ceSEd Maste 
34889f2f44ceSEd Maste     strm.Indent("Data pointer: ");
34899f2f44ceSEd Maste     if (!alloc->data_ptr.isValid())
34909f2f44ceSEd Maste       strm.Printf("unknown\n");
34919f2f44ceSEd Maste     else
34929f2f44ceSEd Maste       strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
34939f2f44ceSEd Maste 
34949f2f44ceSEd Maste     strm.Indent("Dimensions: ");
34959f2f44ceSEd Maste     if (!alloc->dimension.isValid())
34969f2f44ceSEd Maste       strm.Printf("unknown\n");
34979f2f44ceSEd Maste     else
34984bb0738eSEd Maste       strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3499435933ddSDimitry Andric                   alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3500435933ddSDimitry Andric                   alloc->dimension.get()->dim_3);
35019f2f44ceSEd Maste 
35029f2f44ceSEd Maste     strm.Indent("Data Type: ");
3503435933ddSDimitry Andric     if (!alloc->element.type.isValid() ||
3504435933ddSDimitry Andric         !alloc->element.type_vec_size.isValid())
35059f2f44ceSEd Maste       strm.Printf("unknown\n");
3506435933ddSDimitry Andric     else {
35079f2f44ceSEd Maste       const int vector_size = *alloc->element.type_vec_size.get();
35089f2f44ceSEd Maste       Element::DataType type = *alloc->element.type.get();
35099f2f44ceSEd Maste 
35109f2f44ceSEd Maste       if (!alloc->element.type_name.IsEmpty())
35119f2f44ceSEd Maste         strm.Printf("%s\n", alloc->element.type_name.AsCString());
3512435933ddSDimitry Andric       else {
3513435933ddSDimitry Andric         // Enum value isn't monotonous, so doesn't always index
3514435933ddSDimitry Andric         // RsDataTypeToString array
35159f2f44ceSEd Maste         if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3516435933ddSDimitry Andric           type =
3517435933ddSDimitry Andric               static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
35184bb0738eSEd Maste                                              Element::RS_TYPE_MATRIX_2X2 + 1);
35199f2f44ceSEd Maste 
35204bb0738eSEd Maste         if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
35214bb0738eSEd Maste                      sizeof(AllocationDetails::RsDataTypeToString[0])) ||
35224bb0738eSEd Maste             vector_size > 4 || vector_size < 1)
35239f2f44ceSEd Maste           strm.Printf("invalid type\n");
35249f2f44ceSEd Maste         else
3525435933ddSDimitry Andric           strm.Printf(
3526435933ddSDimitry Andric               "%s\n",
3527435933ddSDimitry Andric               AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
35284bb0738eSEd Maste                                                    [vector_size - 1]);
35299f2f44ceSEd Maste       }
35309f2f44ceSEd Maste     }
35319f2f44ceSEd Maste 
35329f2f44ceSEd Maste     strm.Indent("Data Kind: ");
35339f2f44ceSEd Maste     if (!alloc->element.type_kind.isValid())
35349f2f44ceSEd Maste       strm.Printf("unknown\n");
3535435933ddSDimitry Andric     else {
35369f2f44ceSEd Maste       const Element::DataKind kind = *alloc->element.type_kind.get();
35379f2f44ceSEd Maste       if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
35389f2f44ceSEd Maste         strm.Printf("invalid kind\n");
35399f2f44ceSEd Maste       else
3540435933ddSDimitry Andric         strm.Printf(
3541435933ddSDimitry Andric             "%s\n",
3542435933ddSDimitry Andric             AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
35439f2f44ceSEd Maste     }
35449f2f44ceSEd Maste 
35459f2f44ceSEd Maste     strm.EOL();
35469f2f44ceSEd Maste     strm.IndentLess();
35479f2f44ceSEd Maste   }
35489f2f44ceSEd Maste   strm.IndentLess();
35499f2f44ceSEd Maste }
35509f2f44ceSEd Maste 
35519f2f44ceSEd Maste // Set breakpoints on every kernel found in RS module
BreakOnModuleKernels(const RSModuleDescriptorSP rsmodule_sp)3552435933ddSDimitry Andric void RenderScriptRuntime::BreakOnModuleKernels(
3553435933ddSDimitry Andric     const RSModuleDescriptorSP rsmodule_sp) {
3554435933ddSDimitry Andric   for (const auto &kernel : rsmodule_sp->m_kernels) {
35559f2f44ceSEd Maste     // Don't set breakpoint on 'root' kernel
35569f2f44ceSEd Maste     if (strcmp(kernel.m_name.AsCString(), "root") == 0)
35579f2f44ceSEd Maste       continue;
35589f2f44ceSEd Maste 
35599f2f44ceSEd Maste     CreateKernelBreakpoint(kernel.m_name);
35609f2f44ceSEd Maste   }
35619f2f44ceSEd Maste }
35629f2f44ceSEd Maste 
3563435933ddSDimitry Andric // Method is internally called by the 'kernel breakpoint all' command to enable
3564435933ddSDimitry Andric // or disable breaking on all kernels. When do_break is true we want to enable
3565435933ddSDimitry Andric // this functionality. When do_break is false we want to disable it.
SetBreakAllKernels(bool do_break,TargetSP target)3566435933ddSDimitry Andric void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3567435933ddSDimitry Andric   Log *log(
3568435933ddSDimitry Andric       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
35699f2f44ceSEd Maste 
35709f2f44ceSEd Maste   InitSearchFilter(target);
35719f2f44ceSEd Maste 
35729f2f44ceSEd Maste   // Set breakpoints on all the kernels
3573435933ddSDimitry Andric   if (do_break && !m_breakAllKernels) {
35749f2f44ceSEd Maste     m_breakAllKernels = true;
35759f2f44ceSEd Maste 
35769f2f44ceSEd Maste     for (const auto &module : m_rsmodules)
35779f2f44ceSEd Maste       BreakOnModuleKernels(module);
35789f2f44ceSEd Maste 
35799f2f44ceSEd Maste     if (log)
3580435933ddSDimitry Andric       log->Printf("%s(True) - breakpoints set on all currently loaded kernels.",
3581435933ddSDimitry Andric                   __FUNCTION__);
3582435933ddSDimitry Andric   } else if (!do_break &&
3583435933ddSDimitry Andric              m_breakAllKernels) // Breakpoints won't be set on any new kernels.
35849f2f44ceSEd Maste   {
35859f2f44ceSEd Maste     m_breakAllKernels = false;
35869f2f44ceSEd Maste 
35879f2f44ceSEd Maste     if (log)
3588435933ddSDimitry Andric       log->Printf("%s(False) - breakpoints no longer automatically set.",
3589435933ddSDimitry Andric                   __FUNCTION__);
35909f2f44ceSEd Maste   }
35919f2f44ceSEd Maste }
35929f2f44ceSEd Maste 
35934ba319b5SDimitry Andric // Given the name of a kernel this function creates a breakpoint using our own
35944ba319b5SDimitry Andric // breakpoint resolver, and returns the Breakpoint shared pointer.
35959f2f44ceSEd Maste BreakpointSP
CreateKernelBreakpoint(const ConstString & name)3596435933ddSDimitry Andric RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) {
3597435933ddSDimitry Andric   Log *log(
3598435933ddSDimitry Andric       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
35999f2f44ceSEd Maste 
3600435933ddSDimitry Andric   if (!m_filtersp) {
36019f2f44ceSEd Maste     if (log)
36024bb0738eSEd Maste       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
36039f2f44ceSEd Maste     return nullptr;
36049f2f44ceSEd Maste   }
36059f2f44ceSEd Maste 
36069f2f44ceSEd Maste   BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3607acac075bSDimitry Andric   Target &target = GetProcess()->GetTarget();
3608acac075bSDimitry Andric   BreakpointSP bp = target.CreateBreakpoint(
3609435933ddSDimitry Andric       m_filtersp, resolver_sp, false, false, false);
36109f2f44ceSEd Maste 
3611435933ddSDimitry Andric   // Give RS breakpoints a specific name, so the user can manipulate them as a
3612435933ddSDimitry Andric   // group.
36135517e702SDimitry Andric   Status err;
3614acac075bSDimitry Andric   target.AddNameToBreakpoint(bp, "RenderScriptKernel", err);
3615acac075bSDimitry Andric   if (err.Fail() && log)
3616435933ddSDimitry Andric     if (log)
3617435933ddSDimitry Andric       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3618435933ddSDimitry Andric                   err.AsCString());
36199f2f44ceSEd Maste 
36209f2f44ceSEd Maste   return bp;
36219f2f44ceSEd Maste }
36229f2f44ceSEd Maste 
3623435933ddSDimitry Andric BreakpointSP
CreateReductionBreakpoint(const ConstString & name,int kernel_types)3624435933ddSDimitry Andric RenderScriptRuntime::CreateReductionBreakpoint(const ConstString &name,
3625435933ddSDimitry Andric                                                int kernel_types) {
3626435933ddSDimitry Andric   Log *log(
3627435933ddSDimitry Andric       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3628435933ddSDimitry Andric 
3629435933ddSDimitry Andric   if (!m_filtersp) {
3630435933ddSDimitry Andric     if (log)
3631435933ddSDimitry Andric       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3632435933ddSDimitry Andric     return nullptr;
3633435933ddSDimitry Andric   }
3634435933ddSDimitry Andric 
3635435933ddSDimitry Andric   BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3636435933ddSDimitry Andric       nullptr, name, &m_rsmodules, kernel_types));
3637acac075bSDimitry Andric   Target &target = GetProcess()->GetTarget();
3638acac075bSDimitry Andric   BreakpointSP bp = target.CreateBreakpoint(
3639435933ddSDimitry Andric       m_filtersp, resolver_sp, false, false, false);
3640435933ddSDimitry Andric 
3641435933ddSDimitry Andric   // Give RS breakpoints a specific name, so the user can manipulate them as a
3642435933ddSDimitry Andric   // group.
36435517e702SDimitry Andric   Status err;
3644acac075bSDimitry Andric   target.AddNameToBreakpoint(bp, "RenderScriptReduction", err);
3645acac075bSDimitry Andric   if (err.Fail() && log)
3646435933ddSDimitry Andric       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3647435933ddSDimitry Andric                   err.AsCString());
3648435933ddSDimitry Andric 
3649435933ddSDimitry Andric   return bp;
3650435933ddSDimitry Andric }
3651435933ddSDimitry Andric 
3652435933ddSDimitry Andric // Given an expression for a variable this function tries to calculate the
3653435933ddSDimitry Andric // variable's value. If this is possible it returns true and sets the uint64_t
3654435933ddSDimitry Andric // parameter to the variables unsigned value. Otherwise function returns false.
GetFrameVarAsUnsigned(const StackFrameSP frame_sp,const char * var_name,uint64_t & val)3655435933ddSDimitry Andric bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3656435933ddSDimitry Andric                                                 const char *var_name,
3657435933ddSDimitry Andric                                                 uint64_t &val) {
36589f2f44ceSEd Maste   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
36595517e702SDimitry Andric   Status err;
36609f2f44ceSEd Maste   VariableSP var_sp;
36619f2f44ceSEd Maste 
36629f2f44ceSEd Maste   // Find variable in stack frame
36634bb0738eSEd Maste   ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
36644bb0738eSEd Maste       var_name, eNoDynamicValues,
3665435933ddSDimitry Andric       StackFrame::eExpressionPathOptionCheckPtrVsMember |
3666435933ddSDimitry Andric           StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3667435933ddSDimitry Andric       var_sp, err));
3668435933ddSDimitry Andric   if (!err.Success()) {
36699f2f44ceSEd Maste     if (log)
3670435933ddSDimitry Andric       log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__,
3671435933ddSDimitry Andric                   var_name);
36729f2f44ceSEd Maste     return false;
36739f2f44ceSEd Maste   }
36749f2f44ceSEd Maste 
36754bb0738eSEd Maste   // Find the uint32_t value for the variable
36769f2f44ceSEd Maste   bool success = false;
36779f2f44ceSEd Maste   val = value_sp->GetValueAsUnsigned(0, &success);
3678435933ddSDimitry Andric   if (!success) {
36799f2f44ceSEd Maste     if (log)
3680435933ddSDimitry Andric       log->Printf("%s - error, couldn't parse '%s' as an uint32_t.",
3681435933ddSDimitry Andric                   __FUNCTION__, var_name);
36829f2f44ceSEd Maste     return false;
36839f2f44ceSEd Maste   }
36849f2f44ceSEd Maste 
36859f2f44ceSEd Maste   return true;
36869f2f44ceSEd Maste }
36879f2f44ceSEd Maste 
3688435933ddSDimitry Andric // Function attempts to find the current coordinate of a kernel invocation by
3689435933ddSDimitry Andric // investigating the values of frame variables in the .expand function. These
3690435933ddSDimitry Andric // coordinates are returned via the coord array reference parameter. Returns
3691435933ddSDimitry Andric // true if the coordinates could be found, and false otherwise.
GetKernelCoordinate(RSCoordinate & coord,Thread * thread_ptr)3692435933ddSDimitry Andric bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3693435933ddSDimitry Andric                                               Thread *thread_ptr) {
3694435933ddSDimitry Andric   static const char *const x_expr = "rsIndex";
3695435933ddSDimitry Andric   static const char *const y_expr = "p->current.y";
3696435933ddSDimitry Andric   static const char *const z_expr = "p->current.z";
36974bb0738eSEd Maste 
36984bb0738eSEd Maste   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
36994bb0738eSEd Maste 
3700435933ddSDimitry Andric   if (!thread_ptr) {
37014bb0738eSEd Maste     if (log)
37024bb0738eSEd Maste       log->Printf("%s - Error, No thread pointer", __FUNCTION__);
37034bb0738eSEd Maste 
37044bb0738eSEd Maste     return false;
37054bb0738eSEd Maste   }
37064bb0738eSEd Maste 
3707435933ddSDimitry Andric   // Walk the call stack looking for a function whose name has the suffix
3708435933ddSDimitry Andric   // '.expand' and contains the variables we're looking for.
3709435933ddSDimitry Andric   for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
37104bb0738eSEd Maste     if (!thread_ptr->SetSelectedFrameByIndex(i))
37114bb0738eSEd Maste       continue;
37124bb0738eSEd Maste 
37134bb0738eSEd Maste     StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
37144bb0738eSEd Maste     if (!frame_sp)
37154bb0738eSEd Maste       continue;
37164bb0738eSEd Maste 
37174bb0738eSEd Maste     // Find the function name
3718*b5893f02SDimitry Andric     const SymbolContext sym_ctx =
3719*b5893f02SDimitry Andric         frame_sp->GetSymbolContext(eSymbolContextFunction);
3720435933ddSDimitry Andric     const ConstString func_name = sym_ctx.GetFunctionName();
3721435933ddSDimitry Andric     if (!func_name)
37224bb0738eSEd Maste       continue;
37234bb0738eSEd Maste 
37244bb0738eSEd Maste     if (log)
3725435933ddSDimitry Andric       log->Printf("%s - Inspecting function '%s'", __FUNCTION__,
3726435933ddSDimitry Andric                   func_name.GetCString());
37274bb0738eSEd Maste 
37284bb0738eSEd Maste     // Check if function name has .expand suffix
3729435933ddSDimitry Andric     if (!func_name.GetStringRef().endswith(".expand"))
37304bb0738eSEd Maste       continue;
37314bb0738eSEd Maste 
37324bb0738eSEd Maste     if (log)
3733435933ddSDimitry Andric       log->Printf("%s - Found .expand function '%s'", __FUNCTION__,
3734435933ddSDimitry Andric                   func_name.GetCString());
37354bb0738eSEd Maste 
37364ba319b5SDimitry Andric     // Get values for variables in .expand frame that tell us the current
37374ba319b5SDimitry Andric     // kernel invocation
3738435933ddSDimitry Andric     uint64_t x, y, z;
3739435933ddSDimitry Andric     bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
3740435933ddSDimitry Andric                  GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
3741435933ddSDimitry Andric                  GetFrameVarAsUnsigned(frame_sp, z_expr, z);
37424bb0738eSEd Maste 
3743435933ddSDimitry Andric     if (found) {
3744435933ddSDimitry Andric       // The RenderScript runtime uses uint32_t for these vars. If they're not
3745435933ddSDimitry Andric       // within bounds, our frame parsing is garbage
3746435933ddSDimitry Andric       assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
3747435933ddSDimitry Andric       coord.x = (uint32_t)x;
3748435933ddSDimitry Andric       coord.y = (uint32_t)y;
3749435933ddSDimitry Andric       coord.z = (uint32_t)z;
37504bb0738eSEd Maste       return true;
37514bb0738eSEd Maste     }
3752435933ddSDimitry Andric   }
37534bb0738eSEd Maste   return false;
37544bb0738eSEd Maste }
37554bb0738eSEd Maste 
3756435933ddSDimitry Andric // Callback when a kernel breakpoint hits and we're looking for a specific
3757435933ddSDimitry Andric // coordinate. Baton parameter contains a pointer to the target coordinate we
37584ba319b5SDimitry Andric // want to break on. Function then checks the .expand frame for the current
37594ba319b5SDimitry Andric // coordinate and breaks to user if it matches. Parameter 'break_id' is the id
37604ba319b5SDimitry Andric // of the Breakpoint which made the callback. Parameter 'break_loc_id' is the
37614ba319b5SDimitry Andric // id for the BreakpointLocation which was hit, a single logical breakpoint can
37624ba319b5SDimitry Andric // have multiple addresses.
KernelBreakpointHit(void * baton,StoppointCallbackContext * ctx,user_id_t break_id,user_id_t break_loc_id)3763435933ddSDimitry Andric bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3764435933ddSDimitry Andric                                               StoppointCallbackContext *ctx,
3765435933ddSDimitry Andric                                               user_id_t break_id,
3766435933ddSDimitry Andric                                               user_id_t break_loc_id) {
3767435933ddSDimitry Andric   Log *log(
3768435933ddSDimitry Andric       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
37699f2f44ceSEd Maste 
3770435933ddSDimitry Andric   assert(baton &&
3771435933ddSDimitry Andric          "Error: null baton in conditional kernel breakpoint callback");
37729f2f44ceSEd Maste 
37739f2f44ceSEd Maste   // Coordinate we want to stop on
3774435933ddSDimitry Andric   RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
37759f2f44ceSEd Maste 
37769f2f44ceSEd Maste   if (log)
3777435933ddSDimitry Andric     log->Printf("%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__, break_id,
3778435933ddSDimitry Andric                 target_coord.x, target_coord.y, target_coord.z);
37799f2f44ceSEd Maste 
37804bb0738eSEd Maste   // Select current thread
37819f2f44ceSEd Maste   ExecutionContext context(ctx->exe_ctx_ref);
37824bb0738eSEd Maste   Thread *thread_ptr = context.GetThreadPtr();
37834bb0738eSEd Maste   assert(thread_ptr && "Null thread pointer");
37844bb0738eSEd Maste 
37854bb0738eSEd Maste   // Find current kernel invocation from .expand frame variables
3786435933ddSDimitry Andric   RSCoordinate current_coord{};
3787435933ddSDimitry Andric   if (!GetKernelCoordinate(current_coord, thread_ptr)) {
37889f2f44ceSEd Maste     if (log)
3789435933ddSDimitry Andric       log->Printf("%s - Error, couldn't select .expand stack frame",
3790435933ddSDimitry Andric                   __FUNCTION__);
37919f2f44ceSEd Maste     return false;
37929f2f44ceSEd Maste   }
37939f2f44ceSEd Maste 
37949f2f44ceSEd Maste   if (log)
3795435933ddSDimitry Andric     log->Printf("%s - " FMT_COORD, __FUNCTION__, current_coord.x,
3796435933ddSDimitry Andric                 current_coord.y, current_coord.z);
37979f2f44ceSEd Maste 
3798435933ddSDimitry Andric   // Check if the current kernel invocation coordinate matches our target
3799435933ddSDimitry Andric   // coordinate
3800435933ddSDimitry Andric   if (target_coord == current_coord) {
38019f2f44ceSEd Maste     if (log)
3802435933ddSDimitry Andric       log->Printf("%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
3803435933ddSDimitry Andric                   current_coord.y, current_coord.z);
38049f2f44ceSEd Maste 
3805435933ddSDimitry Andric     BreakpointSP breakpoint_sp =
3806435933ddSDimitry Andric         context.GetTargetPtr()->GetBreakpointByID(break_id);
3807435933ddSDimitry Andric     assert(breakpoint_sp != nullptr &&
3808435933ddSDimitry Andric            "Error: Couldn't find breakpoint matching break id for callback");
3809435933ddSDimitry Andric     breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3810435933ddSDimitry Andric                                       // should only be hit once.
38119f2f44ceSEd Maste     return true;
38129f2f44ceSEd Maste   }
38139f2f44ceSEd Maste 
38149f2f44ceSEd Maste   // No match on coordinate
38159f2f44ceSEd Maste   return false;
38169f2f44ceSEd Maste }
38179f2f44ceSEd Maste 
SetConditional(BreakpointSP bp,Stream & messages,const RSCoordinate & coord)3818435933ddSDimitry Andric void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
3819435933ddSDimitry Andric                                          const RSCoordinate &coord) {
3820435933ddSDimitry Andric   messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
3821435933ddSDimitry Andric                   coord.x, coord.y, coord.z);
3822435933ddSDimitry Andric   messages.EOL();
3823435933ddSDimitry Andric 
3824435933ddSDimitry Andric   // Allocate memory for the baton, and copy over coordinate
3825435933ddSDimitry Andric   RSCoordinate *baton = new RSCoordinate(coord);
3826435933ddSDimitry Andric 
3827435933ddSDimitry Andric   // Create a callback that will be invoked every time the breakpoint is hit.
3828435933ddSDimitry Andric   // The baton object passed to the handler is the target coordinate we want to
3829435933ddSDimitry Andric   // break on.
3830435933ddSDimitry Andric   bp->SetCallback(KernelBreakpointHit, baton, true);
3831435933ddSDimitry Andric 
3832435933ddSDimitry Andric   // Store a shared pointer to the baton, so the memory will eventually be
3833435933ddSDimitry Andric   // cleaned up after destruction
3834435933ddSDimitry Andric   m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
38351c3bbb01SEd Maste }
38361c3bbb01SEd Maste 
38374ba319b5SDimitry Andric // Tries to set a breakpoint on the start of a kernel, resolved using the
38384ba319b5SDimitry Andric // kernel name. Argument 'coords', represents a three dimensional coordinate
38394ba319b5SDimitry Andric // which can be used to specify a single kernel instance to break on. If this
38404ba319b5SDimitry Andric // is set then we add a callback to the breakpoint.
PlaceBreakpointOnKernel(TargetSP target,Stream & messages,const char * name,const RSCoordinate * coord)3841435933ddSDimitry Andric bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
3842435933ddSDimitry Andric                                                   Stream &messages,
3843435933ddSDimitry Andric                                                   const char *name,
3844435933ddSDimitry Andric                                                   const RSCoordinate *coord) {
3845435933ddSDimitry Andric   if (!name)
3846435933ddSDimitry Andric     return false;
3847435933ddSDimitry Andric 
38489f2f44ceSEd Maste   InitSearchFilter(target);
38499f2f44ceSEd Maste 
38501c3bbb01SEd Maste   ConstString kernel_name(name);
38519f2f44ceSEd Maste   BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
3852435933ddSDimitry Andric   if (!bp)
3853435933ddSDimitry Andric     return false;
38541c3bbb01SEd Maste 
38559f2f44ceSEd Maste   // We have a conditional breakpoint on a specific coordinate
3856435933ddSDimitry Andric   if (coord)
3857435933ddSDimitry Andric     SetConditional(bp, messages, *coord);
38581c3bbb01SEd Maste 
3859435933ddSDimitry Andric   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
38609f2f44ceSEd Maste 
3861435933ddSDimitry Andric   return true;
38621c3bbb01SEd Maste }
38631c3bbb01SEd Maste 
3864435933ddSDimitry Andric BreakpointSP
CreateScriptGroupBreakpoint(const ConstString & name,bool stop_on_all)3865435933ddSDimitry Andric RenderScriptRuntime::CreateScriptGroupBreakpoint(const ConstString &name,
3866435933ddSDimitry Andric                                                  bool stop_on_all) {
3867435933ddSDimitry Andric   Log *log(
3868435933ddSDimitry Andric       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3869435933ddSDimitry Andric 
3870435933ddSDimitry Andric   if (!m_filtersp) {
3871435933ddSDimitry Andric     if (log)
3872435933ddSDimitry Andric       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3873435933ddSDimitry Andric     return nullptr;
3874435933ddSDimitry Andric   }
3875435933ddSDimitry Andric 
3876435933ddSDimitry Andric   BreakpointResolverSP resolver_sp(new RSScriptGroupBreakpointResolver(
3877435933ddSDimitry Andric       nullptr, name, m_scriptGroups, stop_on_all));
3878acac075bSDimitry Andric   Target &target = GetProcess()->GetTarget();
3879acac075bSDimitry Andric   BreakpointSP bp = target.CreateBreakpoint(
3880435933ddSDimitry Andric       m_filtersp, resolver_sp, false, false, false);
3881435933ddSDimitry Andric   // Give RS breakpoints a specific name, so the user can manipulate them as a
3882435933ddSDimitry Andric   // group.
38835517e702SDimitry Andric   Status err;
3884acac075bSDimitry Andric   target.AddNameToBreakpoint(bp, name.GetCString(), err);
3885acac075bSDimitry Andric   if (err.Fail() && log)
3886435933ddSDimitry Andric     log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3887435933ddSDimitry Andric                 err.AsCString());
3888435933ddSDimitry Andric   // ask the breakpoint to resolve itself
3889435933ddSDimitry Andric   bp->ResolveBreakpoint();
3890435933ddSDimitry Andric   return bp;
3891435933ddSDimitry Andric }
3892435933ddSDimitry Andric 
PlaceBreakpointOnScriptGroup(TargetSP target,Stream & strm,const ConstString & name,bool multi)3893435933ddSDimitry Andric bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target,
3894435933ddSDimitry Andric                                                        Stream &strm,
3895435933ddSDimitry Andric                                                        const ConstString &name,
3896435933ddSDimitry Andric                                                        bool multi) {
3897435933ddSDimitry Andric   InitSearchFilter(target);
3898435933ddSDimitry Andric   BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi);
38999f2f44ceSEd Maste   if (bp)
39009f2f44ceSEd Maste     bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
3901435933ddSDimitry Andric   return bool(bp);
39021c3bbb01SEd Maste }
39031c3bbb01SEd Maste 
PlaceBreakpointOnReduction(TargetSP target,Stream & messages,const char * reduce_name,const RSCoordinate * coord,int kernel_types)3904435933ddSDimitry Andric bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3905435933ddSDimitry Andric                                                      Stream &messages,
3906435933ddSDimitry Andric                                                      const char *reduce_name,
3907435933ddSDimitry Andric                                                      const RSCoordinate *coord,
3908435933ddSDimitry Andric                                                      int kernel_types) {
3909435933ddSDimitry Andric   if (!reduce_name)
3910435933ddSDimitry Andric     return false;
3911435933ddSDimitry Andric 
3912435933ddSDimitry Andric   InitSearchFilter(target);
3913435933ddSDimitry Andric   BreakpointSP bp =
3914435933ddSDimitry Andric       CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3915435933ddSDimitry Andric   if (!bp)
3916435933ddSDimitry Andric     return false;
3917435933ddSDimitry Andric 
3918435933ddSDimitry Andric   if (coord)
3919435933ddSDimitry Andric     SetConditional(bp, messages, *coord);
3920435933ddSDimitry Andric 
3921435933ddSDimitry Andric   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3922435933ddSDimitry Andric 
3923435933ddSDimitry Andric   return true;
3924435933ddSDimitry Andric }
3925435933ddSDimitry Andric 
DumpModules(Stream & strm) const3926435933ddSDimitry Andric void RenderScriptRuntime::DumpModules(Stream &strm) const {
39271c3bbb01SEd Maste   strm.Printf("RenderScript Modules:");
39281c3bbb01SEd Maste   strm.EOL();
39291c3bbb01SEd Maste   strm.IndentMore();
3930435933ddSDimitry Andric   for (const auto &module : m_rsmodules) {
39311c3bbb01SEd Maste     module->Dump(strm);
39321c3bbb01SEd Maste   }
39331c3bbb01SEd Maste   strm.IndentLess();
39341c3bbb01SEd Maste }
39351c3bbb01SEd Maste 
39369f2f44ceSEd Maste RenderScriptRuntime::ScriptDetails *
LookUpScript(addr_t address,bool create)3937435933ddSDimitry Andric RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3938435933ddSDimitry Andric   for (const auto &s : m_scripts) {
39399f2f44ceSEd Maste     if (s->script.isValid())
39409f2f44ceSEd Maste       if (*s->script == address)
39419f2f44ceSEd Maste         return s.get();
39429f2f44ceSEd Maste   }
3943435933ddSDimitry Andric   if (create) {
39449f2f44ceSEd Maste     std::unique_ptr<ScriptDetails> s(new ScriptDetails);
39459f2f44ceSEd Maste     s->script = address;
39469f2f44ceSEd Maste     m_scripts.push_back(std::move(s));
39479f2f44ceSEd Maste     return m_scripts.back().get();
39489f2f44ceSEd Maste   }
39499f2f44ceSEd Maste   return nullptr;
39509f2f44ceSEd Maste }
39519f2f44ceSEd Maste 
39529f2f44ceSEd Maste RenderScriptRuntime::AllocationDetails *
LookUpAllocation(addr_t address)3953435933ddSDimitry Andric RenderScriptRuntime::LookUpAllocation(addr_t address) {
3954435933ddSDimitry Andric   for (const auto &a : m_allocations) {
39559f2f44ceSEd Maste     if (a->address.isValid())
39569f2f44ceSEd Maste       if (*a->address == address)
39579f2f44ceSEd Maste         return a.get();
39589f2f44ceSEd Maste   }
3959435933ddSDimitry Andric   return nullptr;
3960435933ddSDimitry Andric }
3961435933ddSDimitry Andric 
3962435933ddSDimitry Andric RenderScriptRuntime::AllocationDetails *
CreateAllocation(addr_t address)3963435933ddSDimitry Andric RenderScriptRuntime::CreateAllocation(addr_t address) {
3964435933ddSDimitry Andric   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
3965435933ddSDimitry Andric 
3966435933ddSDimitry Andric   // Remove any previous allocation which contains the same address
3967435933ddSDimitry Andric   auto it = m_allocations.begin();
3968435933ddSDimitry Andric   while (it != m_allocations.end()) {
3969435933ddSDimitry Andric     if (*((*it)->address) == address) {
3970435933ddSDimitry Andric       if (log)
3971435933ddSDimitry Andric         log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64,
3972435933ddSDimitry Andric                     __FUNCTION__, (*it)->id, address);
3973435933ddSDimitry Andric 
3974435933ddSDimitry Andric       it = m_allocations.erase(it);
3975435933ddSDimitry Andric     } else {
3976435933ddSDimitry Andric       it++;
3977435933ddSDimitry Andric     }
3978435933ddSDimitry Andric   }
3979435933ddSDimitry Andric 
39809f2f44ceSEd Maste   std::unique_ptr<AllocationDetails> a(new AllocationDetails);
39819f2f44ceSEd Maste   a->address = address;
39829f2f44ceSEd Maste   m_allocations.push_back(std::move(a));
39839f2f44ceSEd Maste   return m_allocations.back().get();
39849f2f44ceSEd Maste }
3985435933ddSDimitry Andric 
ResolveKernelName(lldb::addr_t kernel_addr,ConstString & name)3986435933ddSDimitry Andric bool RenderScriptRuntime::ResolveKernelName(lldb::addr_t kernel_addr,
3987435933ddSDimitry Andric                                             ConstString &name) {
3988435933ddSDimitry Andric   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
3989435933ddSDimitry Andric 
3990435933ddSDimitry Andric   Target &target = GetProcess()->GetTarget();
3991435933ddSDimitry Andric   Address resolved;
3992435933ddSDimitry Andric   // RenderScript module
3993435933ddSDimitry Andric   if (!target.GetSectionLoadList().ResolveLoadAddress(kernel_addr, resolved)) {
3994435933ddSDimitry Andric     if (log)
3995435933ddSDimitry Andric       log->Printf("%s: unable to resolve 0x%" PRIx64 " to a loaded symbol",
3996435933ddSDimitry Andric                   __FUNCTION__, kernel_addr);
3997435933ddSDimitry Andric     return false;
39989f2f44ceSEd Maste   }
39999f2f44ceSEd Maste 
4000435933ddSDimitry Andric   Symbol *sym = resolved.CalculateSymbolContextSymbol();
4001435933ddSDimitry Andric   if (!sym)
4002435933ddSDimitry Andric     return false;
4003435933ddSDimitry Andric 
4004435933ddSDimitry Andric   name = sym->GetName();
4005435933ddSDimitry Andric   assert(IsRenderScriptModule(resolved.CalculateSymbolContextModule()));
4006435933ddSDimitry Andric   if (log)
4007435933ddSDimitry Andric     log->Printf("%s: 0x%" PRIx64 " resolved to the symbol '%s'", __FUNCTION__,
4008435933ddSDimitry Andric                 kernel_addr, name.GetCString());
4009435933ddSDimitry Andric   return true;
4010435933ddSDimitry Andric }
4011435933ddSDimitry Andric 
Dump(Stream & strm) const4012435933ddSDimitry Andric void RSModuleDescriptor::Dump(Stream &strm) const {
4013435933ddSDimitry Andric   int indent = strm.GetIndentLevel();
4014435933ddSDimitry Andric 
40151c3bbb01SEd Maste   strm.Indent();
40161c3bbb01SEd Maste   m_module->GetFileSpec().Dump(&strm);
4017435933ddSDimitry Andric   strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
4018435933ddSDimitry Andric                                              : "Debug info does not exist.");
40191c3bbb01SEd Maste   strm.EOL();
40201c3bbb01SEd Maste   strm.IndentMore();
4021435933ddSDimitry Andric 
40221c3bbb01SEd Maste   strm.Indent();
40231c3bbb01SEd Maste   strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
40241c3bbb01SEd Maste   strm.EOL();
40251c3bbb01SEd Maste   strm.IndentMore();
4026435933ddSDimitry Andric   for (const auto &global : m_globals) {
40271c3bbb01SEd Maste     global.Dump(strm);
40281c3bbb01SEd Maste   }
40291c3bbb01SEd Maste   strm.IndentLess();
4030435933ddSDimitry Andric 
40311c3bbb01SEd Maste   strm.Indent();
40321c3bbb01SEd Maste   strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
40331c3bbb01SEd Maste   strm.EOL();
40341c3bbb01SEd Maste   strm.IndentMore();
4035435933ddSDimitry Andric   for (const auto &kernel : m_kernels) {
40361c3bbb01SEd Maste     kernel.Dump(strm);
40371c3bbb01SEd Maste   }
4038435933ddSDimitry Andric   strm.IndentLess();
4039435933ddSDimitry Andric 
4040435933ddSDimitry Andric   strm.Indent();
40411c3bbb01SEd Maste   strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
40421c3bbb01SEd Maste   strm.EOL();
40431c3bbb01SEd Maste   strm.IndentMore();
4044435933ddSDimitry Andric   for (const auto &key_val : m_pragmas) {
4045435933ddSDimitry Andric     strm.Indent();
40461c3bbb01SEd Maste     strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
40471c3bbb01SEd Maste     strm.EOL();
40481c3bbb01SEd Maste   }
4049435933ddSDimitry Andric   strm.IndentLess();
4050435933ddSDimitry Andric 
4051435933ddSDimitry Andric   strm.Indent();
4052435933ddSDimitry Andric   strm.Printf("Reductions: %" PRIu64,
4053435933ddSDimitry Andric               static_cast<uint64_t>(m_reductions.size()));
4054435933ddSDimitry Andric   strm.EOL();
4055435933ddSDimitry Andric   strm.IndentMore();
4056435933ddSDimitry Andric   for (const auto &reduction : m_reductions) {
4057435933ddSDimitry Andric     reduction.Dump(strm);
40581c3bbb01SEd Maste   }
40591c3bbb01SEd Maste 
4060435933ddSDimitry Andric   strm.SetIndentLevel(indent);
4061435933ddSDimitry Andric }
4062435933ddSDimitry Andric 
Dump(Stream & strm) const4063435933ddSDimitry Andric void RSGlobalDescriptor::Dump(Stream &strm) const {
40641c3bbb01SEd Maste   strm.Indent(m_name.AsCString());
40651c3bbb01SEd Maste   VariableList var_list;
40664ba319b5SDimitry Andric   m_module->m_module->FindGlobalVariables(m_name, nullptr, 1U, var_list);
4067435933ddSDimitry Andric   if (var_list.GetSize() == 1) {
40681c3bbb01SEd Maste     auto var = var_list.GetVariableAtIndex(0);
40691c3bbb01SEd Maste     auto type = var->GetType();
4070435933ddSDimitry Andric     if (type) {
40711c3bbb01SEd Maste       strm.Printf(" - ");
40721c3bbb01SEd Maste       type->DumpTypeName(&strm);
4073435933ddSDimitry Andric     } else {
40741c3bbb01SEd Maste       strm.Printf(" - Unknown Type");
40751c3bbb01SEd Maste     }
4076435933ddSDimitry Andric   } else {
40771c3bbb01SEd Maste     strm.Printf(" - variable identified, but not found in binary");
4078435933ddSDimitry Andric     const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
4079435933ddSDimitry Andric         m_name, eSymbolTypeData);
4080435933ddSDimitry Andric     if (s) {
40811c3bbb01SEd Maste       strm.Printf(" (symbol exists) ");
40821c3bbb01SEd Maste     }
40831c3bbb01SEd Maste   }
40841c3bbb01SEd Maste 
40851c3bbb01SEd Maste   strm.EOL();
40861c3bbb01SEd Maste }
40871c3bbb01SEd Maste 
Dump(Stream & strm) const4088435933ddSDimitry Andric void RSKernelDescriptor::Dump(Stream &strm) const {
40891c3bbb01SEd Maste   strm.Indent(m_name.AsCString());
40901c3bbb01SEd Maste   strm.EOL();
40911c3bbb01SEd Maste }
40921c3bbb01SEd Maste 
Dump(lldb_private::Stream & stream) const4093435933ddSDimitry Andric void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
4094435933ddSDimitry Andric   stream.Indent(m_reduce_name.AsCString());
4095435933ddSDimitry Andric   stream.IndentMore();
4096435933ddSDimitry Andric   stream.EOL();
4097435933ddSDimitry Andric   stream.Indent();
4098435933ddSDimitry Andric   stream.Printf("accumulator: %s", m_accum_name.AsCString());
4099435933ddSDimitry Andric   stream.EOL();
4100435933ddSDimitry Andric   stream.Indent();
4101435933ddSDimitry Andric   stream.Printf("initializer: %s", m_init_name.AsCString());
4102435933ddSDimitry Andric   stream.EOL();
4103435933ddSDimitry Andric   stream.Indent();
4104435933ddSDimitry Andric   stream.Printf("combiner: %s", m_comb_name.AsCString());
4105435933ddSDimitry Andric   stream.EOL();
4106435933ddSDimitry Andric   stream.Indent();
4107435933ddSDimitry Andric   stream.Printf("outconverter: %s", m_outc_name.AsCString());
4108435933ddSDimitry Andric   stream.EOL();
4109435933ddSDimitry Andric   // XXX This is currently unspecified by RenderScript, and unused
4110435933ddSDimitry Andric   // stream.Indent();
4111435933ddSDimitry Andric   // stream.Printf("halter: '%s'", m_init_name.AsCString());
4112435933ddSDimitry Andric   // stream.EOL();
4113435933ddSDimitry Andric   stream.IndentLess();
4114435933ddSDimitry Andric }
4115435933ddSDimitry Andric 
4116435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
41171c3bbb01SEd Maste public:
CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter & interpreter)41181c3bbb01SEd Maste   CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
4119435933ddSDimitry Andric       : CommandObjectParsed(
4120435933ddSDimitry Andric             interpreter, "renderscript module dump",
4121435933ddSDimitry Andric             "Dumps renderscript specific information for all modules.",
4122435933ddSDimitry Andric             "renderscript module dump",
4123435933ddSDimitry Andric             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
41241c3bbb01SEd Maste 
41259f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
41261c3bbb01SEd Maste 
DoExecute(Args & command,CommandReturnObject & result)4127435933ddSDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
41281c3bbb01SEd Maste     RenderScriptRuntime *runtime =
4129435933ddSDimitry Andric         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4130435933ddSDimitry Andric             eLanguageTypeExtRenderScript);
41311c3bbb01SEd Maste     runtime->DumpModules(result.GetOutputStream());
41321c3bbb01SEd Maste     result.SetStatus(eReturnStatusSuccessFinishResult);
41331c3bbb01SEd Maste     return true;
41341c3bbb01SEd Maste   }
41351c3bbb01SEd Maste };
41361c3bbb01SEd Maste 
4137435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
41381c3bbb01SEd Maste public:
CommandObjectRenderScriptRuntimeModule(CommandInterpreter & interpreter)41391c3bbb01SEd Maste   CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
4140435933ddSDimitry Andric       : CommandObjectMultiword(interpreter, "renderscript module",
4141435933ddSDimitry Andric                                "Commands that deal with RenderScript modules.",
4142435933ddSDimitry Andric                                nullptr) {
4143435933ddSDimitry Andric     LoadSubCommand(
4144435933ddSDimitry Andric         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
4145435933ddSDimitry Andric                     interpreter)));
41461c3bbb01SEd Maste   }
41471c3bbb01SEd Maste 
41489f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntimeModule() override = default;
41491c3bbb01SEd Maste };
41501c3bbb01SEd Maste 
4151435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
41521c3bbb01SEd Maste public:
CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter & interpreter)41531c3bbb01SEd Maste   CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
4154435933ddSDimitry Andric       : CommandObjectParsed(
4155435933ddSDimitry Andric             interpreter, "renderscript kernel list",
41564bb0738eSEd Maste             "Lists renderscript kernel names and associated script resources.",
4157435933ddSDimitry Andric             "renderscript kernel list",
4158435933ddSDimitry Andric             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
41591c3bbb01SEd Maste 
41609f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntimeKernelList() override = default;
41611c3bbb01SEd Maste 
DoExecute(Args & command,CommandReturnObject & result)4162435933ddSDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
41631c3bbb01SEd Maste     RenderScriptRuntime *runtime =
4164435933ddSDimitry Andric         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4165435933ddSDimitry Andric             eLanguageTypeExtRenderScript);
41661c3bbb01SEd Maste     runtime->DumpKernels(result.GetOutputStream());
41671c3bbb01SEd Maste     result.SetStatus(eReturnStatusSuccessFinishResult);
41681c3bbb01SEd Maste     return true;
41691c3bbb01SEd Maste   }
41701c3bbb01SEd Maste };
41711c3bbb01SEd Maste 
4172*b5893f02SDimitry Andric static constexpr OptionDefinition g_renderscript_reduction_bp_set_options[] = {
4173435933ddSDimitry Andric     {LLDB_OPT_SET_1, false, "function-role", 't',
4174*b5893f02SDimitry Andric      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOneLiner,
4175435933ddSDimitry Andric      "Break on a comma separated set of reduction kernel types "
4176435933ddSDimitry Andric      "(accumulator,outcoverter,combiner,initializer"},
4177435933ddSDimitry Andric     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4178*b5893f02SDimitry Andric      nullptr, {}, 0, eArgTypeValue,
4179435933ddSDimitry Andric      "Set a breakpoint on a single invocation of the kernel with specified "
4180435933ddSDimitry Andric      "coordinate.\n"
4181435933ddSDimitry Andric      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4182435933ddSDimitry Andric      "integers representing kernel dimensions. "
4183435933ddSDimitry Andric      "Any unset dimensions will be defaulted to zero."}};
4184435933ddSDimitry Andric 
4185435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeReductionBreakpointSet
4186435933ddSDimitry Andric     : public CommandObjectParsed {
41871c3bbb01SEd Maste public:
CommandObjectRenderScriptRuntimeReductionBreakpointSet(CommandInterpreter & interpreter)4188435933ddSDimitry Andric   CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4189435933ddSDimitry Andric       CommandInterpreter &interpreter)
4190435933ddSDimitry Andric       : CommandObjectParsed(
4191435933ddSDimitry Andric             interpreter, "renderscript reduction breakpoint set",
4192435933ddSDimitry Andric             "Set a breakpoint on named RenderScript general reductions",
4193435933ddSDimitry Andric             "renderscript reduction breakpoint set  <kernel_name> [-t "
4194435933ddSDimitry Andric             "<reduction_kernel_type,...>]",
4195435933ddSDimitry Andric             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4196435933ddSDimitry Andric                 eCommandProcessMustBePaused),
4197435933ddSDimitry Andric         m_options(){};
41981c3bbb01SEd Maste 
4199435933ddSDimitry Andric   class CommandOptions : public Options {
42009f2f44ceSEd Maste   public:
CommandOptions()4201435933ddSDimitry Andric     CommandOptions()
4202435933ddSDimitry Andric         : Options(),
4203435933ddSDimitry Andric           m_kernel_types(RSReduceBreakpointResolver::eKernelTypeAll) {}
42049f2f44ceSEd Maste 
42059f2f44ceSEd Maste     ~CommandOptions() override = default;
42069f2f44ceSEd Maste 
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * exe_ctx)42075517e702SDimitry Andric     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4208435933ddSDimitry Andric                           ExecutionContext *exe_ctx) override {
42095517e702SDimitry Andric       Status err;
4210435933ddSDimitry Andric       StreamString err_str;
42119f2f44ceSEd Maste       const int short_option = m_getopt_table[option_idx].val;
4212435933ddSDimitry Andric       switch (short_option) {
4213435933ddSDimitry Andric       case 't':
4214435933ddSDimitry Andric         if (!ParseReductionTypes(option_arg, err_str))
4215435933ddSDimitry Andric           err.SetErrorStringWithFormat(
4216435933ddSDimitry Andric               "Unable to deduce reduction types for %s: %s",
4217435933ddSDimitry Andric               option_arg.str().c_str(), err_str.GetData());
42189f2f44ceSEd Maste         break;
4219435933ddSDimitry Andric       case 'c': {
4220435933ddSDimitry Andric         auto coord = RSCoordinate{};
4221435933ddSDimitry Andric         if (!ParseCoordinate(option_arg, coord))
4222435933ddSDimitry Andric           err.SetErrorStringWithFormat("unable to parse coordinate for %s",
4223435933ddSDimitry Andric                                        option_arg.str().c_str());
4224435933ddSDimitry Andric         else {
4225435933ddSDimitry Andric           m_have_coord = true;
4226435933ddSDimitry Andric           m_coord = coord;
4227435933ddSDimitry Andric         }
4228435933ddSDimitry Andric         break;
4229435933ddSDimitry Andric       }
42309f2f44ceSEd Maste       default:
4231435933ddSDimitry Andric         err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
42329f2f44ceSEd Maste       }
4233435933ddSDimitry Andric       return err;
42349f2f44ceSEd Maste     }
42359f2f44ceSEd Maste 
OptionParsingStarting(ExecutionContext * exe_ctx)4236435933ddSDimitry Andric     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4237435933ddSDimitry Andric       m_have_coord = false;
42389f2f44ceSEd Maste     }
42399f2f44ceSEd Maste 
GetDefinitions()4240435933ddSDimitry Andric     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4241435933ddSDimitry Andric       return llvm::makeArrayRef(g_renderscript_reduction_bp_set_options);
42429f2f44ceSEd Maste     }
42439f2f44ceSEd Maste 
ParseReductionTypes(llvm::StringRef option_val,StreamString & err_str)4244435933ddSDimitry Andric     bool ParseReductionTypes(llvm::StringRef option_val,
4245435933ddSDimitry Andric                              StreamString &err_str) {
4246435933ddSDimitry Andric       m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
4247435933ddSDimitry Andric       const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
4248435933ddSDimitry Andric         return llvm::StringSwitch<int>(name)
4249435933ddSDimitry Andric             .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
4250435933ddSDimitry Andric             .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
4251435933ddSDimitry Andric             .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
4252435933ddSDimitry Andric             .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
4253435933ddSDimitry Andric             .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
4254435933ddSDimitry Andric             // Currently not exposed by the runtime
4255435933ddSDimitry Andric             // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
4256435933ddSDimitry Andric             .Default(0);
42579f2f44ceSEd Maste       };
42581c3bbb01SEd Maste 
4259435933ddSDimitry Andric       // Matching a comma separated list of known words is fairly
42604ba319b5SDimitry Andric       // straightforward with PCRE, but we're using ERE, so we end up with a
42614ba319b5SDimitry Andric       // little ugliness...
4262435933ddSDimitry Andric       RegularExpression::Match match(/* max_matches */ 5);
4263435933ddSDimitry Andric       RegularExpression match_type_list(
4264435933ddSDimitry Andric           llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
4265435933ddSDimitry Andric 
4266435933ddSDimitry Andric       assert(match_type_list.IsValid());
4267435933ddSDimitry Andric 
4268435933ddSDimitry Andric       if (!match_type_list.Execute(option_val, &match)) {
4269435933ddSDimitry Andric         err_str.PutCString(
4270435933ddSDimitry Andric             "a comma-separated list of kernel types is required");
4271435933ddSDimitry Andric         return false;
4272435933ddSDimitry Andric       }
4273435933ddSDimitry Andric 
4274435933ddSDimitry Andric       // splitting on commas is much easier with llvm::StringRef than regex
4275435933ddSDimitry Andric       llvm::SmallVector<llvm::StringRef, 5> type_names;
4276435933ddSDimitry Andric       llvm::StringRef(option_val).split(type_names, ',');
4277435933ddSDimitry Andric 
4278435933ddSDimitry Andric       for (const auto &name : type_names) {
4279435933ddSDimitry Andric         const int type = reduce_name_to_type(name);
4280435933ddSDimitry Andric         if (!type) {
4281435933ddSDimitry Andric           err_str.Printf("unknown kernel type name %s", name.str().c_str());
4282435933ddSDimitry Andric           return false;
4283435933ddSDimitry Andric         }
4284435933ddSDimitry Andric         m_kernel_types |= type;
4285435933ddSDimitry Andric       }
4286435933ddSDimitry Andric 
4287435933ddSDimitry Andric       return true;
4288435933ddSDimitry Andric     }
4289435933ddSDimitry Andric 
4290435933ddSDimitry Andric     int m_kernel_types;
4291435933ddSDimitry Andric     llvm::StringRef m_reduce_name;
4292435933ddSDimitry Andric     RSCoordinate m_coord;
4293435933ddSDimitry Andric     bool m_have_coord;
4294435933ddSDimitry Andric   };
4295435933ddSDimitry Andric 
GetOptions()4296435933ddSDimitry Andric   Options *GetOptions() override { return &m_options; }
4297435933ddSDimitry Andric 
DoExecute(Args & command,CommandReturnObject & result)4298435933ddSDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
42991c3bbb01SEd Maste     const size_t argc = command.GetArgumentCount();
4300435933ddSDimitry Andric     if (argc < 1) {
4301435933ddSDimitry Andric       result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
4302435933ddSDimitry Andric                                    "and an optional kernel type list",
43034bb0738eSEd Maste                                    m_cmd_name.c_str());
43049f2f44ceSEd Maste       result.SetStatus(eReturnStatusFailed);
43059f2f44ceSEd Maste       return false;
43069f2f44ceSEd Maste     }
43079f2f44ceSEd Maste 
4308435933ddSDimitry Andric     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4309435933ddSDimitry Andric         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4310435933ddSDimitry Andric             eLanguageTypeExtRenderScript));
43111c3bbb01SEd Maste 
4312435933ddSDimitry Andric     auto &outstream = result.GetOutputStream();
4313435933ddSDimitry Andric     auto name = command.GetArgumentAtIndex(0);
4314435933ddSDimitry Andric     auto &target = m_exe_ctx.GetTargetSP();
4315435933ddSDimitry Andric     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4316435933ddSDimitry Andric     if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
4317435933ddSDimitry Andric                                              m_options.m_kernel_types)) {
4318435933ddSDimitry Andric       result.SetStatus(eReturnStatusFailed);
4319435933ddSDimitry Andric       result.AppendError("Error: unable to place breakpoint on reduction");
4320435933ddSDimitry Andric       return false;
4321435933ddSDimitry Andric     }
43221c3bbb01SEd Maste     result.AppendMessage("Breakpoint(s) created");
43231c3bbb01SEd Maste     result.SetStatus(eReturnStatusSuccessFinishResult);
43241c3bbb01SEd Maste     return true;
43251c3bbb01SEd Maste   }
43261c3bbb01SEd Maste 
43279f2f44ceSEd Maste private:
43289f2f44ceSEd Maste   CommandOptions m_options;
43299f2f44ceSEd Maste };
43309f2f44ceSEd Maste 
4331*b5893f02SDimitry Andric static constexpr OptionDefinition g_renderscript_kernel_bp_set_options[] = {
4332435933ddSDimitry Andric     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4333*b5893f02SDimitry Andric      nullptr, {}, 0, eArgTypeValue,
4334435933ddSDimitry Andric      "Set a breakpoint on a single invocation of the kernel with specified "
4335435933ddSDimitry Andric      "coordinate.\n"
4336435933ddSDimitry Andric      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4337435933ddSDimitry Andric      "integers representing kernel dimensions. "
4338435933ddSDimitry Andric      "Any unset dimensions will be defaulted to zero."}};
43399f2f44ceSEd Maste 
4340435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeKernelBreakpointSet
4341435933ddSDimitry Andric     : public CommandObjectParsed {
43429f2f44ceSEd Maste public:
CommandObjectRenderScriptRuntimeKernelBreakpointSet(CommandInterpreter & interpreter)4343435933ddSDimitry Andric   CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4344435933ddSDimitry Andric       CommandInterpreter &interpreter)
4345435933ddSDimitry Andric       : CommandObjectParsed(
4346435933ddSDimitry Andric             interpreter, "renderscript kernel breakpoint set",
4347435933ddSDimitry Andric             "Sets a breakpoint on a renderscript kernel.",
4348435933ddSDimitry Andric             "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
4349435933ddSDimitry Andric             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4350435933ddSDimitry Andric                 eCommandProcessMustBePaused),
4351435933ddSDimitry Andric         m_options() {}
4352435933ddSDimitry Andric 
4353435933ddSDimitry Andric   ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
4354435933ddSDimitry Andric 
GetOptions()4355435933ddSDimitry Andric   Options *GetOptions() override { return &m_options; }
4356435933ddSDimitry Andric 
4357435933ddSDimitry Andric   class CommandOptions : public Options {
4358435933ddSDimitry Andric   public:
CommandOptions()4359435933ddSDimitry Andric     CommandOptions() : Options() {}
4360435933ddSDimitry Andric 
4361435933ddSDimitry Andric     ~CommandOptions() override = default;
4362435933ddSDimitry Andric 
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * exe_ctx)43635517e702SDimitry Andric     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4364435933ddSDimitry Andric                           ExecutionContext *exe_ctx) override {
43655517e702SDimitry Andric       Status err;
4366435933ddSDimitry Andric       const int short_option = m_getopt_table[option_idx].val;
4367435933ddSDimitry Andric 
4368435933ddSDimitry Andric       switch (short_option) {
4369435933ddSDimitry Andric       case 'c': {
4370435933ddSDimitry Andric         auto coord = RSCoordinate{};
4371435933ddSDimitry Andric         if (!ParseCoordinate(option_arg, coord))
4372435933ddSDimitry Andric           err.SetErrorStringWithFormat(
4373435933ddSDimitry Andric               "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
4374435933ddSDimitry Andric               option_arg.str().c_str());
4375435933ddSDimitry Andric         else {
4376435933ddSDimitry Andric           m_have_coord = true;
4377435933ddSDimitry Andric           m_coord = coord;
4378435933ddSDimitry Andric         }
4379435933ddSDimitry Andric         break;
4380435933ddSDimitry Andric       }
4381435933ddSDimitry Andric       default:
4382435933ddSDimitry Andric         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4383435933ddSDimitry Andric         break;
4384435933ddSDimitry Andric       }
4385435933ddSDimitry Andric       return err;
4386435933ddSDimitry Andric     }
4387435933ddSDimitry Andric 
OptionParsingStarting(ExecutionContext * exe_ctx)4388435933ddSDimitry Andric     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4389435933ddSDimitry Andric       m_have_coord = false;
4390435933ddSDimitry Andric     }
4391435933ddSDimitry Andric 
GetDefinitions()4392435933ddSDimitry Andric     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4393435933ddSDimitry Andric       return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
4394435933ddSDimitry Andric     }
4395435933ddSDimitry Andric 
4396435933ddSDimitry Andric     RSCoordinate m_coord;
4397435933ddSDimitry Andric     bool m_have_coord;
4398435933ddSDimitry Andric   };
4399435933ddSDimitry Andric 
DoExecute(Args & command,CommandReturnObject & result)4400435933ddSDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
4401435933ddSDimitry Andric     const size_t argc = command.GetArgumentCount();
4402435933ddSDimitry Andric     if (argc < 1) {
4403435933ddSDimitry Andric       result.AppendErrorWithFormat(
4404435933ddSDimitry Andric           "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4405435933ddSDimitry Andric           m_cmd_name.c_str());
4406435933ddSDimitry Andric       result.SetStatus(eReturnStatusFailed);
4407435933ddSDimitry Andric       return false;
4408435933ddSDimitry Andric     }
4409435933ddSDimitry Andric 
4410435933ddSDimitry Andric     RenderScriptRuntime *runtime =
4411435933ddSDimitry Andric         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4412435933ddSDimitry Andric             eLanguageTypeExtRenderScript);
4413435933ddSDimitry Andric 
4414435933ddSDimitry Andric     auto &outstream = result.GetOutputStream();
4415435933ddSDimitry Andric     auto &target = m_exe_ctx.GetTargetSP();
4416435933ddSDimitry Andric     auto name = command.GetArgumentAtIndex(0);
4417435933ddSDimitry Andric     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4418435933ddSDimitry Andric     if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
4419435933ddSDimitry Andric       result.SetStatus(eReturnStatusFailed);
4420435933ddSDimitry Andric       result.AppendErrorWithFormat(
4421435933ddSDimitry Andric           "Error: unable to set breakpoint on kernel '%s'", name);
4422435933ddSDimitry Andric       return false;
4423435933ddSDimitry Andric     }
4424435933ddSDimitry Andric 
4425435933ddSDimitry Andric     result.AppendMessage("Breakpoint(s) created");
4426435933ddSDimitry Andric     result.SetStatus(eReturnStatusSuccessFinishResult);
4427435933ddSDimitry Andric     return true;
4428435933ddSDimitry Andric   }
4429435933ddSDimitry Andric 
4430435933ddSDimitry Andric private:
4431435933ddSDimitry Andric   CommandOptions m_options;
4432435933ddSDimitry Andric };
4433435933ddSDimitry Andric 
4434435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4435435933ddSDimitry Andric     : public CommandObjectParsed {
4436435933ddSDimitry Andric public:
CommandObjectRenderScriptRuntimeKernelBreakpointAll(CommandInterpreter & interpreter)4437435933ddSDimitry Andric   CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4438435933ddSDimitry Andric       CommandInterpreter &interpreter)
44394bb0738eSEd Maste       : CommandObjectParsed(
44404bb0738eSEd Maste             interpreter, "renderscript kernel breakpoint all",
4441435933ddSDimitry Andric             "Automatically sets a breakpoint on all renderscript kernels that "
4442435933ddSDimitry Andric             "are or will be loaded.\n"
4443435933ddSDimitry Andric             "Disabling option means breakpoints will no longer be set on any "
4444435933ddSDimitry Andric             "kernels loaded in the future, "
44459f2f44ceSEd Maste             "but does not remove currently set breakpoints.",
44469f2f44ceSEd Maste             "renderscript kernel breakpoint all <enable/disable>",
4447435933ddSDimitry Andric             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4448435933ddSDimitry Andric                 eCommandProcessMustBePaused) {}
44499f2f44ceSEd Maste 
44509f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
44519f2f44ceSEd Maste 
DoExecute(Args & command,CommandReturnObject & result)4452435933ddSDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
44539f2f44ceSEd Maste     const size_t argc = command.GetArgumentCount();
4454435933ddSDimitry Andric     if (argc != 1) {
4455435933ddSDimitry Andric       result.AppendErrorWithFormat(
4456435933ddSDimitry Andric           "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
44571c3bbb01SEd Maste       result.SetStatus(eReturnStatusFailed);
44581c3bbb01SEd Maste       return false;
44591c3bbb01SEd Maste     }
44609f2f44ceSEd Maste 
44614bb0738eSEd Maste     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4462435933ddSDimitry Andric         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4463435933ddSDimitry Andric             eLanguageTypeExtRenderScript));
44649f2f44ceSEd Maste 
44659f2f44ceSEd Maste     bool do_break = false;
44669f2f44ceSEd Maste     const char *argument = command.GetArgumentAtIndex(0);
4467435933ddSDimitry Andric     if (strcmp(argument, "enable") == 0) {
44689f2f44ceSEd Maste       do_break = true;
44699f2f44ceSEd Maste       result.AppendMessage("Breakpoints will be set on all kernels.");
4470435933ddSDimitry Andric     } else if (strcmp(argument, "disable") == 0) {
44719f2f44ceSEd Maste       do_break = false;
44729f2f44ceSEd Maste       result.AppendMessage("Breakpoints will not be set on any new kernels.");
4473435933ddSDimitry Andric     } else {
4474435933ddSDimitry Andric       result.AppendErrorWithFormat(
4475435933ddSDimitry Andric           "Argument must be either 'enable' or 'disable'");
44769f2f44ceSEd Maste       result.SetStatus(eReturnStatusFailed);
44779f2f44ceSEd Maste       return false;
44789f2f44ceSEd Maste     }
44799f2f44ceSEd Maste 
44809f2f44ceSEd Maste     runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
44819f2f44ceSEd Maste 
44829f2f44ceSEd Maste     result.SetStatus(eReturnStatusSuccessFinishResult);
44839f2f44ceSEd Maste     return true;
44849f2f44ceSEd Maste   }
44859f2f44ceSEd Maste };
44869f2f44ceSEd Maste 
4487435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeReductionBreakpoint
4488435933ddSDimitry Andric     : public CommandObjectMultiword {
44894bb0738eSEd Maste public:
CommandObjectRenderScriptRuntimeReductionBreakpoint(CommandInterpreter & interpreter)4490435933ddSDimitry Andric   CommandObjectRenderScriptRuntimeReductionBreakpoint(
4491435933ddSDimitry Andric       CommandInterpreter &interpreter)
4492435933ddSDimitry Andric       : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4493435933ddSDimitry Andric                                "Commands that manipulate breakpoints on "
4494435933ddSDimitry Andric                                "renderscript general reductions.",
4495435933ddSDimitry Andric                                nullptr) {
4496435933ddSDimitry Andric     LoadSubCommand(
4497435933ddSDimitry Andric         "set", CommandObjectSP(
4498435933ddSDimitry Andric                    new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4499435933ddSDimitry Andric                        interpreter)));
4500435933ddSDimitry Andric   }
4501435933ddSDimitry Andric 
4502435933ddSDimitry Andric   ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4503435933ddSDimitry Andric };
4504435933ddSDimitry Andric 
4505435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeKernelCoordinate
4506435933ddSDimitry Andric     : public CommandObjectParsed {
4507435933ddSDimitry Andric public:
CommandObjectRenderScriptRuntimeKernelCoordinate(CommandInterpreter & interpreter)4508435933ddSDimitry Andric   CommandObjectRenderScriptRuntimeKernelCoordinate(
4509435933ddSDimitry Andric       CommandInterpreter &interpreter)
4510435933ddSDimitry Andric       : CommandObjectParsed(
4511435933ddSDimitry Andric             interpreter, "renderscript kernel coordinate",
45124bb0738eSEd Maste             "Shows the (x,y,z) coordinate of the current kernel invocation.",
45134bb0738eSEd Maste             "renderscript kernel coordinate",
4514435933ddSDimitry Andric             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4515435933ddSDimitry Andric                 eCommandProcessMustBePaused) {}
45164bb0738eSEd Maste 
45174bb0738eSEd Maste   ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
45184bb0738eSEd Maste 
DoExecute(Args & command,CommandReturnObject & result)4519435933ddSDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
4520435933ddSDimitry Andric     RSCoordinate coord{};
4521435933ddSDimitry Andric     bool success = RenderScriptRuntime::GetKernelCoordinate(
4522435933ddSDimitry Andric         coord, m_exe_ctx.GetThreadPtr());
45234bb0738eSEd Maste     Stream &stream = result.GetOutputStream();
45244bb0738eSEd Maste 
4525435933ddSDimitry Andric     if (success) {
4526435933ddSDimitry Andric       stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
45274bb0738eSEd Maste       stream.EOL();
45284bb0738eSEd Maste       result.SetStatus(eReturnStatusSuccessFinishResult);
4529435933ddSDimitry Andric     } else {
45304bb0738eSEd Maste       stream.Printf("Error: Coordinate could not be found.");
45314bb0738eSEd Maste       stream.EOL();
45324bb0738eSEd Maste       result.SetStatus(eReturnStatusFailed);
45334bb0738eSEd Maste     }
45344bb0738eSEd Maste     return true;
45354bb0738eSEd Maste   }
45364bb0738eSEd Maste };
45374bb0738eSEd Maste 
4538435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeKernelBreakpoint
4539435933ddSDimitry Andric     : public CommandObjectMultiword {
45409f2f44ceSEd Maste public:
CommandObjectRenderScriptRuntimeKernelBreakpoint(CommandInterpreter & interpreter)4541435933ddSDimitry Andric   CommandObjectRenderScriptRuntimeKernelBreakpoint(
4542435933ddSDimitry Andric       CommandInterpreter &interpreter)
4543435933ddSDimitry Andric       : CommandObjectMultiword(
4544435933ddSDimitry Andric             interpreter, "renderscript kernel",
4545435933ddSDimitry Andric             "Commands that generate breakpoints on renderscript kernels.",
4546435933ddSDimitry Andric             nullptr) {
4547435933ddSDimitry Andric     LoadSubCommand(
4548435933ddSDimitry Andric         "set",
4549435933ddSDimitry Andric         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4550435933ddSDimitry Andric             interpreter)));
4551435933ddSDimitry Andric     LoadSubCommand(
4552435933ddSDimitry Andric         "all",
4553435933ddSDimitry Andric         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4554435933ddSDimitry Andric             interpreter)));
45559f2f44ceSEd Maste   }
45569f2f44ceSEd Maste 
45579f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
45581c3bbb01SEd Maste };
45591c3bbb01SEd Maste 
4560435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
45611c3bbb01SEd Maste public:
CommandObjectRenderScriptRuntimeKernel(CommandInterpreter & interpreter)45621c3bbb01SEd Maste   CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4563435933ddSDimitry Andric       : CommandObjectMultiword(interpreter, "renderscript kernel",
4564435933ddSDimitry Andric                                "Commands that deal with RenderScript kernels.",
4565435933ddSDimitry Andric                                nullptr) {
4566435933ddSDimitry Andric     LoadSubCommand(
4567435933ddSDimitry Andric         "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4568435933ddSDimitry Andric                     interpreter)));
4569435933ddSDimitry Andric     LoadSubCommand(
4570435933ddSDimitry Andric         "coordinate",
4571435933ddSDimitry Andric         CommandObjectSP(
4572435933ddSDimitry Andric             new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4573435933ddSDimitry Andric     LoadSubCommand(
4574435933ddSDimitry Andric         "breakpoint",
4575435933ddSDimitry Andric         CommandObjectSP(
4576435933ddSDimitry Andric             new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
45771c3bbb01SEd Maste   }
45781c3bbb01SEd Maste 
45799f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntimeKernel() override = default;
45801c3bbb01SEd Maste };
45811c3bbb01SEd Maste 
4582435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
45831c3bbb01SEd Maste public:
CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter & interpreter)45841c3bbb01SEd Maste   CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4585435933ddSDimitry Andric       : CommandObjectParsed(interpreter, "renderscript context dump",
4586435933ddSDimitry Andric                             "Dumps renderscript context information.",
4587435933ddSDimitry Andric                             "renderscript context dump",
4588435933ddSDimitry Andric                             eCommandRequiresProcess |
4589435933ddSDimitry Andric                                 eCommandProcessMustBeLaunched) {}
45901c3bbb01SEd Maste 
45919f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntimeContextDump() override = default;
45921c3bbb01SEd Maste 
DoExecute(Args & command,CommandReturnObject & result)4593435933ddSDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
45941c3bbb01SEd Maste     RenderScriptRuntime *runtime =
4595435933ddSDimitry Andric         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4596435933ddSDimitry Andric             eLanguageTypeExtRenderScript);
45971c3bbb01SEd Maste     runtime->DumpContexts(result.GetOutputStream());
45981c3bbb01SEd Maste     result.SetStatus(eReturnStatusSuccessFinishResult);
45991c3bbb01SEd Maste     return true;
46001c3bbb01SEd Maste   }
46011c3bbb01SEd Maste };
46021c3bbb01SEd Maste 
4603*b5893f02SDimitry Andric static constexpr OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
4604435933ddSDimitry Andric     {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
4605*b5893f02SDimitry Andric      nullptr, {}, 0, eArgTypeFilename,
4606435933ddSDimitry Andric      "Print results to specified file instead of command line."}};
4607435933ddSDimitry Andric 
4608435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
46091c3bbb01SEd Maste public:
CommandObjectRenderScriptRuntimeContext(CommandInterpreter & interpreter)46101c3bbb01SEd Maste   CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4611435933ddSDimitry Andric       : CommandObjectMultiword(interpreter, "renderscript context",
4612435933ddSDimitry Andric                                "Commands that deal with RenderScript contexts.",
4613435933ddSDimitry Andric                                nullptr) {
4614435933ddSDimitry Andric     LoadSubCommand(
4615435933ddSDimitry Andric         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4616435933ddSDimitry Andric                     interpreter)));
46171c3bbb01SEd Maste   }
46181c3bbb01SEd Maste 
46199f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntimeContext() override = default;
46209f2f44ceSEd Maste };
46219f2f44ceSEd Maste 
4622435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeAllocationDump
4623435933ddSDimitry Andric     : public CommandObjectParsed {
46249f2f44ceSEd Maste public:
CommandObjectRenderScriptRuntimeAllocationDump(CommandInterpreter & interpreter)4625435933ddSDimitry Andric   CommandObjectRenderScriptRuntimeAllocationDump(
4626435933ddSDimitry Andric       CommandInterpreter &interpreter)
46279f2f44ceSEd Maste       : CommandObjectParsed(interpreter, "renderscript allocation dump",
4628435933ddSDimitry Andric                             "Displays the contents of a particular allocation",
4629435933ddSDimitry Andric                             "renderscript allocation dump <ID>",
4630435933ddSDimitry Andric                             eCommandRequiresProcess |
4631435933ddSDimitry Andric                                 eCommandProcessMustBeLaunched),
4632435933ddSDimitry Andric         m_options() {}
46339f2f44ceSEd Maste 
46349f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
46359f2f44ceSEd Maste 
GetOptions()4636435933ddSDimitry Andric   Options *GetOptions() override { return &m_options; }
46379f2f44ceSEd Maste 
4638435933ddSDimitry Andric   class CommandOptions : public Options {
46399f2f44ceSEd Maste   public:
CommandOptions()4640435933ddSDimitry Andric     CommandOptions() : Options() {}
46419f2f44ceSEd Maste 
46429f2f44ceSEd Maste     ~CommandOptions() override = default;
46439f2f44ceSEd Maste 
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * exe_ctx)46445517e702SDimitry Andric     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4645435933ddSDimitry Andric                           ExecutionContext *exe_ctx) override {
46465517e702SDimitry Andric       Status err;
46479f2f44ceSEd Maste       const int short_option = m_getopt_table[option_idx].val;
46489f2f44ceSEd Maste 
4649435933ddSDimitry Andric       switch (short_option) {
46509f2f44ceSEd Maste       case 'f':
4651*b5893f02SDimitry Andric         m_outfile.SetFile(option_arg, FileSpec::Style::native);
4652*b5893f02SDimitry Andric         FileSystem::Instance().Resolve(m_outfile);
4653*b5893f02SDimitry Andric         if (FileSystem::Instance().Exists(m_outfile)) {
46549f2f44ceSEd Maste           m_outfile.Clear();
4655435933ddSDimitry Andric           err.SetErrorStringWithFormat("file already exists: '%s'",
4656435933ddSDimitry Andric                                        option_arg.str().c_str());
46579f2f44ceSEd Maste         }
46589f2f44ceSEd Maste         break;
46599f2f44ceSEd Maste       default:
4660435933ddSDimitry Andric         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
46619f2f44ceSEd Maste         break;
46629f2f44ceSEd Maste       }
4663435933ddSDimitry Andric       return err;
46649f2f44ceSEd Maste     }
46659f2f44ceSEd Maste 
OptionParsingStarting(ExecutionContext * exe_ctx)4666435933ddSDimitry Andric     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
46679f2f44ceSEd Maste       m_outfile.Clear();
46689f2f44ceSEd Maste     }
46699f2f44ceSEd Maste 
GetDefinitions()4670435933ddSDimitry Andric     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4671435933ddSDimitry Andric       return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
46729f2f44ceSEd Maste     }
46739f2f44ceSEd Maste 
46749f2f44ceSEd Maste     FileSpec m_outfile;
46759f2f44ceSEd Maste   };
46769f2f44ceSEd Maste 
DoExecute(Args & command,CommandReturnObject & result)4677435933ddSDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
46789f2f44ceSEd Maste     const size_t argc = command.GetArgumentCount();
4679435933ddSDimitry Andric     if (argc < 1) {
4680435933ddSDimitry Andric       result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4681435933ddSDimitry Andric                                    "As well as an optional -f argument",
46829f2f44ceSEd Maste                                    m_cmd_name.c_str());
46839f2f44ceSEd Maste       result.SetStatus(eReturnStatusFailed);
46849f2f44ceSEd Maste       return false;
46859f2f44ceSEd Maste     }
46869f2f44ceSEd Maste 
46874bb0738eSEd Maste     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4688435933ddSDimitry Andric         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4689435933ddSDimitry Andric             eLanguageTypeExtRenderScript));
46909f2f44ceSEd Maste 
46919f2f44ceSEd Maste     const char *id_cstr = command.GetArgumentAtIndex(0);
4692435933ddSDimitry Andric     bool success = false;
4693435933ddSDimitry Andric     const uint32_t id =
4694435933ddSDimitry Andric         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4695435933ddSDimitry Andric     if (!success) {
4696435933ddSDimitry Andric       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4697435933ddSDimitry Andric                                    id_cstr);
46989f2f44ceSEd Maste       result.SetStatus(eReturnStatusFailed);
46999f2f44ceSEd Maste       return false;
47009f2f44ceSEd Maste     }
47019f2f44ceSEd Maste 
47029f2f44ceSEd Maste     Stream *output_strm = nullptr;
47039f2f44ceSEd Maste     StreamFile outfile_stream;
4704435933ddSDimitry Andric     const FileSpec &outfile_spec =
4705435933ddSDimitry Andric         m_options.m_outfile; // Dump allocation to file instead
4706435933ddSDimitry Andric     if (outfile_spec) {
47079f2f44ceSEd Maste       // Open output file
4708*b5893f02SDimitry Andric       std::string path = outfile_spec.GetPath();
4709*b5893f02SDimitry Andric       auto error = FileSystem::Instance().Open(
4710*b5893f02SDimitry Andric           outfile_stream.GetFile(), outfile_spec,
4711*b5893f02SDimitry Andric           File::eOpenOptionWrite | File::eOpenOptionCanCreate);
4712*b5893f02SDimitry Andric       if (error.Success()) {
47139f2f44ceSEd Maste         output_strm = &outfile_stream;
4714*b5893f02SDimitry Andric         result.GetOutputStream().Printf("Results written to '%s'",
4715*b5893f02SDimitry Andric                                         path.c_str());
47169f2f44ceSEd Maste         result.GetOutputStream().EOL();
4717435933ddSDimitry Andric       } else {
4718*b5893f02SDimitry Andric         result.AppendErrorWithFormat("Couldn't open file '%s'", path.c_str());
47199f2f44ceSEd Maste         result.SetStatus(eReturnStatusFailed);
47209f2f44ceSEd Maste         return false;
47219f2f44ceSEd Maste       }
4722435933ddSDimitry Andric     } else
47239f2f44ceSEd Maste       output_strm = &result.GetOutputStream();
47249f2f44ceSEd Maste 
47259f2f44ceSEd Maste     assert(output_strm != nullptr);
4726435933ddSDimitry Andric     bool dumped =
4727435933ddSDimitry Andric         runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
47289f2f44ceSEd Maste 
4729435933ddSDimitry Andric     if (dumped)
47309f2f44ceSEd Maste       result.SetStatus(eReturnStatusSuccessFinishResult);
47319f2f44ceSEd Maste     else
47329f2f44ceSEd Maste       result.SetStatus(eReturnStatusFailed);
47339f2f44ceSEd Maste 
47349f2f44ceSEd Maste     return true;
47359f2f44ceSEd Maste   }
47369f2f44ceSEd Maste 
47379f2f44ceSEd Maste private:
47389f2f44ceSEd Maste   CommandOptions m_options;
47399f2f44ceSEd Maste };
47409f2f44ceSEd Maste 
4741*b5893f02SDimitry Andric static constexpr OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
4742435933ddSDimitry Andric     {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
4743*b5893f02SDimitry Andric      {}, 0, eArgTypeIndex,
4744435933ddSDimitry Andric      "Only show details of a single allocation with specified id."}};
47459f2f44ceSEd Maste 
4746435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeAllocationList
4747435933ddSDimitry Andric     : public CommandObjectParsed {
47489f2f44ceSEd Maste public:
CommandObjectRenderScriptRuntimeAllocationList(CommandInterpreter & interpreter)4749435933ddSDimitry Andric   CommandObjectRenderScriptRuntimeAllocationList(
4750435933ddSDimitry Andric       CommandInterpreter &interpreter)
4751435933ddSDimitry Andric       : CommandObjectParsed(
4752435933ddSDimitry Andric             interpreter, "renderscript allocation list",
4753435933ddSDimitry Andric             "List renderscript allocations and their information.",
4754435933ddSDimitry Andric             "renderscript allocation list",
47554bb0738eSEd Maste             eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4756435933ddSDimitry Andric         m_options() {}
47579f2f44ceSEd Maste 
47589f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
47599f2f44ceSEd Maste 
GetOptions()4760435933ddSDimitry Andric   Options *GetOptions() override { return &m_options; }
47619f2f44ceSEd Maste 
4762435933ddSDimitry Andric   class CommandOptions : public Options {
47639f2f44ceSEd Maste   public:
CommandOptions()4764435933ddSDimitry Andric     CommandOptions() : Options(), m_id(0) {}
47659f2f44ceSEd Maste 
47669f2f44ceSEd Maste     ~CommandOptions() override = default;
47679f2f44ceSEd Maste 
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * exe_ctx)47685517e702SDimitry Andric     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4769435933ddSDimitry Andric                           ExecutionContext *exe_ctx) override {
47705517e702SDimitry Andric       Status err;
47719f2f44ceSEd Maste       const int short_option = m_getopt_table[option_idx].val;
47729f2f44ceSEd Maste 
4773435933ddSDimitry Andric       switch (short_option) {
47744bb0738eSEd Maste       case 'i':
4775435933ddSDimitry Andric         if (option_arg.getAsInteger(0, m_id))
4776435933ddSDimitry Andric           err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4777435933ddSDimitry Andric                                        short_option);
47789f2f44ceSEd Maste         break;
47799f2f44ceSEd Maste       default:
4780435933ddSDimitry Andric         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
47819f2f44ceSEd Maste         break;
47829f2f44ceSEd Maste       }
4783435933ddSDimitry Andric       return err;
47849f2f44ceSEd Maste     }
47859f2f44ceSEd Maste 
OptionParsingStarting(ExecutionContext * exe_ctx)4786435933ddSDimitry Andric     void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
4787435933ddSDimitry Andric 
GetDefinitions()4788435933ddSDimitry Andric     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4789435933ddSDimitry Andric       return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
47909f2f44ceSEd Maste     }
47919f2f44ceSEd Maste 
47924bb0738eSEd Maste     uint32_t m_id;
47939f2f44ceSEd Maste   };
47949f2f44ceSEd Maste 
DoExecute(Args & command,CommandReturnObject & result)4795435933ddSDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
47964bb0738eSEd Maste     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4797435933ddSDimitry Andric         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4798435933ddSDimitry Andric             eLanguageTypeExtRenderScript));
4799435933ddSDimitry Andric     runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4800435933ddSDimitry Andric                              m_options.m_id);
48019f2f44ceSEd Maste     result.SetStatus(eReturnStatusSuccessFinishResult);
48029f2f44ceSEd Maste     return true;
48039f2f44ceSEd Maste   }
48049f2f44ceSEd Maste 
48059f2f44ceSEd Maste private:
48069f2f44ceSEd Maste   CommandOptions m_options;
48079f2f44ceSEd Maste };
48089f2f44ceSEd Maste 
4809435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeAllocationLoad
4810435933ddSDimitry Andric     : public CommandObjectParsed {
48119f2f44ceSEd Maste public:
CommandObjectRenderScriptRuntimeAllocationLoad(CommandInterpreter & interpreter)4812435933ddSDimitry Andric   CommandObjectRenderScriptRuntimeAllocationLoad(
4813435933ddSDimitry Andric       CommandInterpreter &interpreter)
48144bb0738eSEd Maste       : CommandObjectParsed(
4815435933ddSDimitry Andric             interpreter, "renderscript allocation load",
4816435933ddSDimitry Andric             "Loads renderscript allocation contents from a file.",
4817435933ddSDimitry Andric             "renderscript allocation load <ID> <filename>",
4818435933ddSDimitry Andric             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
48199f2f44ceSEd Maste 
48209f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
48219f2f44ceSEd Maste 
DoExecute(Args & command,CommandReturnObject & result)4822435933ddSDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
48239f2f44ceSEd Maste     const size_t argc = command.GetArgumentCount();
4824435933ddSDimitry Andric     if (argc != 2) {
4825435933ddSDimitry Andric       result.AppendErrorWithFormat(
4826435933ddSDimitry Andric           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
48274bb0738eSEd Maste           m_cmd_name.c_str());
48289f2f44ceSEd Maste       result.SetStatus(eReturnStatusFailed);
48299f2f44ceSEd Maste       return false;
48309f2f44ceSEd Maste     }
48319f2f44ceSEd Maste 
48324bb0738eSEd Maste     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4833435933ddSDimitry Andric         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4834435933ddSDimitry Andric             eLanguageTypeExtRenderScript));
48359f2f44ceSEd Maste 
48369f2f44ceSEd Maste     const char *id_cstr = command.GetArgumentAtIndex(0);
4837435933ddSDimitry Andric     bool success = false;
4838435933ddSDimitry Andric     const uint32_t id =
4839435933ddSDimitry Andric         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4840435933ddSDimitry Andric     if (!success) {
4841435933ddSDimitry Andric       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4842435933ddSDimitry Andric                                    id_cstr);
48439f2f44ceSEd Maste       result.SetStatus(eReturnStatusFailed);
48449f2f44ceSEd Maste       return false;
48459f2f44ceSEd Maste     }
48469f2f44ceSEd Maste 
4847435933ddSDimitry Andric     const char *path = command.GetArgumentAtIndex(1);
4848435933ddSDimitry Andric     bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
4849435933ddSDimitry Andric                                           m_exe_ctx.GetFramePtr());
48509f2f44ceSEd Maste 
4851435933ddSDimitry Andric     if (loaded)
48529f2f44ceSEd Maste       result.SetStatus(eReturnStatusSuccessFinishResult);
48539f2f44ceSEd Maste     else
48549f2f44ceSEd Maste       result.SetStatus(eReturnStatusFailed);
48559f2f44ceSEd Maste 
48569f2f44ceSEd Maste     return true;
48579f2f44ceSEd Maste   }
48589f2f44ceSEd Maste };
48599f2f44ceSEd Maste 
4860435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeAllocationSave
4861435933ddSDimitry Andric     : public CommandObjectParsed {
48629f2f44ceSEd Maste public:
CommandObjectRenderScriptRuntimeAllocationSave(CommandInterpreter & interpreter)4863435933ddSDimitry Andric   CommandObjectRenderScriptRuntimeAllocationSave(
4864435933ddSDimitry Andric       CommandInterpreter &interpreter)
4865435933ddSDimitry Andric       : CommandObjectParsed(interpreter, "renderscript allocation save",
4866435933ddSDimitry Andric                             "Write renderscript allocation contents to a file.",
4867435933ddSDimitry Andric                             "renderscript allocation save <ID> <filename>",
4868435933ddSDimitry Andric                             eCommandRequiresProcess |
4869435933ddSDimitry Andric                                 eCommandProcessMustBeLaunched) {}
48709f2f44ceSEd Maste 
48719f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
48729f2f44ceSEd Maste 
DoExecute(Args & command,CommandReturnObject & result)4873435933ddSDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
48749f2f44ceSEd Maste     const size_t argc = command.GetArgumentCount();
4875435933ddSDimitry Andric     if (argc != 2) {
4876435933ddSDimitry Andric       result.AppendErrorWithFormat(
4877435933ddSDimitry Andric           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
48784bb0738eSEd Maste           m_cmd_name.c_str());
48799f2f44ceSEd Maste       result.SetStatus(eReturnStatusFailed);
48809f2f44ceSEd Maste       return false;
48819f2f44ceSEd Maste     }
48829f2f44ceSEd Maste 
48834bb0738eSEd Maste     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4884435933ddSDimitry Andric         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4885435933ddSDimitry Andric             eLanguageTypeExtRenderScript));
48869f2f44ceSEd Maste 
48879f2f44ceSEd Maste     const char *id_cstr = command.GetArgumentAtIndex(0);
4888435933ddSDimitry Andric     bool success = false;
4889435933ddSDimitry Andric     const uint32_t id =
4890435933ddSDimitry Andric         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4891435933ddSDimitry Andric     if (!success) {
4892435933ddSDimitry Andric       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4893435933ddSDimitry Andric                                    id_cstr);
48949f2f44ceSEd Maste       result.SetStatus(eReturnStatusFailed);
48959f2f44ceSEd Maste       return false;
48969f2f44ceSEd Maste     }
48979f2f44ceSEd Maste 
4898435933ddSDimitry Andric     const char *path = command.GetArgumentAtIndex(1);
4899435933ddSDimitry Andric     bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
4900435933ddSDimitry Andric                                          m_exe_ctx.GetFramePtr());
49019f2f44ceSEd Maste 
4902435933ddSDimitry Andric     if (saved)
49039f2f44ceSEd Maste       result.SetStatus(eReturnStatusSuccessFinishResult);
49049f2f44ceSEd Maste     else
49059f2f44ceSEd Maste       result.SetStatus(eReturnStatusFailed);
49069f2f44ceSEd Maste 
49079f2f44ceSEd Maste     return true;
49089f2f44ceSEd Maste   }
49099f2f44ceSEd Maste };
49109f2f44ceSEd Maste 
4911435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeAllocationRefresh
4912435933ddSDimitry Andric     : public CommandObjectParsed {
49134bb0738eSEd Maste public:
CommandObjectRenderScriptRuntimeAllocationRefresh(CommandInterpreter & interpreter)4914435933ddSDimitry Andric   CommandObjectRenderScriptRuntimeAllocationRefresh(
4915435933ddSDimitry Andric       CommandInterpreter &interpreter)
49164bb0738eSEd Maste       : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4917435933ddSDimitry Andric                             "Recomputes the details of all allocations.",
4918435933ddSDimitry Andric                             "renderscript allocation refresh",
4919435933ddSDimitry Andric                             eCommandRequiresProcess |
4920435933ddSDimitry Andric                                 eCommandProcessMustBeLaunched) {}
49214bb0738eSEd Maste 
49224bb0738eSEd Maste   ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
49234bb0738eSEd Maste 
DoExecute(Args & command,CommandReturnObject & result)4924435933ddSDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
49254bb0738eSEd Maste     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4926435933ddSDimitry Andric         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4927435933ddSDimitry Andric             eLanguageTypeExtRenderScript));
49284bb0738eSEd Maste 
4929435933ddSDimitry Andric     bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4930435933ddSDimitry Andric                                                     m_exe_ctx.GetFramePtr());
49314bb0738eSEd Maste 
4932435933ddSDimitry Andric     if (success) {
49334bb0738eSEd Maste       result.SetStatus(eReturnStatusSuccessFinishResult);
49344bb0738eSEd Maste       return true;
4935435933ddSDimitry Andric     } else {
49364bb0738eSEd Maste       result.SetStatus(eReturnStatusFailed);
49374bb0738eSEd Maste       return false;
49384bb0738eSEd Maste     }
49394bb0738eSEd Maste   }
49404bb0738eSEd Maste };
49414bb0738eSEd Maste 
4942435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeAllocation
4943435933ddSDimitry Andric     : public CommandObjectMultiword {
49449f2f44ceSEd Maste public:
CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter & interpreter)49459f2f44ceSEd Maste   CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4946435933ddSDimitry Andric       : CommandObjectMultiword(
4947435933ddSDimitry Andric             interpreter, "renderscript allocation",
4948435933ddSDimitry Andric             "Commands that deal with RenderScript allocations.", nullptr) {
4949435933ddSDimitry Andric     LoadSubCommand(
4950435933ddSDimitry Andric         "list",
4951435933ddSDimitry Andric         CommandObjectSP(
4952435933ddSDimitry Andric             new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4953435933ddSDimitry Andric     LoadSubCommand(
4954435933ddSDimitry Andric         "dump",
4955435933ddSDimitry Andric         CommandObjectSP(
4956435933ddSDimitry Andric             new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4957435933ddSDimitry Andric     LoadSubCommand(
4958435933ddSDimitry Andric         "save",
4959435933ddSDimitry Andric         CommandObjectSP(
4960435933ddSDimitry Andric             new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4961435933ddSDimitry Andric     LoadSubCommand(
4962435933ddSDimitry Andric         "load",
4963435933ddSDimitry Andric         CommandObjectSP(
4964435933ddSDimitry Andric             new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4965435933ddSDimitry Andric     LoadSubCommand(
4966435933ddSDimitry Andric         "refresh",
4967435933ddSDimitry Andric         CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4968435933ddSDimitry Andric             interpreter)));
49699f2f44ceSEd Maste   }
49709f2f44ceSEd Maste 
49719f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntimeAllocation() override = default;
49721c3bbb01SEd Maste };
49731c3bbb01SEd Maste 
4974435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
49751c3bbb01SEd Maste public:
CommandObjectRenderScriptRuntimeStatus(CommandInterpreter & interpreter)49761c3bbb01SEd Maste   CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4977435933ddSDimitry Andric       : CommandObjectParsed(interpreter, "renderscript status",
4978435933ddSDimitry Andric                             "Displays current RenderScript runtime status.",
4979435933ddSDimitry Andric                             "renderscript status",
4980435933ddSDimitry Andric                             eCommandRequiresProcess |
4981435933ddSDimitry Andric                                 eCommandProcessMustBeLaunched) {}
49821c3bbb01SEd Maste 
49839f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntimeStatus() override = default;
49841c3bbb01SEd Maste 
DoExecute(Args & command,CommandReturnObject & result)4985435933ddSDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
49861c3bbb01SEd Maste     RenderScriptRuntime *runtime =
4987435933ddSDimitry Andric         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4988435933ddSDimitry Andric             eLanguageTypeExtRenderScript);
49895517e702SDimitry Andric     runtime->DumpStatus(result.GetOutputStream());
49901c3bbb01SEd Maste     result.SetStatus(eReturnStatusSuccessFinishResult);
49911c3bbb01SEd Maste     return true;
49921c3bbb01SEd Maste   }
49931c3bbb01SEd Maste };
49941c3bbb01SEd Maste 
4995435933ddSDimitry Andric class CommandObjectRenderScriptRuntimeReduction
4996435933ddSDimitry Andric     : public CommandObjectMultiword {
4997435933ddSDimitry Andric public:
CommandObjectRenderScriptRuntimeReduction(CommandInterpreter & interpreter)4998435933ddSDimitry Andric   CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
4999435933ddSDimitry Andric       : CommandObjectMultiword(interpreter, "renderscript reduction",
5000435933ddSDimitry Andric                                "Commands that handle general reduction kernels",
5001435933ddSDimitry Andric                                nullptr) {
5002435933ddSDimitry Andric     LoadSubCommand(
5003435933ddSDimitry Andric         "breakpoint",
5004435933ddSDimitry Andric         CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
5005435933ddSDimitry Andric             interpreter)));
5006435933ddSDimitry Andric   }
5007435933ddSDimitry Andric   ~CommandObjectRenderScriptRuntimeReduction() override = default;
5008435933ddSDimitry Andric };
5009435933ddSDimitry Andric 
5010435933ddSDimitry Andric class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
50111c3bbb01SEd Maste public:
CommandObjectRenderScriptRuntime(CommandInterpreter & interpreter)50121c3bbb01SEd Maste   CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
5013435933ddSDimitry Andric       : CommandObjectMultiword(
5014435933ddSDimitry Andric             interpreter, "renderscript",
5015435933ddSDimitry Andric             "Commands for operating on the RenderScript runtime.",
5016435933ddSDimitry Andric             "renderscript <subcommand> [<subcommand-options>]") {
5017435933ddSDimitry Andric     LoadSubCommand(
5018435933ddSDimitry Andric         "module", CommandObjectSP(
5019435933ddSDimitry Andric                       new CommandObjectRenderScriptRuntimeModule(interpreter)));
5020435933ddSDimitry Andric     LoadSubCommand(
5021435933ddSDimitry Andric         "status", CommandObjectSP(
5022435933ddSDimitry Andric                       new CommandObjectRenderScriptRuntimeStatus(interpreter)));
5023435933ddSDimitry Andric     LoadSubCommand(
5024435933ddSDimitry Andric         "kernel", CommandObjectSP(
5025435933ddSDimitry Andric                       new CommandObjectRenderScriptRuntimeKernel(interpreter)));
5026435933ddSDimitry Andric     LoadSubCommand("context",
5027435933ddSDimitry Andric                    CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
5028435933ddSDimitry Andric                        interpreter)));
5029435933ddSDimitry Andric     LoadSubCommand(
5030435933ddSDimitry Andric         "allocation",
5031435933ddSDimitry Andric         CommandObjectSP(
5032435933ddSDimitry Andric             new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
5033435933ddSDimitry Andric     LoadSubCommand("scriptgroup",
5034435933ddSDimitry Andric                    NewCommandObjectRenderScriptScriptGroup(interpreter));
5035435933ddSDimitry Andric     LoadSubCommand(
5036435933ddSDimitry Andric         "reduction",
5037435933ddSDimitry Andric         CommandObjectSP(
5038435933ddSDimitry Andric             new CommandObjectRenderScriptRuntimeReduction(interpreter)));
50391c3bbb01SEd Maste   }
50401c3bbb01SEd Maste 
50419f2f44ceSEd Maste   ~CommandObjectRenderScriptRuntime() override = default;
50421c3bbb01SEd Maste };
50431c3bbb01SEd Maste 
Initiate()5044435933ddSDimitry Andric void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
50451c3bbb01SEd Maste 
RenderScriptRuntime(Process * process)50461c3bbb01SEd Maste RenderScriptRuntime::RenderScriptRuntime(Process *process)
5047435933ddSDimitry Andric     : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
5048435933ddSDimitry Andric       m_debuggerPresentFlagged(false), m_breakAllKernels(false),
5049435933ddSDimitry Andric       m_ir_passes(nullptr) {
50501c3bbb01SEd Maste   ModulesDidLoad(process->GetTarget().GetImages());
50511c3bbb01SEd Maste }
50521c3bbb01SEd Maste 
GetCommandObject(lldb_private::CommandInterpreter & interpreter)5053435933ddSDimitry Andric lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
5054435933ddSDimitry Andric     lldb_private::CommandInterpreter &interpreter) {
50554bb0738eSEd Maste   return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
50561c3bbb01SEd Maste }
50571c3bbb01SEd Maste 
50589f2f44ceSEd Maste RenderScriptRuntime::~RenderScriptRuntime() = default;
5059