15ec532a9SColin Riley //===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===//
25ec532a9SColin Riley //
35ec532a9SColin Riley //                     The LLVM Compiler Infrastructure
45ec532a9SColin Riley //
55ec532a9SColin Riley // This file is distributed under the University of Illinois Open Source
65ec532a9SColin Riley // License. See LICENSE.TXT for details.
75ec532a9SColin Riley //
85ec532a9SColin Riley //===----------------------------------------------------------------------===//
95ec532a9SColin Riley 
10222b937cSEugene Zelenko // C Includes
11222b937cSEugene Zelenko // C++ Includes
12222b937cSEugene Zelenko // Other libraries and framework includes
13*b3bbcb12SLuke Drummond #include "llvm/ADT/StringSwitch.h"
147f193d69SLuke Drummond 
15222b937cSEugene Zelenko // Project includes
165ec532a9SColin Riley #include "RenderScriptRuntime.h"
175ec532a9SColin Riley 
18b3f7f69dSAidan Dodds #include "lldb/Breakpoint/StoppointCallbackContext.h"
195ec532a9SColin Riley #include "lldb/Core/ConstString.h"
205ec532a9SColin Riley #include "lldb/Core/Debugger.h"
215ec532a9SColin Riley #include "lldb/Core/Error.h"
225ec532a9SColin Riley #include "lldb/Core/Log.h"
235ec532a9SColin Riley #include "lldb/Core/PluginManager.h"
24018f5a7eSEwan Crawford #include "lldb/Core/RegularExpression.h"
25b3f7f69dSAidan Dodds #include "lldb/Core/ValueObjectVariable.h"
268b244e21SEwan Crawford #include "lldb/DataFormatters/DumpValueObjectOptions.h"
27b3f7f69dSAidan Dodds #include "lldb/Expression/UserExpression.h"
28a0f08674SEwan Crawford #include "lldb/Host/StringConvert.h"
29b3f7f69dSAidan Dodds #include "lldb/Interpreter/Args.h"
30b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandInterpreter.h"
31b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandObjectMultiword.h"
32b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandReturnObject.h"
33b3f7f69dSAidan Dodds #include "lldb/Interpreter/Options.h"
345ec532a9SColin Riley #include "lldb/Symbol/Symbol.h"
354640cde1SColin Riley #include "lldb/Symbol/Type.h"
36b3f7f69dSAidan Dodds #include "lldb/Symbol/VariableList.h"
375ec532a9SColin Riley #include "lldb/Target/Process.h"
38b3f7f69dSAidan Dodds #include "lldb/Target/RegisterContext.h"
395ec532a9SColin Riley #include "lldb/Target/Target.h"
40018f5a7eSEwan Crawford #include "lldb/Target/Thread.h"
415ec532a9SColin Riley 
425ec532a9SColin Riley using namespace lldb;
435ec532a9SColin Riley using namespace lldb_private;
4498156583SEwan Crawford using namespace lldb_renderscript;
455ec532a9SColin Riley 
4600f56eebSLuke Drummond #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")"
4700f56eebSLuke Drummond 
48b9c1b51eSKate Stone namespace {
4978f339d1SEwan Crawford 
5078f339d1SEwan Crawford // The empirical_type adds a basic level of validation to arbitrary data
5180af0b9eSLuke Drummond // allowing us to track if data has been discovered and stored or not. An
5280af0b9eSLuke Drummond // empirical_type will be marked as valid only if it has been explicitly
53b9c1b51eSKate Stone // assigned to.
54b9c1b51eSKate Stone template <typename type_t> class empirical_type {
5578f339d1SEwan Crawford public:
5678f339d1SEwan Crawford   // Ctor. Contents is invalid when constructed.
57b3f7f69dSAidan Dodds   empirical_type() : valid(false) {}
5878f339d1SEwan Crawford 
5978f339d1SEwan Crawford   // Return true and copy contents to out if valid, else return false.
60b9c1b51eSKate Stone   bool get(type_t &out) const {
6178f339d1SEwan Crawford     if (valid)
6278f339d1SEwan Crawford       out = data;
6378f339d1SEwan Crawford     return valid;
6478f339d1SEwan Crawford   }
6578f339d1SEwan Crawford 
6678f339d1SEwan Crawford   // Return a pointer to the contents or nullptr if it was not valid.
67b9c1b51eSKate Stone   const type_t *get() const { return valid ? &data : nullptr; }
6878f339d1SEwan Crawford 
6978f339d1SEwan Crawford   // Assign data explicitly.
70b9c1b51eSKate Stone   void set(const type_t in) {
7178f339d1SEwan Crawford     data = in;
7278f339d1SEwan Crawford     valid = true;
7378f339d1SEwan Crawford   }
7478f339d1SEwan Crawford 
7578f339d1SEwan Crawford   // Mark contents as invalid.
76b9c1b51eSKate Stone   void invalidate() { valid = false; }
7778f339d1SEwan Crawford 
7878f339d1SEwan Crawford   // Returns true if this type contains valid data.
79b9c1b51eSKate Stone   bool isValid() const { return valid; }
8078f339d1SEwan Crawford 
8178f339d1SEwan Crawford   // Assignment operator.
82b9c1b51eSKate Stone   empirical_type<type_t> &operator=(const type_t in) {
8378f339d1SEwan Crawford     set(in);
8478f339d1SEwan Crawford     return *this;
8578f339d1SEwan Crawford   }
8678f339d1SEwan Crawford 
8778f339d1SEwan Crawford   // Dereference operator returns contents.
8878f339d1SEwan Crawford   // Warning: Will assert if not valid so use only when you know data is valid.
89b9c1b51eSKate Stone   const type_t &operator*() const {
9078f339d1SEwan Crawford     assert(valid);
9178f339d1SEwan Crawford     return data;
9278f339d1SEwan Crawford   }
9378f339d1SEwan Crawford 
9478f339d1SEwan Crawford protected:
9578f339d1SEwan Crawford   bool valid;
9678f339d1SEwan Crawford   type_t data;
9778f339d1SEwan Crawford };
9878f339d1SEwan Crawford 
99b9c1b51eSKate Stone // ArgItem is used by the GetArgs() function when reading function arguments
100b9c1b51eSKate Stone // from the target.
101b9c1b51eSKate Stone struct ArgItem {
102b9c1b51eSKate Stone   enum { ePointer, eInt32, eInt64, eLong, eBool } type;
103f4786785SAidan Dodds 
104f4786785SAidan Dodds   uint64_t value;
105f4786785SAidan Dodds 
106f4786785SAidan Dodds   explicit operator uint64_t() const { return value; }
107f4786785SAidan Dodds };
108f4786785SAidan Dodds 
109b9c1b51eSKate Stone // Context structure to be passed into GetArgsXXX(), argument reading functions
110b9c1b51eSKate Stone // below.
111b9c1b51eSKate Stone struct GetArgsCtx {
112f4786785SAidan Dodds   RegisterContext *reg_ctx;
113f4786785SAidan Dodds   Process *process;
114f4786785SAidan Dodds };
115f4786785SAidan Dodds 
116b9c1b51eSKate Stone bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
117f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
118f4786785SAidan Dodds 
11980af0b9eSLuke Drummond   Error err;
12067dc3e15SAidan Dodds 
121f4786785SAidan Dodds   // get the current stack pointer
122f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
123f4786785SAidan Dodds 
124b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
125f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
126f4786785SAidan Dodds     // advance up the stack by one argument
127f4786785SAidan Dodds     sp += sizeof(uint32_t);
128f4786785SAidan Dodds     // get the argument type size
129f4786785SAidan Dodds     size_t arg_size = sizeof(uint32_t);
130f4786785SAidan Dodds     // read the argument from memory
131f4786785SAidan Dodds     arg.value = 0;
13280af0b9eSLuke Drummond     Error err;
133b9c1b51eSKate Stone     size_t read =
13480af0b9eSLuke Drummond         ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
13580af0b9eSLuke Drummond     if (read != arg_size || !err.Success()) {
136f4786785SAidan Dodds       if (log)
137b9c1b51eSKate Stone         log->Printf("%s - error reading argument: %" PRIu64 " '%s'",
13880af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString());
139f4786785SAidan Dodds       return false;
140f4786785SAidan Dodds     }
141f4786785SAidan Dodds   }
142f4786785SAidan Dodds   return true;
143f4786785SAidan Dodds }
144f4786785SAidan Dodds 
145b9c1b51eSKate Stone bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
146f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
147f4786785SAidan Dodds 
148f4786785SAidan Dodds   // number of arguments passed in registers
14980af0b9eSLuke Drummond   static const uint32_t args_in_reg = 6;
150f4786785SAidan Dodds   // register passing order
15180af0b9eSLuke Drummond   static const std::array<const char *, args_in_reg> reg_names{
152b9c1b51eSKate Stone       {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
153f4786785SAidan Dodds   // argument type to size mapping
1541ee07253SSaleem Abdulrasool   static const std::array<size_t, 5> arg_size{{
155f4786785SAidan Dodds       8, // ePointer,
156f4786785SAidan Dodds       4, // eInt32,
157f4786785SAidan Dodds       8, // eInt64,
158f4786785SAidan Dodds       8, // eLong,
159f4786785SAidan Dodds       4, // eBool,
1601ee07253SSaleem Abdulrasool   }};
161f4786785SAidan Dodds 
16280af0b9eSLuke Drummond   Error err;
16317e07c0aSAidan Dodds 
164f4786785SAidan Dodds   // get the current stack pointer
165f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
166f4786785SAidan Dodds   // step over the return address
167f4786785SAidan Dodds   sp += sizeof(uint64_t);
168f4786785SAidan Dodds 
169f4786785SAidan Dodds   // check the stack alignment was correct (16 byte aligned)
170b9c1b51eSKate Stone   if ((sp & 0xf) != 0x0) {
171f4786785SAidan Dodds     if (log)
172f4786785SAidan Dodds       log->Printf("%s - stack misaligned", __FUNCTION__);
173f4786785SAidan Dodds     return false;
174f4786785SAidan Dodds   }
175f4786785SAidan Dodds 
176f4786785SAidan Dodds   // find the start of arguments on the stack
177f4786785SAidan Dodds   uint64_t sp_offset = 0;
17880af0b9eSLuke Drummond   for (uint32_t i = args_in_reg; i < num_args; ++i) {
179f4786785SAidan Dodds     sp_offset += arg_size[arg_list[i].type];
180f4786785SAidan Dodds   }
181f4786785SAidan Dodds   // round up to multiple of 16
182f4786785SAidan Dodds   sp_offset = (sp_offset + 0xf) & 0xf;
183f4786785SAidan Dodds   sp += sp_offset;
184f4786785SAidan Dodds 
185b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
186f4786785SAidan Dodds     bool success = false;
187f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
188f4786785SAidan Dodds     // arguments passed in registers
18980af0b9eSLuke Drummond     if (i < args_in_reg) {
19080af0b9eSLuke Drummond       const RegisterInfo *reg =
19180af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoByName(reg_names[i]);
19280af0b9eSLuke Drummond       RegisterValue reg_val;
19380af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
19480af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
195f4786785SAidan Dodds     }
196f4786785SAidan Dodds     // arguments passed on the stack
197b9c1b51eSKate Stone     else {
198f4786785SAidan Dodds       // get the argument type size
199f4786785SAidan Dodds       const size_t size = arg_size[arg_list[i].type];
200f4786785SAidan Dodds       // read the argument from memory
201f4786785SAidan Dodds       arg.value = 0;
202b9c1b51eSKate Stone       // note: due to little endian layout reading 4 or 8 bytes will give the
203b9c1b51eSKate Stone       // correct value.
20480af0b9eSLuke Drummond       size_t read = ctx.process->ReadMemory(sp, &arg.value, size, err);
20580af0b9eSLuke Drummond       success = (err.Success() && read == size);
206f4786785SAidan Dodds       // advance past this argument
207f4786785SAidan Dodds       sp -= size;
208f4786785SAidan Dodds     }
209f4786785SAidan Dodds     // fail if we couldn't read this argument
210b9c1b51eSKate Stone     if (!success) {
211f4786785SAidan Dodds       if (log)
21217e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
21380af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
214f4786785SAidan Dodds       return false;
215f4786785SAidan Dodds     }
216f4786785SAidan Dodds   }
217f4786785SAidan Dodds   return true;
218f4786785SAidan Dodds }
219f4786785SAidan Dodds 
220b9c1b51eSKate Stone bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
221f4786785SAidan Dodds   // number of arguments passed in registers
22280af0b9eSLuke Drummond   static const uint32_t args_in_reg = 4;
223f4786785SAidan Dodds 
224f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
225f4786785SAidan Dodds 
22680af0b9eSLuke Drummond   Error err;
22717e07c0aSAidan Dodds 
228f4786785SAidan Dodds   // get the current stack pointer
229f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
230f4786785SAidan Dodds 
231b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
232f4786785SAidan Dodds     bool success = false;
233f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
234f4786785SAidan Dodds     // arguments passed in registers
23580af0b9eSLuke Drummond     if (i < args_in_reg) {
23680af0b9eSLuke Drummond       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
23780af0b9eSLuke Drummond       RegisterValue reg_val;
23880af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
23980af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt32(0, &success);
240f4786785SAidan Dodds     }
241f4786785SAidan Dodds     // arguments passed on the stack
242b9c1b51eSKate Stone     else {
243f4786785SAidan Dodds       // get the argument type size
244f4786785SAidan Dodds       const size_t arg_size = sizeof(uint32_t);
245f4786785SAidan Dodds       // clear all 64bits
246f4786785SAidan Dodds       arg.value = 0;
247f4786785SAidan Dodds       // read this argument from memory
248b9c1b51eSKate Stone       size_t bytes_read =
24980af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
25080af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
251f4786785SAidan Dodds       // advance the stack pointer
252f4786785SAidan Dodds       sp += sizeof(uint32_t);
253f4786785SAidan Dodds     }
254f4786785SAidan Dodds     // fail if we couldn't read this argument
255b9c1b51eSKate Stone     if (!success) {
256f4786785SAidan Dodds       if (log)
25717e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
25880af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
259f4786785SAidan Dodds       return false;
260f4786785SAidan Dodds     }
261f4786785SAidan Dodds   }
262f4786785SAidan Dodds   return true;
263f4786785SAidan Dodds }
264f4786785SAidan Dodds 
265b9c1b51eSKate Stone bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
266f4786785SAidan Dodds   // number of arguments passed in registers
26780af0b9eSLuke Drummond   static const uint32_t args_in_reg = 8;
268f4786785SAidan Dodds 
269f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
270f4786785SAidan Dodds 
271b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
272f4786785SAidan Dodds     bool success = false;
273f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
274f4786785SAidan Dodds     // arguments passed in registers
27580af0b9eSLuke Drummond     if (i < args_in_reg) {
27680af0b9eSLuke Drummond       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
27780af0b9eSLuke Drummond       RegisterValue reg_val;
27880af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
27980af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
280f4786785SAidan Dodds     }
281f4786785SAidan Dodds     // arguments passed on the stack
282b9c1b51eSKate Stone     else {
283f4786785SAidan Dodds       if (log)
284b9c1b51eSKate Stone         log->Printf("%s - reading arguments spilled to stack not implemented",
285b9c1b51eSKate Stone                     __FUNCTION__);
286f4786785SAidan Dodds     }
287f4786785SAidan Dodds     // fail if we couldn't read this argument
288b9c1b51eSKate Stone     if (!success) {
289f4786785SAidan Dodds       if (log)
290f4786785SAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__,
291f4786785SAidan Dodds                     uint64_t(i));
292f4786785SAidan Dodds       return false;
293f4786785SAidan Dodds     }
294f4786785SAidan Dodds   }
295f4786785SAidan Dodds   return true;
296f4786785SAidan Dodds }
297f4786785SAidan Dodds 
298b9c1b51eSKate Stone bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
299f4786785SAidan Dodds   // number of arguments passed in registers
30080af0b9eSLuke Drummond   static const uint32_t args_in_reg = 4;
301f4786785SAidan Dodds   // register file offset to first argument
30280af0b9eSLuke Drummond   static const uint32_t reg_offset = 4;
303f4786785SAidan Dodds 
304f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
305f4786785SAidan Dodds 
30680af0b9eSLuke Drummond   Error err;
30717e07c0aSAidan Dodds 
30817e07c0aSAidan Dodds   // find offset to arguments on the stack (+16 to skip over a0-a3 shadow space)
30917e07c0aSAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP() + 16;
31017e07c0aSAidan Dodds 
311b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
312f4786785SAidan Dodds     bool success = false;
313f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
314f4786785SAidan Dodds     // arguments passed in registers
31580af0b9eSLuke Drummond     if (i < args_in_reg) {
31680af0b9eSLuke Drummond       const RegisterInfo *reg =
31780af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
31880af0b9eSLuke Drummond       RegisterValue reg_val;
31980af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
32080af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
321f4786785SAidan Dodds     }
322f4786785SAidan Dodds     // arguments passed on the stack
323b9c1b51eSKate Stone     else {
3246dd4b579SAidan Dodds       const size_t arg_size = sizeof(uint32_t);
3256dd4b579SAidan Dodds       arg.value = 0;
326b9c1b51eSKate Stone       size_t bytes_read =
32780af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
32880af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
32967dc3e15SAidan Dodds       // advance the stack pointer
33067dc3e15SAidan Dodds       sp += arg_size;
331f4786785SAidan Dodds     }
332f4786785SAidan Dodds     // fail if we couldn't read this argument
333b9c1b51eSKate Stone     if (!success) {
334f4786785SAidan Dodds       if (log)
33567dc3e15SAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
33680af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
337f4786785SAidan Dodds       return false;
338f4786785SAidan Dodds     }
339f4786785SAidan Dodds   }
340f4786785SAidan Dodds   return true;
341f4786785SAidan Dodds }
342f4786785SAidan Dodds 
343b9c1b51eSKate Stone bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
344f4786785SAidan Dodds   // number of arguments passed in registers
34580af0b9eSLuke Drummond   static const uint32_t args_in_reg = 8;
346f4786785SAidan Dodds   // register file offset to first argument
34780af0b9eSLuke Drummond   static const uint32_t reg_offset = 4;
348f4786785SAidan Dodds 
349f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
350f4786785SAidan Dodds 
35180af0b9eSLuke Drummond   Error err;
35217e07c0aSAidan Dodds 
353f4786785SAidan Dodds   // get the current stack pointer
354f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
355f4786785SAidan Dodds 
356b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
357f4786785SAidan Dodds     bool success = false;
358f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
359f4786785SAidan Dodds     // arguments passed in registers
36080af0b9eSLuke Drummond     if (i < args_in_reg) {
36180af0b9eSLuke Drummond       const RegisterInfo *reg =
36280af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
36380af0b9eSLuke Drummond       RegisterValue reg_val;
36480af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
36580af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
366f4786785SAidan Dodds     }
367f4786785SAidan Dodds     // arguments passed on the stack
368b9c1b51eSKate Stone     else {
369f4786785SAidan Dodds       // get the argument type size
370f4786785SAidan Dodds       const size_t arg_size = sizeof(uint64_t);
371f4786785SAidan Dodds       // clear all 64bits
372f4786785SAidan Dodds       arg.value = 0;
373f4786785SAidan Dodds       // read this argument from memory
374b9c1b51eSKate Stone       size_t bytes_read =
37580af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
37680af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
377f4786785SAidan Dodds       // advance the stack pointer
378f4786785SAidan Dodds       sp += arg_size;
379f4786785SAidan Dodds     }
380f4786785SAidan Dodds     // fail if we couldn't read this argument
381b9c1b51eSKate Stone     if (!success) {
382f4786785SAidan Dodds       if (log)
38317e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
38480af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
385f4786785SAidan Dodds       return false;
386f4786785SAidan Dodds     }
387f4786785SAidan Dodds   }
388f4786785SAidan Dodds   return true;
389f4786785SAidan Dodds }
390f4786785SAidan Dodds 
39180af0b9eSLuke Drummond bool GetArgs(ExecutionContext &exe_ctx, ArgItem *arg_list, size_t num_args) {
392f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
393f4786785SAidan Dodds 
394f4786785SAidan Dodds   // verify that we have a target
39580af0b9eSLuke Drummond   if (!exe_ctx.GetTargetPtr()) {
396f4786785SAidan Dodds     if (log)
397f4786785SAidan Dodds       log->Printf("%s - invalid target", __FUNCTION__);
398f4786785SAidan Dodds     return false;
399f4786785SAidan Dodds   }
400f4786785SAidan Dodds 
40180af0b9eSLuke Drummond   GetArgsCtx ctx = {exe_ctx.GetRegisterContext(), exe_ctx.GetProcessPtr()};
402f4786785SAidan Dodds   assert(ctx.reg_ctx && ctx.process);
403f4786785SAidan Dodds 
404f4786785SAidan Dodds   // dispatch based on architecture
40580af0b9eSLuke Drummond   switch (exe_ctx.GetTargetPtr()->GetArchitecture().GetMachine()) {
406f4786785SAidan Dodds   case llvm::Triple::ArchType::x86:
407f4786785SAidan Dodds     return GetArgsX86(ctx, arg_list, num_args);
408f4786785SAidan Dodds 
409f4786785SAidan Dodds   case llvm::Triple::ArchType::x86_64:
410f4786785SAidan Dodds     return GetArgsX86_64(ctx, arg_list, num_args);
411f4786785SAidan Dodds 
412f4786785SAidan Dodds   case llvm::Triple::ArchType::arm:
413f4786785SAidan Dodds     return GetArgsArm(ctx, arg_list, num_args);
414f4786785SAidan Dodds 
415f4786785SAidan Dodds   case llvm::Triple::ArchType::aarch64:
416f4786785SAidan Dodds     return GetArgsAarch64(ctx, arg_list, num_args);
417f4786785SAidan Dodds 
418f4786785SAidan Dodds   case llvm::Triple::ArchType::mipsel:
419f4786785SAidan Dodds     return GetArgsMipsel(ctx, arg_list, num_args);
420f4786785SAidan Dodds 
421f4786785SAidan Dodds   case llvm::Triple::ArchType::mips64el:
422f4786785SAidan Dodds     return GetArgsMips64el(ctx, arg_list, num_args);
423f4786785SAidan Dodds 
424f4786785SAidan Dodds   default:
425f4786785SAidan Dodds     // unsupported architecture
426b9c1b51eSKate Stone     if (log) {
427b9c1b51eSKate Stone       log->Printf(
428b9c1b51eSKate Stone           "%s - architecture not supported: '%s'", __FUNCTION__,
42980af0b9eSLuke Drummond           exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
430f4786785SAidan Dodds     }
431f4786785SAidan Dodds     return false;
432f4786785SAidan Dodds   }
433f4786785SAidan Dodds }
43400f56eebSLuke Drummond 
435*b3bbcb12SLuke Drummond bool IsRenderScriptScriptModule(ModuleSP module) {
436*b3bbcb12SLuke Drummond   if (!module)
437*b3bbcb12SLuke Drummond     return false;
438*b3bbcb12SLuke Drummond   return module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
439*b3bbcb12SLuke Drummond                                                 eSymbolTypeData) != nullptr;
440*b3bbcb12SLuke Drummond }
441*b3bbcb12SLuke Drummond 
44200f56eebSLuke Drummond bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
44300f56eebSLuke Drummond   // takes an argument of the form 'num[,num][,num]'.
44400f56eebSLuke Drummond   // Where 'coord_s' is a comma separated 1,2 or 3-dimensional coordinate
44500f56eebSLuke Drummond   // with the whitespace trimmed.
44600f56eebSLuke Drummond   // Missing coordinates are defaulted to zero.
44700f56eebSLuke Drummond   // If parsing of any elements fails the contents of &coord are undefined
44800f56eebSLuke Drummond   // and `false` is returned, `true` otherwise
44900f56eebSLuke Drummond 
45000f56eebSLuke Drummond   RegularExpression regex;
45100f56eebSLuke Drummond   RegularExpression::Match regex_match(3);
45200f56eebSLuke Drummond 
45300f56eebSLuke Drummond   bool matched = false;
45400f56eebSLuke Drummond   if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+),([0-9]+)$")) &&
45500f56eebSLuke Drummond       regex.Execute(coord_s, &regex_match))
45600f56eebSLuke Drummond     matched = true;
45700f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+)$")) &&
45800f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
45900f56eebSLuke Drummond     matched = true;
46000f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([0-9]+)$")) &&
46100f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
46200f56eebSLuke Drummond     matched = true;
46300f56eebSLuke Drummond 
46400f56eebSLuke Drummond   if (!matched)
46500f56eebSLuke Drummond     return false;
46600f56eebSLuke Drummond 
46700f56eebSLuke Drummond   auto get_index = [&](int idx, uint32_t &i) -> bool {
46800f56eebSLuke Drummond     std::string group;
46900f56eebSLuke Drummond     errno = 0;
47000f56eebSLuke Drummond     if (regex_match.GetMatchAtIndex(coord_s.str().c_str(), idx + 1, group))
47100f56eebSLuke Drummond       return !llvm::StringRef(group).getAsInteger<uint32_t>(10, i);
47200f56eebSLuke Drummond     return true;
47300f56eebSLuke Drummond   };
47400f56eebSLuke Drummond 
47500f56eebSLuke Drummond   return get_index(0, coord.x) && get_index(1, coord.y) &&
47600f56eebSLuke Drummond          get_index(2, coord.z);
47700f56eebSLuke Drummond }
478222b937cSEugene Zelenko } // anonymous namespace
47978f339d1SEwan Crawford 
480b9c1b51eSKate Stone // The ScriptDetails class collects data associated with a single script
481b9c1b51eSKate Stone // instance.
482b9c1b51eSKate Stone struct RenderScriptRuntime::ScriptDetails {
483222b937cSEugene Zelenko   ~ScriptDetails() = default;
48478f339d1SEwan Crawford 
485b9c1b51eSKate Stone   enum ScriptType { eScript, eScriptC };
48678f339d1SEwan Crawford 
48778f339d1SEwan Crawford   // The derived type of the script.
48878f339d1SEwan Crawford   empirical_type<ScriptType> type;
48978f339d1SEwan Crawford   // The name of the original source file.
49080af0b9eSLuke Drummond   empirical_type<std::string> res_name;
49178f339d1SEwan Crawford   // Path to script .so file on the device.
49280af0b9eSLuke Drummond   empirical_type<std::string> shared_lib;
49378f339d1SEwan Crawford   // Directory where kernel objects are cached on device.
49480af0b9eSLuke Drummond   empirical_type<std::string> cache_dir;
49578f339d1SEwan Crawford   // Pointer to the context which owns this script.
49678f339d1SEwan Crawford   empirical_type<lldb::addr_t> context;
49778f339d1SEwan Crawford   // Pointer to the script object itself.
49878f339d1SEwan Crawford   empirical_type<lldb::addr_t> script;
49978f339d1SEwan Crawford };
50078f339d1SEwan Crawford 
50180af0b9eSLuke Drummond // This Element class represents the Element object in RS, defining the type
50280af0b9eSLuke Drummond // associated with an Allocation.
503b9c1b51eSKate Stone struct RenderScriptRuntime::Element {
50415f2bd95SEwan Crawford   // Taken from rsDefines.h
505b9c1b51eSKate Stone   enum DataKind {
50615f2bd95SEwan Crawford     RS_KIND_USER,
50715f2bd95SEwan Crawford     RS_KIND_PIXEL_L = 7,
50815f2bd95SEwan Crawford     RS_KIND_PIXEL_A,
50915f2bd95SEwan Crawford     RS_KIND_PIXEL_LA,
51015f2bd95SEwan Crawford     RS_KIND_PIXEL_RGB,
51115f2bd95SEwan Crawford     RS_KIND_PIXEL_RGBA,
51215f2bd95SEwan Crawford     RS_KIND_PIXEL_DEPTH,
51315f2bd95SEwan Crawford     RS_KIND_PIXEL_YUV,
51415f2bd95SEwan Crawford     RS_KIND_INVALID = 100
51515f2bd95SEwan Crawford   };
51678f339d1SEwan Crawford 
51715f2bd95SEwan Crawford   // Taken from rsDefines.h
518b9c1b51eSKate Stone   enum DataType {
51915f2bd95SEwan Crawford     RS_TYPE_NONE = 0,
52015f2bd95SEwan Crawford     RS_TYPE_FLOAT_16,
52115f2bd95SEwan Crawford     RS_TYPE_FLOAT_32,
52215f2bd95SEwan Crawford     RS_TYPE_FLOAT_64,
52315f2bd95SEwan Crawford     RS_TYPE_SIGNED_8,
52415f2bd95SEwan Crawford     RS_TYPE_SIGNED_16,
52515f2bd95SEwan Crawford     RS_TYPE_SIGNED_32,
52615f2bd95SEwan Crawford     RS_TYPE_SIGNED_64,
52715f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_8,
52815f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_16,
52915f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_32,
53015f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_64,
5312e920715SEwan Crawford     RS_TYPE_BOOLEAN,
5322e920715SEwan Crawford 
5332e920715SEwan Crawford     RS_TYPE_UNSIGNED_5_6_5,
5342e920715SEwan Crawford     RS_TYPE_UNSIGNED_5_5_5_1,
5352e920715SEwan Crawford     RS_TYPE_UNSIGNED_4_4_4_4,
5362e920715SEwan Crawford 
5372e920715SEwan Crawford     RS_TYPE_MATRIX_4X4,
5382e920715SEwan Crawford     RS_TYPE_MATRIX_3X3,
5392e920715SEwan Crawford     RS_TYPE_MATRIX_2X2,
5402e920715SEwan Crawford 
5412e920715SEwan Crawford     RS_TYPE_ELEMENT = 1000,
5422e920715SEwan Crawford     RS_TYPE_TYPE,
5432e920715SEwan Crawford     RS_TYPE_ALLOCATION,
5442e920715SEwan Crawford     RS_TYPE_SAMPLER,
5452e920715SEwan Crawford     RS_TYPE_SCRIPT,
5462e920715SEwan Crawford     RS_TYPE_MESH,
5472e920715SEwan Crawford     RS_TYPE_PROGRAM_FRAGMENT,
5482e920715SEwan Crawford     RS_TYPE_PROGRAM_VERTEX,
5492e920715SEwan Crawford     RS_TYPE_PROGRAM_RASTER,
5502e920715SEwan Crawford     RS_TYPE_PROGRAM_STORE,
5512e920715SEwan Crawford     RS_TYPE_FONT,
5522e920715SEwan Crawford 
5532e920715SEwan Crawford     RS_TYPE_INVALID = 10000
55478f339d1SEwan Crawford   };
55578f339d1SEwan Crawford 
5568b244e21SEwan Crawford   std::vector<Element> children; // Child Element fields for structs
557b9c1b51eSKate Stone   empirical_type<lldb::addr_t>
558b9c1b51eSKate Stone       element_ptr; // Pointer to the RS Element of the Type
559b9c1b51eSKate Stone   empirical_type<DataType>
560b9c1b51eSKate Stone       type; // Type of each data pointer stored by the allocation
561b9c1b51eSKate Stone   empirical_type<DataKind>
562b9c1b51eSKate Stone       type_kind; // Defines pixel type if Allocation is created from an image
563b9c1b51eSKate Stone   empirical_type<uint32_t>
564b9c1b51eSKate Stone       type_vec_size; // Vector size of each data point, e.g '4' for uchar4
5658b244e21SEwan Crawford   empirical_type<uint32_t> field_count; // Number of Subelements
5668b244e21SEwan Crawford   empirical_type<uint32_t> datum_size;  // Size of a single Element with padding
5678b244e21SEwan Crawford   empirical_type<uint32_t> padding;     // Number of padding bytes
568b9c1b51eSKate Stone   empirical_type<uint32_t>
569b9c1b51eSKate Stone       array_size;        // Number of items in array, only needed for strucrs
5708b244e21SEwan Crawford   ConstString type_name; // Name of type, only needed for structs
5718b244e21SEwan Crawford 
572b3f7f69dSAidan Dodds   static const ConstString &
573b3f7f69dSAidan Dodds   GetFallbackStructName(); // Print this as the type name of a struct Element
5748b244e21SEwan Crawford                            // If we can't resolve the actual struct name
5758b59062aSEwan Crawford 
57680af0b9eSLuke Drummond   bool ShouldRefresh() const {
5778b59062aSEwan Crawford     const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
578b9c1b51eSKate Stone     const bool valid_type =
579b9c1b51eSKate Stone         type.isValid() && type_vec_size.isValid() && type_kind.isValid();
5808b59062aSEwan Crawford     return !valid_ptr || !valid_type || !datum_size.isValid();
5818b59062aSEwan Crawford   }
5828b244e21SEwan Crawford };
5838b244e21SEwan Crawford 
5848b244e21SEwan Crawford // This AllocationDetails class collects data associated with a single
5858b244e21SEwan Crawford // allocation instance.
586b9c1b51eSKate Stone struct RenderScriptRuntime::AllocationDetails {
587b9c1b51eSKate Stone   struct Dimension {
58815f2bd95SEwan Crawford     uint32_t dim_1;
58915f2bd95SEwan Crawford     uint32_t dim_2;
59015f2bd95SEwan Crawford     uint32_t dim_3;
59180af0b9eSLuke Drummond     uint32_t cube_map;
59215f2bd95SEwan Crawford 
593b9c1b51eSKate Stone     Dimension() {
59415f2bd95SEwan Crawford       dim_1 = 0;
59515f2bd95SEwan Crawford       dim_2 = 0;
59615f2bd95SEwan Crawford       dim_3 = 0;
59780af0b9eSLuke Drummond       cube_map = 0;
59815f2bd95SEwan Crawford     }
59978f339d1SEwan Crawford   };
60078f339d1SEwan Crawford 
601b9c1b51eSKate Stone   // The FileHeader struct specifies the header we use for writing allocations
60280af0b9eSLuke Drummond   // to a binary file. Our format begins with the ASCII characters "RSAD",
60380af0b9eSLuke Drummond   // identifying the file as an allocation dump. Member variables dims and
60480af0b9eSLuke Drummond   // hdr_size are then written consecutively, immediately followed by an
60580af0b9eSLuke Drummond   // instance of the ElementHeader struct. Because Elements can contain
60680af0b9eSLuke Drummond   // subelements, there may be more than one instance of the ElementHeader
60780af0b9eSLuke Drummond   // struct. With this first instance being the root element, and the other
60880af0b9eSLuke Drummond   // instances being the root's descendants. To identify which instances are an
60980af0b9eSLuke Drummond   // ElementHeader's children, each struct is immediately followed by a sequence
61080af0b9eSLuke Drummond   // of consecutive offsets to the start of its child structs. These offsets are
61180af0b9eSLuke Drummond   // 4 bytes in size, and the 0 offset signifies no more children.
612b9c1b51eSKate Stone   struct FileHeader {
61355232f09SEwan Crawford     uint8_t ident[4];  // ASCII 'RSAD' identifying the file
61426e52a70SEwan Crawford     uint32_t dims[3];  // Dimensions
61526e52a70SEwan Crawford     uint16_t hdr_size; // Header size in bytes, including all element headers
61626e52a70SEwan Crawford   };
61726e52a70SEwan Crawford 
618b9c1b51eSKate Stone   struct ElementHeader {
61955232f09SEwan Crawford     uint16_t type;         // DataType enum
62055232f09SEwan Crawford     uint32_t kind;         // DataKind enum
62155232f09SEwan Crawford     uint32_t element_size; // Size of a single element, including padding
62226e52a70SEwan Crawford     uint16_t vector_size;  // Vector width
62326e52a70SEwan Crawford     uint32_t array_size;   // Number of elements in array
62455232f09SEwan Crawford   };
62555232f09SEwan Crawford 
62615f2bd95SEwan Crawford   // Monotonically increasing from 1
627b3f7f69dSAidan Dodds   static uint32_t ID;
62815f2bd95SEwan Crawford 
62915f2bd95SEwan Crawford   // Maps Allocation DataType enum and vector size to printable strings
63015f2bd95SEwan Crawford   // using mapping from RenderScript numerical types summary documentation
63115f2bd95SEwan Crawford   static const char *RsDataTypeToString[][4];
63215f2bd95SEwan Crawford 
63315f2bd95SEwan Crawford   // Maps Allocation DataKind enum to printable strings
63415f2bd95SEwan Crawford   static const char *RsDataKindToString[];
63515f2bd95SEwan Crawford 
636a0f08674SEwan Crawford   // Maps allocation types to format sizes for printing.
637b3f7f69dSAidan Dodds   static const uint32_t RSTypeToFormat[][3];
638a0f08674SEwan Crawford 
63915f2bd95SEwan Crawford   // Give each allocation an ID as a way
64015f2bd95SEwan Crawford   // for commands to reference it.
641b3f7f69dSAidan Dodds   const uint32_t id;
64215f2bd95SEwan Crawford 
64380af0b9eSLuke Drummond   // Allocation Element type
64480af0b9eSLuke Drummond   RenderScriptRuntime::Element element;
64580af0b9eSLuke Drummond   // Dimensions of the Allocation
64680af0b9eSLuke Drummond   empirical_type<Dimension> dimension;
64780af0b9eSLuke Drummond   // Pointer to address of the RS Allocation
64880af0b9eSLuke Drummond   empirical_type<lldb::addr_t> address;
64980af0b9eSLuke Drummond   // Pointer to the data held by the Allocation
65080af0b9eSLuke Drummond   empirical_type<lldb::addr_t> data_ptr;
65180af0b9eSLuke Drummond   // Pointer to the RS Type of the Allocation
65280af0b9eSLuke Drummond   empirical_type<lldb::addr_t> type_ptr;
65380af0b9eSLuke Drummond   // Pointer to the RS Context of the Allocation
65480af0b9eSLuke Drummond   empirical_type<lldb::addr_t> context;
65580af0b9eSLuke Drummond   // Size of the allocation
65680af0b9eSLuke Drummond   empirical_type<uint32_t> size;
65780af0b9eSLuke Drummond   // Stride between rows of the allocation
65880af0b9eSLuke Drummond   empirical_type<uint32_t> stride;
65915f2bd95SEwan Crawford 
66015f2bd95SEwan Crawford   // Give each allocation an id, so we can reference it in user commands.
661b3f7f69dSAidan Dodds   AllocationDetails() : id(ID++) {}
6628b59062aSEwan Crawford 
66380af0b9eSLuke Drummond   bool ShouldRefresh() const {
6648b59062aSEwan Crawford     bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
6658b59062aSEwan Crawford     valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
666b9c1b51eSKate Stone     return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
66780af0b9eSLuke Drummond            element.ShouldRefresh();
6688b59062aSEwan Crawford   }
66915f2bd95SEwan Crawford };
67015f2bd95SEwan Crawford 
671b9c1b51eSKate Stone const ConstString &RenderScriptRuntime::Element::GetFallbackStructName() {
672fe06b5adSAdrian McCarthy   static const ConstString FallbackStructName("struct");
673fe06b5adSAdrian McCarthy   return FallbackStructName;
674fe06b5adSAdrian McCarthy }
6758b244e21SEwan Crawford 
676b3f7f69dSAidan Dodds uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
67715f2bd95SEwan Crawford 
678b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
679b9c1b51eSKate Stone     "User",       "Undefined",   "Undefined", "Undefined",
680b9c1b51eSKate Stone     "Undefined",  "Undefined",   "Undefined", // Enum jumps from 0 to 7
681b3f7f69dSAidan Dodds     "L Pixel",    "A Pixel",     "LA Pixel",  "RGB Pixel",
682b3f7f69dSAidan Dodds     "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
68315f2bd95SEwan Crawford 
684b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
68515f2bd95SEwan Crawford     {"None", "None", "None", "None"},
68615f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
68715f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
68815f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
68915f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
69015f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
69115f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
69215f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
69315f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
69415f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
69515f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
69615f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
6972e920715SEwan Crawford     {"bool", "bool2", "bool3", "bool4"},
6982e920715SEwan Crawford     {"packed_565", "packed_565", "packed_565", "packed_565"},
6992e920715SEwan Crawford     {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
7002e920715SEwan Crawford     {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
7012e920715SEwan Crawford     {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
7022e920715SEwan Crawford     {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
7032e920715SEwan Crawford     {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
7042e920715SEwan Crawford 
7052e920715SEwan Crawford     // Handlers
7062e920715SEwan Crawford     {"RS Element", "RS Element", "RS Element", "RS Element"},
7072e920715SEwan Crawford     {"RS Type", "RS Type", "RS Type", "RS Type"},
7082e920715SEwan Crawford     {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
7092e920715SEwan Crawford     {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
7102e920715SEwan Crawford     {"RS Script", "RS Script", "RS Script", "RS Script"},
7112e920715SEwan Crawford 
7122e920715SEwan Crawford     // Deprecated
7132e920715SEwan Crawford     {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
714b9c1b51eSKate Stone     {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
715b9c1b51eSKate Stone      "RS Program Fragment"},
716b9c1b51eSKate Stone     {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
717b9c1b51eSKate Stone      "RS Program Vertex"},
718b9c1b51eSKate Stone     {"RS Program Raster", "RS Program Raster", "RS Program Raster",
719b9c1b51eSKate Stone      "RS Program Raster"},
720b9c1b51eSKate Stone     {"RS Program Store", "RS Program Store", "RS Program Store",
721b9c1b51eSKate Stone      "RS Program Store"},
722b3f7f69dSAidan Dodds     {"RS Font", "RS Font", "RS Font", "RS Font"}};
72378f339d1SEwan Crawford 
724a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
725b9c1b51eSKate Stone enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
726a0f08674SEwan Crawford 
727b9c1b51eSKate Stone // { format enum of single element, format enum of element vector, size of
728b9c1b51eSKate Stone // element}
729b3f7f69dSAidan Dodds const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
73080af0b9eSLuke Drummond     // RS_TYPE_NONE
73180af0b9eSLuke Drummond     {eFormatHex, eFormatHex, 1},
73280af0b9eSLuke Drummond     // RS_TYPE_FLOAT_16
73380af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat16, 2},
73480af0b9eSLuke Drummond     // RS_TYPE_FLOAT_32
73580af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
73680af0b9eSLuke Drummond     // RS_TYPE_FLOAT_64
73780af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
73880af0b9eSLuke Drummond     // RS_TYPE_SIGNED_8
73980af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
74080af0b9eSLuke Drummond     // RS_TYPE_SIGNED_16
74180af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
74280af0b9eSLuke Drummond     // RS_TYPE_SIGNED_32
74380af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
74480af0b9eSLuke Drummond     // RS_TYPE_SIGNED_64
74580af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
74680af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_8
74780af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
74880af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_16
74980af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
75080af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_32
75180af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
75280af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_64
75380af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
75480af0b9eSLuke Drummond     // RS_TYPE_BOOL
75580af0b9eSLuke Drummond     {eFormatBoolean, eFormatBoolean, 1},
75680af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_5_6_5
75780af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
75880af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_5_5_5_1
75980af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
76080af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_4_4_4_4
76180af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
76280af0b9eSLuke Drummond     // RS_TYPE_MATRIX_4X4
76380af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
76480af0b9eSLuke Drummond     // RS_TYPE_MATRIX_3X3
76580af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
76680af0b9eSLuke Drummond     // RS_TYPE_MATRIX_2X2
76780af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
768a0f08674SEwan Crawford 
7695ec532a9SColin Riley //------------------------------------------------------------------
7705ec532a9SColin Riley // Static Functions
7715ec532a9SColin Riley //------------------------------------------------------------------
7725ec532a9SColin Riley LanguageRuntime *
773b9c1b51eSKate Stone RenderScriptRuntime::CreateInstance(Process *process,
774b9c1b51eSKate Stone                                     lldb::LanguageType language) {
7755ec532a9SColin Riley 
7765ec532a9SColin Riley   if (language == eLanguageTypeExtRenderScript)
7775ec532a9SColin Riley     return new RenderScriptRuntime(process);
7785ec532a9SColin Riley   else
779b3f7f69dSAidan Dodds     return nullptr;
7805ec532a9SColin Riley }
7815ec532a9SColin Riley 
78280af0b9eSLuke Drummond // Callback with a module to search for matching symbols. We first check that
78380af0b9eSLuke Drummond // the module contains RS kernels. Then look for a symbol which matches our
78480af0b9eSLuke Drummond // kernel name. The breakpoint address is finally set using the address of this
78580af0b9eSLuke Drummond // symbol.
78698156583SEwan Crawford Searcher::CallbackReturn
787b9c1b51eSKate Stone RSBreakpointResolver::SearchCallback(SearchFilter &filter,
788b9c1b51eSKate Stone                                      SymbolContext &context, Address *, bool) {
78998156583SEwan Crawford   ModuleSP module = context.module_sp;
79098156583SEwan Crawford 
791*b3bbcb12SLuke Drummond   if (!module || !IsRenderScriptScriptModule(module))
79298156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
79398156583SEwan Crawford 
794b9c1b51eSKate Stone   // Attempt to set a breakpoint on the kernel name symbol within the module
79580af0b9eSLuke Drummond   // library. If it's not found, it's likely debug info is unavailable - try to
79680af0b9eSLuke Drummond   // set a breakpoint on <name>.expand.
797b9c1b51eSKate Stone   const Symbol *kernel_sym =
798b9c1b51eSKate Stone       module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
799b9c1b51eSKate Stone   if (!kernel_sym) {
80098156583SEwan Crawford     std::string kernel_name_expanded(m_kernel_name.AsCString());
80198156583SEwan Crawford     kernel_name_expanded.append(".expand");
802b9c1b51eSKate Stone     kernel_sym = module->FindFirstSymbolWithNameAndType(
803b9c1b51eSKate Stone         ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
80498156583SEwan Crawford   }
80598156583SEwan Crawford 
806b9c1b51eSKate Stone   if (kernel_sym) {
80798156583SEwan Crawford     Address bp_addr = kernel_sym->GetAddress();
80898156583SEwan Crawford     if (filter.AddressPasses(bp_addr))
80998156583SEwan Crawford       m_breakpoint->AddLocation(bp_addr);
81098156583SEwan Crawford   }
81198156583SEwan Crawford 
81298156583SEwan Crawford   return Searcher::eCallbackReturnContinue;
81398156583SEwan Crawford }
81498156583SEwan Crawford 
815*b3bbcb12SLuke Drummond Searcher::CallbackReturn
816*b3bbcb12SLuke Drummond RSReduceBreakpointResolver::SearchCallback(lldb_private::SearchFilter &filter,
817*b3bbcb12SLuke Drummond                                            lldb_private::SymbolContext &context,
818*b3bbcb12SLuke Drummond                                            Address *, bool) {
819*b3bbcb12SLuke Drummond   // We need to have access to the list of reductions currently parsed, as
820*b3bbcb12SLuke Drummond   // reduce names don't actually exist as
821*b3bbcb12SLuke Drummond   // symbols in a module. They are only identifiable by parsing the .rs.info
822*b3bbcb12SLuke Drummond   // packet, or finding the expand symbol. We
823*b3bbcb12SLuke Drummond   // therefore need access to the list of parsed rs modules to properly resolve
824*b3bbcb12SLuke Drummond   // reduction names.
825*b3bbcb12SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
826*b3bbcb12SLuke Drummond   ModuleSP module = context.module_sp;
827*b3bbcb12SLuke Drummond 
828*b3bbcb12SLuke Drummond   if (!module || !IsRenderScriptScriptModule(module))
829*b3bbcb12SLuke Drummond     return Searcher::eCallbackReturnContinue;
830*b3bbcb12SLuke Drummond 
831*b3bbcb12SLuke Drummond   if (!m_rsmodules)
832*b3bbcb12SLuke Drummond     return Searcher::eCallbackReturnContinue;
833*b3bbcb12SLuke Drummond 
834*b3bbcb12SLuke Drummond   for (const auto &module_desc : *m_rsmodules) {
835*b3bbcb12SLuke Drummond     if (module_desc->m_module != module)
836*b3bbcb12SLuke Drummond       continue;
837*b3bbcb12SLuke Drummond 
838*b3bbcb12SLuke Drummond     for (const auto &reduction : module_desc->m_reductions) {
839*b3bbcb12SLuke Drummond       if (reduction.m_reduce_name != m_reduce_name)
840*b3bbcb12SLuke Drummond         continue;
841*b3bbcb12SLuke Drummond 
842*b3bbcb12SLuke Drummond       std::array<std::pair<ConstString, int>, 5> funcs{
843*b3bbcb12SLuke Drummond           {{reduction.m_init_name, eKernelTypeInit},
844*b3bbcb12SLuke Drummond            {reduction.m_accum_name, eKernelTypeAccum},
845*b3bbcb12SLuke Drummond            {reduction.m_comb_name, eKernelTypeComb},
846*b3bbcb12SLuke Drummond            {reduction.m_outc_name, eKernelTypeOutC},
847*b3bbcb12SLuke Drummond            {reduction.m_halter_name, eKernelTypeHalter}}};
848*b3bbcb12SLuke Drummond 
849*b3bbcb12SLuke Drummond       for (const auto &kernel : funcs) {
850*b3bbcb12SLuke Drummond         // Skip constituent functions that don't match our spec
851*b3bbcb12SLuke Drummond         if (!(m_kernel_types & kernel.second))
852*b3bbcb12SLuke Drummond           continue;
853*b3bbcb12SLuke Drummond 
854*b3bbcb12SLuke Drummond         const auto kernel_name = kernel.first;
855*b3bbcb12SLuke Drummond         const auto symbol = module->FindFirstSymbolWithNameAndType(
856*b3bbcb12SLuke Drummond             kernel_name, eSymbolTypeCode);
857*b3bbcb12SLuke Drummond         if (!symbol)
858*b3bbcb12SLuke Drummond           continue;
859*b3bbcb12SLuke Drummond 
860*b3bbcb12SLuke Drummond         auto address = symbol->GetAddress();
861*b3bbcb12SLuke Drummond         if (filter.AddressPasses(address)) {
862*b3bbcb12SLuke Drummond           bool new_bp;
863*b3bbcb12SLuke Drummond           m_breakpoint->AddLocation(address, &new_bp);
864*b3bbcb12SLuke Drummond           if (log)
865*b3bbcb12SLuke Drummond             log->Printf("%s: %s reduction breakpoint on %s in %s", __FUNCTION__,
866*b3bbcb12SLuke Drummond                         new_bp ? "new" : "existing", kernel_name.GetCString(),
867*b3bbcb12SLuke Drummond                         address.GetModule()->GetFileSpec().GetCString());
868*b3bbcb12SLuke Drummond         }
869*b3bbcb12SLuke Drummond       }
870*b3bbcb12SLuke Drummond     }
871*b3bbcb12SLuke Drummond   }
872*b3bbcb12SLuke Drummond   return eCallbackReturnContinue;
873*b3bbcb12SLuke Drummond }
874*b3bbcb12SLuke Drummond 
875b9c1b51eSKate Stone void RenderScriptRuntime::Initialize() {
876b9c1b51eSKate Stone   PluginManager::RegisterPlugin(GetPluginNameStatic(),
877b9c1b51eSKate Stone                                 "RenderScript language support", CreateInstance,
878b3f7f69dSAidan Dodds                                 GetCommandObject);
8795ec532a9SColin Riley }
8805ec532a9SColin Riley 
881b9c1b51eSKate Stone void RenderScriptRuntime::Terminate() {
8825ec532a9SColin Riley   PluginManager::UnregisterPlugin(CreateInstance);
8835ec532a9SColin Riley }
8845ec532a9SColin Riley 
885b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginNameStatic() {
88680af0b9eSLuke Drummond   static ConstString plugin_name("renderscript");
88780af0b9eSLuke Drummond   return plugin_name;
8885ec532a9SColin Riley }
8895ec532a9SColin Riley 
890ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
891b9c1b51eSKate Stone RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
892b9c1b51eSKate Stone   if (module_sp) {
893*b3bbcb12SLuke Drummond     if (IsRenderScriptScriptModule(module_sp))
894ef20b08fSColin Riley       return eModuleKindKernelObj;
8954640cde1SColin Riley 
8964640cde1SColin Riley     // Is this the main RS runtime library
8974640cde1SColin Riley     const ConstString rs_lib("libRS.so");
898b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
8994640cde1SColin Riley       return eModuleKindLibRS;
9004640cde1SColin Riley     }
9014640cde1SColin Riley 
9024640cde1SColin Riley     const ConstString rs_driverlib("libRSDriver.so");
903b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
9044640cde1SColin Riley       return eModuleKindDriver;
9054640cde1SColin Riley     }
9064640cde1SColin Riley 
90715f2bd95SEwan Crawford     const ConstString rs_cpureflib("libRSCpuRef.so");
908b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
9094640cde1SColin Riley       return eModuleKindImpl;
9104640cde1SColin Riley     }
911ef20b08fSColin Riley   }
912ef20b08fSColin Riley   return eModuleKindIgnored;
913ef20b08fSColin Riley }
914ef20b08fSColin Riley 
915b9c1b51eSKate Stone bool RenderScriptRuntime::IsRenderScriptModule(
916b9c1b51eSKate Stone     const lldb::ModuleSP &module_sp) {
917ef20b08fSColin Riley   return GetModuleKind(module_sp) != eModuleKindIgnored;
918ef20b08fSColin Riley }
919ef20b08fSColin Riley 
920b9c1b51eSKate Stone void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
921bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
922ef20b08fSColin Riley 
923ef20b08fSColin Riley   size_t num_modules = module_list.GetSize();
924b9c1b51eSKate Stone   for (size_t i = 0; i < num_modules; i++) {
925ef20b08fSColin Riley     auto mod = module_list.GetModuleAtIndex(i);
926b9c1b51eSKate Stone     if (IsRenderScriptModule(mod)) {
927ef20b08fSColin Riley       LoadModule(mod);
928ef20b08fSColin Riley     }
929ef20b08fSColin Riley   }
930ef20b08fSColin Riley }
931ef20b08fSColin Riley 
9325ec532a9SColin Riley //------------------------------------------------------------------
9335ec532a9SColin Riley // PluginInterface protocol
9345ec532a9SColin Riley //------------------------------------------------------------------
935b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginName() {
9365ec532a9SColin Riley   return GetPluginNameStatic();
9375ec532a9SColin Riley }
9385ec532a9SColin Riley 
939b9c1b51eSKate Stone uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; }
9405ec532a9SColin Riley 
941b9c1b51eSKate Stone bool RenderScriptRuntime::IsVTableName(const char *name) { return false; }
9425ec532a9SColin Riley 
943b9c1b51eSKate Stone bool RenderScriptRuntime::GetDynamicTypeAndAddress(
944b9c1b51eSKate Stone     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
9455f57b6eeSEnrico Granata     TypeAndOrName &class_type_or_name, Address &address,
946b9c1b51eSKate Stone     Value::ValueType &value_type) {
9475ec532a9SColin Riley   return false;
9485ec532a9SColin Riley }
9495ec532a9SColin Riley 
950c74275bcSEnrico Granata TypeAndOrName
951b9c1b51eSKate Stone RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
952b9c1b51eSKate Stone                                       ValueObject &static_value) {
953c74275bcSEnrico Granata   return type_and_or_name;
954c74275bcSEnrico Granata }
955c74275bcSEnrico Granata 
956b9c1b51eSKate Stone bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
9575ec532a9SColin Riley   return false;
9585ec532a9SColin Riley }
9595ec532a9SColin Riley 
9605ec532a9SColin Riley lldb::BreakpointResolverSP
96180af0b9eSLuke Drummond RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bp, bool catch_bp,
962b9c1b51eSKate Stone                                              bool throw_bp) {
9635ec532a9SColin Riley   BreakpointResolverSP resolver_sp;
9645ec532a9SColin Riley   return resolver_sp;
9655ec532a9SColin Riley }
9665ec532a9SColin Riley 
967b9c1b51eSKate Stone const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
968b9c1b51eSKate Stone     {
9694640cde1SColin Riley         // rsdScript
970b9c1b51eSKate Stone         {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
971b9c1b51eSKate Stone                           "NS0_7ScriptCEPKcS7_PKhjj",
972b9c1b51eSKate Stone          "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
973b9c1b51eSKate Stone          "7ScriptCEPKcS7_PKhmj",
974b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
975b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInit},
976b9c1b51eSKate Stone         {"rsdScriptInvokeForEachMulti",
977b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
978b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
979b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
980b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
981b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
982b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
983b9c1b51eSKate Stone         {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
984b9c1b51eSKate Stone                                   "script7ContextEPKNS0_6ScriptEjPvj",
985b9c1b51eSKate Stone          "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
986b9c1b51eSKate Stone          "6ScriptEjPvm",
987b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
988b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
9894640cde1SColin Riley 
9904640cde1SColin Riley         // rsdAllocation
991b9c1b51eSKate Stone         {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
992b9c1b51eSKate Stone                               "ontextEPNS0_10AllocationEb",
993b9c1b51eSKate Stone          "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
994b9c1b51eSKate Stone          "10AllocationEb",
995b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
996b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
997b9c1b51eSKate Stone         {"rsdAllocationRead2D",
998b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
999b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1000b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1001b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1002b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1003b9c1b51eSKate Stone         {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1004b9c1b51eSKate Stone                                  "ript7ContextEPNS0_10AllocationE",
1005b9c1b51eSKate Stone          "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1006b9c1b51eSKate Stone          "10AllocationE",
1007b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1008b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
10094640cde1SColin Riley };
10104640cde1SColin Riley 
1011b9c1b51eSKate Stone const size_t RenderScriptRuntime::s_runtimeHookCount =
1012b9c1b51eSKate Stone     sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
10134640cde1SColin Riley 
1014b9c1b51eSKate Stone bool RenderScriptRuntime::HookCallback(void *baton,
1015b9c1b51eSKate Stone                                        StoppointCallbackContext *ctx,
1016b9c1b51eSKate Stone                                        lldb::user_id_t break_id,
1017b9c1b51eSKate Stone                                        lldb::user_id_t break_loc_id) {
101880af0b9eSLuke Drummond   RuntimeHook *hook = (RuntimeHook *)baton;
101980af0b9eSLuke Drummond   ExecutionContext exe_ctx(ctx->exe_ctx_ref);
10204640cde1SColin Riley 
1021b3f7f69dSAidan Dodds   RenderScriptRuntime *lang_rt =
102280af0b9eSLuke Drummond       (RenderScriptRuntime *)exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1023b9c1b51eSKate Stone           eLanguageTypeExtRenderScript);
10244640cde1SColin Riley 
102580af0b9eSLuke Drummond   lang_rt->HookCallback(hook, exe_ctx);
10264640cde1SColin Riley 
10274640cde1SColin Riley   return false;
10284640cde1SColin Riley }
10294640cde1SColin Riley 
103080af0b9eSLuke Drummond void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
103180af0b9eSLuke Drummond                                        ExecutionContext &exe_ctx) {
10324640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
10334640cde1SColin Riley 
10344640cde1SColin Riley   if (log)
103580af0b9eSLuke Drummond     log->Printf("%s - '%s'", __FUNCTION__, hook->defn->name);
10364640cde1SColin Riley 
103780af0b9eSLuke Drummond   if (hook->defn->grabber) {
103880af0b9eSLuke Drummond     (this->*(hook->defn->grabber))(hook, exe_ctx);
10394640cde1SColin Riley   }
10404640cde1SColin Riley }
10414640cde1SColin Riley 
1042b9c1b51eSKate Stone void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
104380af0b9eSLuke Drummond     RuntimeHook *hook, ExecutionContext &exe_ctx) {
1044e09c44b6SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1045e09c44b6SAidan Dodds 
1046b9c1b51eSKate Stone   enum {
1047f4786785SAidan Dodds     eRsContext = 0,
1048f4786785SAidan Dodds     eRsScript,
1049f4786785SAidan Dodds     eRsSlot,
1050f4786785SAidan Dodds     eRsAIns,
1051f4786785SAidan Dodds     eRsInLen,
1052f4786785SAidan Dodds     eRsAOut,
1053f4786785SAidan Dodds     eRsUsr,
1054f4786785SAidan Dodds     eRsUsrLen,
1055f4786785SAidan Dodds     eRsSc,
1056f4786785SAidan Dodds   };
1057e09c44b6SAidan Dodds 
10581ee07253SSaleem Abdulrasool   std::array<ArgItem, 9> args{{
1059f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Context       *rsc
1060f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Script              *s
1061f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // uint32_t             slot
1062f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Allocation   **aIns
1063f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               inLen
1064f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Allocation          *aout
1065f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const void          *usr
1066f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               usrLen
1067f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall  *sc
10681ee07253SSaleem Abdulrasool   }};
1069e09c44b6SAidan Dodds 
107080af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1071b9c1b51eSKate Stone   if (!success) {
1072e09c44b6SAidan Dodds     if (log)
1073b9c1b51eSKate Stone       log->Printf("%s - Error while reading the function parameters",
1074b9c1b51eSKate Stone                   __FUNCTION__);
1075e09c44b6SAidan Dodds     return;
1076e09c44b6SAidan Dodds   }
1077e09c44b6SAidan Dodds 
1078e09c44b6SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
107980af0b9eSLuke Drummond   Error err;
1080e09c44b6SAidan Dodds   std::vector<uint64_t> allocs;
1081e09c44b6SAidan Dodds 
1082e09c44b6SAidan Dodds   // traverse allocation list
1083b9c1b51eSKate Stone   for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1084e09c44b6SAidan Dodds     // calculate offest to allocation pointer
1085f4786785SAidan Dodds     const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1086e09c44b6SAidan Dodds 
108780af0b9eSLuke Drummond     // Note: due to little endian layout, reading 32bits or 64bits into res
108880af0b9eSLuke Drummond     // will give the correct results.
108980af0b9eSLuke Drummond     uint64_t result = 0;
109080af0b9eSLuke Drummond     size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
109180af0b9eSLuke Drummond     if (read != target_ptr_size || !err.Success()) {
1092e09c44b6SAidan Dodds       if (log)
1093b9c1b51eSKate Stone         log->Printf(
1094b9c1b51eSKate Stone             "%s - Error while reading allocation list argument %" PRIu64,
1095b9c1b51eSKate Stone             __FUNCTION__, i);
1096b9c1b51eSKate Stone     } else {
109780af0b9eSLuke Drummond       allocs.push_back(result);
1098e09c44b6SAidan Dodds     }
1099e09c44b6SAidan Dodds   }
1100e09c44b6SAidan Dodds 
1101e09c44b6SAidan Dodds   // if there is an output allocation track it
110280af0b9eSLuke Drummond   if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
110380af0b9eSLuke Drummond     allocs.push_back(alloc_out);
1104e09c44b6SAidan Dodds   }
1105e09c44b6SAidan Dodds 
1106e09c44b6SAidan Dodds   // for all allocations we have found
1107b9c1b51eSKate Stone   for (const uint64_t alloc_addr : allocs) {
11085d057637SLuke Drummond     AllocationDetails *alloc = LookUpAllocation(alloc_addr);
11095d057637SLuke Drummond     if (!alloc)
11105d057637SLuke Drummond       alloc = CreateAllocation(alloc_addr);
11115d057637SLuke Drummond 
1112b9c1b51eSKate Stone     if (alloc) {
1113e09c44b6SAidan Dodds       // save the allocation address
1114b9c1b51eSKate Stone       if (alloc->address.isValid()) {
1115e09c44b6SAidan Dodds         // check the allocation address we already have matches
1116e09c44b6SAidan Dodds         assert(*alloc->address.get() == alloc_addr);
1117b9c1b51eSKate Stone       } else {
1118e09c44b6SAidan Dodds         alloc->address = alloc_addr;
1119e09c44b6SAidan Dodds       }
1120e09c44b6SAidan Dodds 
1121e09c44b6SAidan Dodds       // save the context
1122b9c1b51eSKate Stone       if (log) {
1123b9c1b51eSKate Stone         if (alloc->context.isValid() &&
1124b9c1b51eSKate Stone             *alloc->context.get() != addr_t(args[eRsContext]))
1125b9c1b51eSKate Stone           log->Printf("%s - Allocation used by multiple contexts",
1126b9c1b51eSKate Stone                       __FUNCTION__);
1127e09c44b6SAidan Dodds       }
1128f4786785SAidan Dodds       alloc->context = addr_t(args[eRsContext]);
1129e09c44b6SAidan Dodds     }
1130e09c44b6SAidan Dodds   }
1131e09c44b6SAidan Dodds 
1132e09c44b6SAidan Dodds   // make sure we track this script object
1133b9c1b51eSKate Stone   if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1134b9c1b51eSKate Stone           LookUpScript(addr_t(args[eRsScript]), true)) {
1135b9c1b51eSKate Stone     if (log) {
1136b9c1b51eSKate Stone       if (script->context.isValid() &&
1137b9c1b51eSKate Stone           *script->context.get() != addr_t(args[eRsContext]))
1138b3f7f69dSAidan Dodds         log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1139e09c44b6SAidan Dodds     }
1140f4786785SAidan Dodds     script->context = addr_t(args[eRsContext]);
1141e09c44b6SAidan Dodds   }
1142e09c44b6SAidan Dodds }
1143e09c44b6SAidan Dodds 
114480af0b9eSLuke Drummond void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1145b9c1b51eSKate Stone                                               ExecutionContext &context) {
11464640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11474640cde1SColin Riley 
1148b9c1b51eSKate Stone   enum {
1149f4786785SAidan Dodds     eRsContext,
1150f4786785SAidan Dodds     eRsScript,
1151f4786785SAidan Dodds     eRsId,
1152f4786785SAidan Dodds     eRsData,
1153f4786785SAidan Dodds     eRsLength,
1154f4786785SAidan Dodds   };
11554640cde1SColin Riley 
11561ee07253SSaleem Abdulrasool   std::array<ArgItem, 5> args{{
1157f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1158f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsScript
1159f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsId
1160f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsData
1161f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsLength
11621ee07253SSaleem Abdulrasool   }};
11634640cde1SColin Riley 
1164f4786785SAidan Dodds   bool success = GetArgs(context, &args[0], args.size());
1165b9c1b51eSKate Stone   if (!success) {
116682780287SAidan Dodds     if (log)
1167b3f7f69dSAidan Dodds       log->Printf("%s - error reading the function parameters.", __FUNCTION__);
116882780287SAidan Dodds     return;
116982780287SAidan Dodds   }
11704640cde1SColin Riley 
1171b9c1b51eSKate Stone   if (log) {
1172b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1173b9c1b51eSKate Stone                 ":%" PRIu64 "bytes.",
1174b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1175b9c1b51eSKate Stone                 uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1176f4786785SAidan Dodds                 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
11774640cde1SColin Riley 
1178f4786785SAidan Dodds     addr_t script_addr = addr_t(args[eRsScript]);
1179b9c1b51eSKate Stone     if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
11804640cde1SColin Riley       auto rsm = m_scriptMappings[script_addr];
1181b9c1b51eSKate Stone       if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1182f4786785SAidan Dodds         auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1183b9c1b51eSKate Stone         log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__,
1184b9c1b51eSKate Stone                     rsg.m_name.AsCString(),
1185f4786785SAidan Dodds                     rsm->m_module->GetFileSpec().GetFilename().AsCString());
11864640cde1SColin Riley       }
11874640cde1SColin Riley     }
11884640cde1SColin Riley   }
11894640cde1SColin Riley }
11904640cde1SColin Riley 
119180af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
119280af0b9eSLuke Drummond                                                 ExecutionContext &exe_ctx) {
11934640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11944640cde1SColin Riley 
1195b9c1b51eSKate Stone   enum { eRsContext, eRsAlloc, eRsForceZero };
11964640cde1SColin Riley 
11971ee07253SSaleem Abdulrasool   std::array<ArgItem, 3> args{{
1198f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1199f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1200f4786785SAidan Dodds       ArgItem{ArgItem::eBool, 0},    // eRsForceZero
12011ee07253SSaleem Abdulrasool   }};
12024640cde1SColin Riley 
120380af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
120480af0b9eSLuke Drummond   if (!success) {
120582780287SAidan Dodds     if (log)
1206b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters",
1207b9c1b51eSKate Stone                   __FUNCTION__);
120880af0b9eSLuke Drummond     return;
120982780287SAidan Dodds   }
12104640cde1SColin Riley 
12114640cde1SColin Riley   if (log)
1212b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1213b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1214f4786785SAidan Dodds                 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
121578f339d1SEwan Crawford 
12165d057637SLuke Drummond   AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
121778f339d1SEwan Crawford   if (alloc)
1218f4786785SAidan Dodds     alloc->context = uint64_t(args[eRsContext]);
12194640cde1SColin Riley }
12204640cde1SColin Riley 
122180af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
122280af0b9eSLuke Drummond                                                    ExecutionContext &exe_ctx) {
1223e69df382SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1224e69df382SEwan Crawford 
1225b9c1b51eSKate Stone   enum {
1226f4786785SAidan Dodds     eRsContext,
1227f4786785SAidan Dodds     eRsAlloc,
1228f4786785SAidan Dodds   };
1229e69df382SEwan Crawford 
12301ee07253SSaleem Abdulrasool   std::array<ArgItem, 2> args{{
1231f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1232f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
12331ee07253SSaleem Abdulrasool   }};
1234f4786785SAidan Dodds 
123580af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1236b9c1b51eSKate Stone   if (!success) {
1237e69df382SEwan Crawford     if (log)
1238b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1239b9c1b51eSKate Stone                   __FUNCTION__);
1240b3f7f69dSAidan Dodds     return;
1241e69df382SEwan Crawford   }
1242e69df382SEwan Crawford 
1243e69df382SEwan Crawford   if (log)
1244b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1245b9c1b51eSKate Stone                 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1246e69df382SEwan Crawford 
1247b9c1b51eSKate Stone   for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1248e69df382SEwan Crawford     auto &allocation_ap = *iter; // get the unique pointer
1249b9c1b51eSKate Stone     if (allocation_ap->address.isValid() &&
1250b9c1b51eSKate Stone         *allocation_ap->address.get() == addr_t(args[eRsAlloc])) {
1251e69df382SEwan Crawford       m_allocations.erase(iter);
1252e69df382SEwan Crawford       if (log)
1253b3f7f69dSAidan Dodds         log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1254e69df382SEwan Crawford       return;
1255e69df382SEwan Crawford     }
1256e69df382SEwan Crawford   }
1257e69df382SEwan Crawford 
1258e69df382SEwan Crawford   if (log)
1259b3f7f69dSAidan Dodds     log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1260e69df382SEwan Crawford }
1261e69df382SEwan Crawford 
126280af0b9eSLuke Drummond void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
126380af0b9eSLuke Drummond                                             ExecutionContext &exe_ctx) {
12644640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
12654640cde1SColin Riley 
126680af0b9eSLuke Drummond   Error err;
126780af0b9eSLuke Drummond   Process *process = exe_ctx.GetProcessPtr();
12684640cde1SColin Riley 
1269b9c1b51eSKate Stone   enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
12704640cde1SColin Riley 
1271b9c1b51eSKate Stone   std::array<ArgItem, 4> args{
1272b9c1b51eSKate Stone       {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
12731ee07253SSaleem Abdulrasool        ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
127480af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1275b9c1b51eSKate Stone   if (!success) {
127682780287SAidan Dodds     if (log)
1277b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1278b9c1b51eSKate Stone                   __FUNCTION__);
127982780287SAidan Dodds     return;
128082780287SAidan Dodds   }
128182780287SAidan Dodds 
128280af0b9eSLuke Drummond   std::string res_name;
128380af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
128480af0b9eSLuke Drummond   if (err.Fail()) {
12854640cde1SColin Riley     if (log)
128680af0b9eSLuke Drummond       log->Printf("%s - error reading res_name: %s.", __FUNCTION__,
128780af0b9eSLuke Drummond                   err.AsCString());
12884640cde1SColin Riley   }
12894640cde1SColin Riley 
129080af0b9eSLuke Drummond   std::string cache_dir;
129180af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
129280af0b9eSLuke Drummond   if (err.Fail()) {
12934640cde1SColin Riley     if (log)
129480af0b9eSLuke Drummond       log->Printf("%s - error reading cache_dir: %s.", __FUNCTION__,
129580af0b9eSLuke Drummond                   err.AsCString());
12964640cde1SColin Riley   }
12974640cde1SColin Riley 
12984640cde1SColin Riley   if (log)
1299b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1300b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
130180af0b9eSLuke Drummond                 uint64_t(args[eRsScript]), res_name.c_str(), cache_dir.c_str());
13024640cde1SColin Riley 
130380af0b9eSLuke Drummond   if (res_name.size() > 0) {
13044640cde1SColin Riley     StreamString strm;
130580af0b9eSLuke Drummond     strm.Printf("librs.%s.so", res_name.c_str());
13064640cde1SColin Riley 
1307f4786785SAidan Dodds     ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1308b9c1b51eSKate Stone     if (script) {
130978f339d1SEwan Crawford       script->type = ScriptDetails::eScriptC;
131080af0b9eSLuke Drummond       script->cache_dir = cache_dir;
131180af0b9eSLuke Drummond       script->res_name = res_name;
131280af0b9eSLuke Drummond       script->shared_lib = strm.GetData();
1313f4786785SAidan Dodds       script->context = addr_t(args[eRsContext]);
131478f339d1SEwan Crawford     }
13154640cde1SColin Riley 
13164640cde1SColin Riley     if (log)
1317b9c1b51eSKate Stone       log->Printf("%s - '%s' tagged with context 0x%" PRIx64
1318b9c1b51eSKate Stone                   " and script 0x%" PRIx64 ".",
1319b9c1b51eSKate Stone                   __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1320b9c1b51eSKate Stone                   uint64_t(args[eRsScript]));
1321b9c1b51eSKate Stone   } else if (log) {
1322b3f7f69dSAidan Dodds     log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
13234640cde1SColin Riley   }
13244640cde1SColin Riley }
13254640cde1SColin Riley 
1326b9c1b51eSKate Stone void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1327b9c1b51eSKate Stone                                            ModuleKind kind) {
13284640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
13294640cde1SColin Riley 
1330b9c1b51eSKate Stone   if (!module) {
13314640cde1SColin Riley     return;
13324640cde1SColin Riley   }
13334640cde1SColin Riley 
133482780287SAidan Dodds   Target &target = GetProcess()->GetTarget();
133580af0b9eSLuke Drummond   llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
133682780287SAidan Dodds 
133780af0b9eSLuke Drummond   if (machine != llvm::Triple::ArchType::x86 &&
133880af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::arm &&
133980af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::aarch64 &&
134080af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mipsel &&
134180af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mips64el &&
134280af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::x86_64) {
13434640cde1SColin Riley     if (log)
1344b3f7f69dSAidan Dodds       log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
13454640cde1SColin Riley     return;
13464640cde1SColin Riley   }
13474640cde1SColin Riley 
134880af0b9eSLuke Drummond   uint32_t target_ptr_size = target.GetArchitecture().GetAddressByteSize();
13494640cde1SColin Riley 
1350b9c1b51eSKate Stone   for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
13514640cde1SColin Riley     const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1352b9c1b51eSKate Stone     if (hook_defn->kind != kind) {
13534640cde1SColin Riley       continue;
13544640cde1SColin Riley     }
13554640cde1SColin Riley 
135680af0b9eSLuke Drummond     const char *symbol_name = (target_ptr_size == 4)
135780af0b9eSLuke Drummond                                   ? hook_defn->symbol_name_m32
1358b9c1b51eSKate Stone                                   : hook_defn->symbol_name_m64;
135982780287SAidan Dodds 
1360b9c1b51eSKate Stone     const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1361b9c1b51eSKate Stone         ConstString(symbol_name), eSymbolTypeCode);
1362b9c1b51eSKate Stone     if (!sym) {
1363b9c1b51eSKate Stone       if (log) {
1364b3f7f69dSAidan Dodds         log->Printf("%s - symbol '%s' related to the function %s not found",
1365b3f7f69dSAidan Dodds                     __FUNCTION__, symbol_name, hook_defn->name);
136682780287SAidan Dodds       }
136782780287SAidan Dodds       continue;
136882780287SAidan Dodds     }
13694640cde1SColin Riley 
1370358cf1eaSGreg Clayton     addr_t addr = sym->GetLoadAddress(&target);
1371b9c1b51eSKate Stone     if (addr == LLDB_INVALID_ADDRESS) {
13724640cde1SColin Riley       if (log)
1373b9c1b51eSKate Stone         log->Printf("%s - unable to resolve the address of hook function '%s' "
1374b9c1b51eSKate Stone                     "with symbol '%s'.",
1375b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, symbol_name);
13764640cde1SColin Riley       continue;
1377b9c1b51eSKate Stone     } else {
137882780287SAidan Dodds       if (log)
1379b3f7f69dSAidan Dodds         log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1380b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, addr);
138182780287SAidan Dodds     }
13824640cde1SColin Riley 
13834640cde1SColin Riley     RuntimeHookSP hook(new RuntimeHook());
13844640cde1SColin Riley     hook->address = addr;
13854640cde1SColin Riley     hook->defn = hook_defn;
13864640cde1SColin Riley     hook->bp_sp = target.CreateBreakpoint(addr, true, false);
13874640cde1SColin Riley     hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
13884640cde1SColin Riley     m_runtimeHooks[addr] = hook;
1389b9c1b51eSKate Stone     if (log) {
1390b9c1b51eSKate Stone       log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64
1391b9c1b51eSKate Stone                   " at 0x%" PRIx64 ".",
1392b9c1b51eSKate Stone                   __FUNCTION__, hook_defn->name,
1393b9c1b51eSKate Stone                   module->GetFileSpec().GetFilename().AsCString(),
1394b3f7f69dSAidan Dodds                   (uint64_t)hook_defn->version, (uint64_t)addr);
13954640cde1SColin Riley     }
13964640cde1SColin Riley   }
13974640cde1SColin Riley }
13984640cde1SColin Riley 
1399b9c1b51eSKate Stone void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
14004640cde1SColin Riley   if (!rsmodule_sp)
14014640cde1SColin Riley     return;
14024640cde1SColin Riley 
14034640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14044640cde1SColin Riley 
14054640cde1SColin Riley   const ModuleSP module = rsmodule_sp->m_module;
14064640cde1SColin Riley   const FileSpec &file = module->GetPlatformFileSpec();
14074640cde1SColin Riley 
140878f339d1SEwan Crawford   // Iterate over all of the scripts that we currently know of.
140978f339d1SEwan Crawford   // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
1410b9c1b51eSKate Stone   for (const auto &rs_script : m_scripts) {
141178f339d1SEwan Crawford     // Extract the expected .so file path for this script.
141280af0b9eSLuke Drummond     std::string shared_lib;
141380af0b9eSLuke Drummond     if (!rs_script->shared_lib.get(shared_lib))
141478f339d1SEwan Crawford       continue;
141578f339d1SEwan Crawford 
141678f339d1SEwan Crawford     // Only proceed if the module that has loaded corresponds to this script.
141780af0b9eSLuke Drummond     if (file.GetFilename() != ConstString(shared_lib.c_str()))
141878f339d1SEwan Crawford       continue;
141978f339d1SEwan Crawford 
142078f339d1SEwan Crawford     // Obtain the script address which we use as a key.
142178f339d1SEwan Crawford     lldb::addr_t script;
142278f339d1SEwan Crawford     if (!rs_script->script.get(script))
142378f339d1SEwan Crawford       continue;
142478f339d1SEwan Crawford 
142578f339d1SEwan Crawford     // If we have a script mapping for the current script.
1426b9c1b51eSKate Stone     if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
142778f339d1SEwan Crawford       // if the module we have stored is different to the one we just received.
1428b9c1b51eSKate Stone       if (m_scriptMappings[script] != rsmodule_sp) {
14294640cde1SColin Riley         if (log)
1430b9c1b51eSKate Stone           log->Printf(
1431b9c1b51eSKate Stone               "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1432b9c1b51eSKate Stone               __FUNCTION__, (uint64_t)script,
1433b9c1b51eSKate Stone               rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
14344640cde1SColin Riley       }
14354640cde1SColin Riley     }
143678f339d1SEwan Crawford     // We don't have a script mapping for the current script.
1437b9c1b51eSKate Stone     else {
143878f339d1SEwan Crawford       // Obtain the script resource name.
143980af0b9eSLuke Drummond       std::string res_name;
144080af0b9eSLuke Drummond       if (rs_script->res_name.get(res_name))
144178f339d1SEwan Crawford         // Set the modules resource name.
144280af0b9eSLuke Drummond         rsmodule_sp->m_resname = res_name;
144378f339d1SEwan Crawford       // Add Script/Module pair to map.
144478f339d1SEwan Crawford       m_scriptMappings[script] = rsmodule_sp;
14454640cde1SColin Riley       if (log)
1446b9c1b51eSKate Stone         log->Printf(
1447b9c1b51eSKate Stone             "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1448b9c1b51eSKate Stone             __FUNCTION__, (uint64_t)script,
1449b9c1b51eSKate Stone             rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
14504640cde1SColin Riley     }
14514640cde1SColin Riley   }
14524640cde1SColin Riley }
14534640cde1SColin Riley 
1454b9c1b51eSKate Stone // Uses the Target API to evaluate the expression passed as a parameter to the
145580af0b9eSLuke Drummond // function The result of that expression is returned an unsigned 64 bit int,
145680af0b9eSLuke Drummond // via the result* parameter. Function returns true on success, and false on
145780af0b9eSLuke Drummond // failure
145880af0b9eSLuke Drummond bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1459b9c1b51eSKate Stone                                            StackFrame *frame_ptr,
1460b9c1b51eSKate Stone                                            uint64_t *result) {
146115f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
146215f2bd95SEwan Crawford   if (log)
146380af0b9eSLuke Drummond     log->Printf("%s(%s)", __FUNCTION__, expr);
146415f2bd95SEwan Crawford 
146515f2bd95SEwan Crawford   ValueObjectSP expr_result;
14668433fdbeSAidan Dodds   EvaluateExpressionOptions options;
14678433fdbeSAidan Dodds   options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
146815f2bd95SEwan Crawford   // Perform the actual expression evaluation
146980af0b9eSLuke Drummond   auto &target = GetProcess()->GetTarget();
147080af0b9eSLuke Drummond   target.EvaluateExpression(expr, frame_ptr, expr_result, options);
147115f2bd95SEwan Crawford 
1472b9c1b51eSKate Stone   if (!expr_result) {
147315f2bd95SEwan Crawford     if (log)
1474b3f7f69dSAidan Dodds       log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
147515f2bd95SEwan Crawford     return false;
147615f2bd95SEwan Crawford   }
147715f2bd95SEwan Crawford 
147815f2bd95SEwan Crawford   // The result of the expression is invalid
1479b9c1b51eSKate Stone   if (!expr_result->GetError().Success()) {
148015f2bd95SEwan Crawford     Error err = expr_result->GetError();
148180af0b9eSLuke Drummond     // Expression returned is void, so this is actually a success
148280af0b9eSLuke Drummond     if (err.GetError() == UserExpression::kNoResult) {
148315f2bd95SEwan Crawford       if (log)
1484b3f7f69dSAidan Dodds         log->Printf("%s - expression returned void.", __FUNCTION__);
148515f2bd95SEwan Crawford 
148615f2bd95SEwan Crawford       result = nullptr;
148715f2bd95SEwan Crawford       return true;
148815f2bd95SEwan Crawford     }
148915f2bd95SEwan Crawford 
149015f2bd95SEwan Crawford     if (log)
1491b3f7f69dSAidan Dodds       log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1492b3f7f69dSAidan Dodds                   err.AsCString());
149315f2bd95SEwan Crawford     return false;
149415f2bd95SEwan Crawford   }
149515f2bd95SEwan Crawford 
149615f2bd95SEwan Crawford   bool success = false;
149780af0b9eSLuke Drummond   // We only read the result as an uint32_t.
149880af0b9eSLuke Drummond   *result = expr_result->GetValueAsUnsigned(0, &success);
149915f2bd95SEwan Crawford 
1500b9c1b51eSKate Stone   if (!success) {
150115f2bd95SEwan Crawford     if (log)
1502b9c1b51eSKate Stone       log->Printf("%s - couldn't convert expression result to uint32_t",
1503b9c1b51eSKate Stone                   __FUNCTION__);
150415f2bd95SEwan Crawford     return false;
150515f2bd95SEwan Crawford   }
150615f2bd95SEwan Crawford 
150715f2bd95SEwan Crawford   return true;
150815f2bd95SEwan Crawford }
150915f2bd95SEwan Crawford 
1510b9c1b51eSKate Stone namespace {
1511836d9651SEwan Crawford // Used to index expression format strings
1512b9c1b51eSKate Stone enum ExpressionStrings {
1513836d9651SEwan Crawford   eExprGetOffsetPtr = 0,
1514836d9651SEwan Crawford   eExprAllocGetType,
1515836d9651SEwan Crawford   eExprTypeDimX,
1516836d9651SEwan Crawford   eExprTypeDimY,
1517836d9651SEwan Crawford   eExprTypeDimZ,
1518836d9651SEwan Crawford   eExprTypeElemPtr,
1519836d9651SEwan Crawford   eExprElementType,
1520836d9651SEwan Crawford   eExprElementKind,
1521836d9651SEwan Crawford   eExprElementVec,
1522836d9651SEwan Crawford   eExprElementFieldCount,
1523836d9651SEwan Crawford   eExprSubelementsId,
1524836d9651SEwan Crawford   eExprSubelementsName,
1525ea0636b5SEwan Crawford   eExprSubelementsArrSize,
1526ea0636b5SEwan Crawford 
152780af0b9eSLuke Drummond   _eExprLast // keep at the end, implicit size of the array runtime_expressions
1528836d9651SEwan Crawford };
152915f2bd95SEwan Crawford 
1530ea0636b5SEwan Crawford // max length of an expanded expression
1531ea0636b5SEwan Crawford const int jit_max_expr_size = 512;
1532ea0636b5SEwan Crawford 
1533ea0636b5SEwan Crawford // Retrieve the string to JIT for the given expression
1534b9c1b51eSKate Stone const char *JITTemplate(ExpressionStrings e) {
1535ea0636b5SEwan Crawford   // Format strings containing the expressions we may need to evaluate.
153680af0b9eSLuke Drummond   static std::array<const char *, _eExprLast> runtime_expressions = {
1537b9c1b51eSKate Stone       {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1538b9c1b51eSKate Stone        "(int*)_"
1539b9c1b51eSKate Stone        "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1540b9c1b51eSKate Stone        "CubemapFace"
1541577570b4SAidan Dodds        "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)",
154215f2bd95SEwan Crawford 
154315f2bd95SEwan Crawford        // Type* rsaAllocationGetType(Context*, Allocation*)
1544577570b4SAidan Dodds        "(void*)rsaAllocationGetType(0x%" PRIx64 ", 0x%" PRIx64 ")",
154515f2bd95SEwan Crawford 
154680af0b9eSLuke Drummond        // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
154780af0b9eSLuke Drummond        // data in the following way mHal.state.dimX; mHal.state.dimY;
154880af0b9eSLuke Drummond        // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement; into
154980af0b9eSLuke Drummond        // typeData Need to specify 32 or 64 bit for uint_t since this differs
155080af0b9eSLuke Drummond        // between devices
1551b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1552b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[0]", // X dim
1553b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1554b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[1]", // Y dim
1555b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1556b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[2]", // Z dim
1557b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1558b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[5]", // Element ptr
155915f2bd95SEwan Crawford 
156015f2bd95SEwan Crawford        // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1561b9c1b51eSKate Stone        // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1562b9c1b51eSKate Stone        // elemData
1563b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1564b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[0]", // Type
1565b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1566b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[1]", // Kind
1567b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1568b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[3]", // Vector Size
1569b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1570b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[4]", // Field Count
15718b244e21SEwan Crawford 
1572b9c1b51eSKate Stone        // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
157380af0b9eSLuke Drummond        // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1574b9c1b51eSKate Stone        // Needed for Allocations of structs to gather details about
157580af0b9eSLuke Drummond        // fields/Subelements Element* of field
1576b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1577b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1578b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1579b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]",
15808b244e21SEwan Crawford 
1581577570b4SAidan Dodds        // Name of field
1582b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1583b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1584b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1585b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]",
15868b244e21SEwan Crawford 
1587577570b4SAidan Dodds        // Array size of field
1588b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1589b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1590b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1591b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}};
1592ea0636b5SEwan Crawford 
159380af0b9eSLuke Drummond   return runtime_expressions[e];
1594ea0636b5SEwan Crawford }
1595ea0636b5SEwan Crawford } // end of the anonymous namespace
1596ea0636b5SEwan Crawford 
159780af0b9eSLuke Drummond // JITs the RS runtime for the internal data pointer of an allocation. Is passed
159880af0b9eSLuke Drummond // x,y,z coordinates for the pointer to a specific element. Then sets the
159980af0b9eSLuke Drummond // data_ptr member in Allocation with the result. Returns true on success, false
160080af0b9eSLuke Drummond // otherwise
160180af0b9eSLuke Drummond bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1602b9c1b51eSKate Stone                                          StackFrame *frame_ptr, uint32_t x,
1603b9c1b51eSKate Stone                                          uint32_t y, uint32_t z) {
160415f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
160515f2bd95SEwan Crawford 
160680af0b9eSLuke Drummond   if (!alloc->address.isValid()) {
160715f2bd95SEwan Crawford     if (log)
1608b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
160915f2bd95SEwan Crawford     return false;
161015f2bd95SEwan Crawford   }
161115f2bd95SEwan Crawford 
161280af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
161380af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
161415f2bd95SEwan Crawford 
161580af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
161680af0b9eSLuke Drummond                          *alloc->address.get(), x, y, z);
161780af0b9eSLuke Drummond   if (written < 0) {
161815f2bd95SEwan Crawford     if (log)
1619b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
162015f2bd95SEwan Crawford     return false;
162180af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
162215f2bd95SEwan Crawford     if (log)
1623b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
162415f2bd95SEwan Crawford     return false;
162515f2bd95SEwan Crawford   }
162615f2bd95SEwan Crawford 
162715f2bd95SEwan Crawford   uint64_t result = 0;
162880af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
162915f2bd95SEwan Crawford     return false;
163015f2bd95SEwan Crawford 
163180af0b9eSLuke Drummond   addr_t data_ptr = static_cast<lldb::addr_t>(result);
163280af0b9eSLuke Drummond   alloc->data_ptr = data_ptr;
163315f2bd95SEwan Crawford 
163415f2bd95SEwan Crawford   return true;
163515f2bd95SEwan Crawford }
163615f2bd95SEwan Crawford 
163715f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
163880af0b9eSLuke Drummond // Then sets the type_ptr member in Allocation with the result. Returns true on
163980af0b9eSLuke Drummond // success, false otherwise
164080af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1641b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
164215f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
164315f2bd95SEwan Crawford 
164480af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->context.isValid()) {
164515f2bd95SEwan Crawford     if (log)
1646b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
164715f2bd95SEwan Crawford     return false;
164815f2bd95SEwan Crawford   }
164915f2bd95SEwan Crawford 
165080af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprAllocGetType);
165180af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
165215f2bd95SEwan Crawford 
165380af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
165480af0b9eSLuke Drummond                          *alloc->context.get(), *alloc->address.get());
165580af0b9eSLuke Drummond   if (written < 0) {
165615f2bd95SEwan Crawford     if (log)
1657b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
165815f2bd95SEwan Crawford     return false;
165980af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
166015f2bd95SEwan Crawford     if (log)
1661b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
166215f2bd95SEwan Crawford     return false;
166315f2bd95SEwan Crawford   }
166415f2bd95SEwan Crawford 
166515f2bd95SEwan Crawford   uint64_t result = 0;
166680af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
166715f2bd95SEwan Crawford     return false;
166815f2bd95SEwan Crawford 
166915f2bd95SEwan Crawford   addr_t type_ptr = static_cast<lldb::addr_t>(result);
167080af0b9eSLuke Drummond   alloc->type_ptr = type_ptr;
167115f2bd95SEwan Crawford 
167215f2bd95SEwan Crawford   return true;
167315f2bd95SEwan Crawford }
167415f2bd95SEwan Crawford 
1675b9c1b51eSKate Stone // JITs the RS runtime for information about the dimensions and type of an
167680af0b9eSLuke Drummond // allocation Then sets dimension and element_ptr members in Allocation with the
167780af0b9eSLuke Drummond // result. Returns true on success, false otherwise
167880af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1679b9c1b51eSKate Stone                                         StackFrame *frame_ptr) {
168015f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
168115f2bd95SEwan Crawford 
168280af0b9eSLuke Drummond   if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
168315f2bd95SEwan Crawford     if (log)
1684b3f7f69dSAidan Dodds       log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
168515f2bd95SEwan Crawford     return false;
168615f2bd95SEwan Crawford   }
168715f2bd95SEwan Crawford 
168815f2bd95SEwan Crawford   // Expression is different depending on if device is 32 or 64 bit
168980af0b9eSLuke Drummond   uint32_t target_ptr_size =
1690b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
169180af0b9eSLuke Drummond   const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
169215f2bd95SEwan Crawford 
169315f2bd95SEwan Crawford   // We want 4 elements from packed data
1694b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
1695b9c1b51eSKate Stone   assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) &&
1696b9c1b51eSKate Stone          "Invalid number of expressions");
169715f2bd95SEwan Crawford 
169880af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
169915f2bd95SEwan Crawford   uint64_t results[num_exprs];
170015f2bd95SEwan Crawford 
1701b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; ++i) {
170280af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
170380af0b9eSLuke Drummond     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, bits,
170480af0b9eSLuke Drummond                            *alloc->context.get(), *alloc->type_ptr.get());
170580af0b9eSLuke Drummond     if (written < 0) {
170615f2bd95SEwan Crawford       if (log)
1707b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
170815f2bd95SEwan Crawford       return false;
170980af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
171015f2bd95SEwan Crawford       if (log)
1711b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
171215f2bd95SEwan Crawford       return false;
171315f2bd95SEwan Crawford     }
171415f2bd95SEwan Crawford 
171515f2bd95SEwan Crawford     // Perform expression evaluation
171680af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
171715f2bd95SEwan Crawford       return false;
171815f2bd95SEwan Crawford   }
171915f2bd95SEwan Crawford 
172015f2bd95SEwan Crawford   // Assign results to allocation members
172115f2bd95SEwan Crawford   AllocationDetails::Dimension dims;
172215f2bd95SEwan Crawford   dims.dim_1 = static_cast<uint32_t>(results[0]);
172315f2bd95SEwan Crawford   dims.dim_2 = static_cast<uint32_t>(results[1]);
172415f2bd95SEwan Crawford   dims.dim_3 = static_cast<uint32_t>(results[2]);
172580af0b9eSLuke Drummond   alloc->dimension = dims;
172615f2bd95SEwan Crawford 
172780af0b9eSLuke Drummond   addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
172880af0b9eSLuke Drummond   alloc->element.element_ptr = element_ptr;
172915f2bd95SEwan Crawford 
173015f2bd95SEwan Crawford   if (log)
1731b9c1b51eSKate Stone     log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
1732b9c1b51eSKate Stone                 ") Element*: 0x%" PRIx64 ".",
173380af0b9eSLuke Drummond                 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
173415f2bd95SEwan Crawford 
173515f2bd95SEwan Crawford   return true;
173615f2bd95SEwan Crawford }
173715f2bd95SEwan Crawford 
173880af0b9eSLuke Drummond // JITs the RS runtime for information about the Element of an allocation Then
173980af0b9eSLuke Drummond // sets type, type_vec_size, field_count and type_kind members in Element with
174080af0b9eSLuke Drummond // the result. Returns true on success, false otherwise
1741b9c1b51eSKate Stone bool RenderScriptRuntime::JITElementPacked(Element &elem,
1742b9c1b51eSKate Stone                                            const lldb::addr_t context,
1743b9c1b51eSKate Stone                                            StackFrame *frame_ptr) {
174415f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
174515f2bd95SEwan Crawford 
1746b9c1b51eSKate Stone   if (!elem.element_ptr.isValid()) {
174715f2bd95SEwan Crawford     if (log)
1748b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
174915f2bd95SEwan Crawford     return false;
175015f2bd95SEwan Crawford   }
175115f2bd95SEwan Crawford 
17528b244e21SEwan Crawford   // We want 4 elements from packed data
1753b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
1754b9c1b51eSKate Stone   assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) &&
1755b9c1b51eSKate Stone          "Invalid number of expressions");
175615f2bd95SEwan Crawford 
175780af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
175815f2bd95SEwan Crawford   uint64_t results[num_exprs];
175915f2bd95SEwan Crawford 
1760b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; i++) {
176180af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
176280af0b9eSLuke Drummond     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
176380af0b9eSLuke Drummond                            *elem.element_ptr.get());
176480af0b9eSLuke Drummond     if (written < 0) {
176515f2bd95SEwan Crawford       if (log)
1766b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
176715f2bd95SEwan Crawford       return false;
176880af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
176915f2bd95SEwan Crawford       if (log)
1770b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
177115f2bd95SEwan Crawford       return false;
177215f2bd95SEwan Crawford     }
177315f2bd95SEwan Crawford 
177415f2bd95SEwan Crawford     // Perform expression evaluation
177580af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
177615f2bd95SEwan Crawford       return false;
177715f2bd95SEwan Crawford   }
177815f2bd95SEwan Crawford 
177915f2bd95SEwan Crawford   // Assign results to allocation members
17808b244e21SEwan Crawford   elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
1781b9c1b51eSKate Stone   elem.type_kind =
1782b9c1b51eSKate Stone       static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
17838b244e21SEwan Crawford   elem.type_vec_size = static_cast<uint32_t>(results[2]);
17848b244e21SEwan Crawford   elem.field_count = static_cast<uint32_t>(results[3]);
178515f2bd95SEwan Crawford 
178615f2bd95SEwan Crawford   if (log)
1787b9c1b51eSKate Stone     log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32
1788b9c1b51eSKate Stone                 ", vector size %" PRIu32 ", field count %" PRIu32,
1789b9c1b51eSKate Stone                 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
1790b9c1b51eSKate Stone                 *elem.type_vec_size.get(), *elem.field_count.get());
17918b244e21SEwan Crawford 
1792b9c1b51eSKate Stone   // If this Element has subelements then JIT rsaElementGetSubElements() for
1793b9c1b51eSKate Stone   // details about its fields
17948b244e21SEwan Crawford   if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
17958b244e21SEwan Crawford     return false;
17968b244e21SEwan Crawford 
17978b244e21SEwan Crawford   return true;
17988b244e21SEwan Crawford }
17998b244e21SEwan Crawford 
1800b9c1b51eSKate Stone // JITs the RS runtime for information about the subelements/fields of a struct
180180af0b9eSLuke Drummond // allocation This is necessary for infering the struct type so we can pretty
180280af0b9eSLuke Drummond // print the allocation's contents. Returns true on success, false otherwise
1803b9c1b51eSKate Stone bool RenderScriptRuntime::JITSubelements(Element &elem,
1804b9c1b51eSKate Stone                                          const lldb::addr_t context,
1805b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
18068b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
18078b244e21SEwan Crawford 
1808b9c1b51eSKate Stone   if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
18098b244e21SEwan Crawford     if (log)
1810b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
18118b244e21SEwan Crawford     return false;
18128b244e21SEwan Crawford   }
18138b244e21SEwan Crawford 
18148b244e21SEwan Crawford   const short num_exprs = 3;
1815b9c1b51eSKate Stone   assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) &&
1816b9c1b51eSKate Stone          "Invalid number of expressions");
18178b244e21SEwan Crawford 
1818ea0636b5SEwan Crawford   char expr_buffer[jit_max_expr_size];
18198b244e21SEwan Crawford   uint64_t results;
18208b244e21SEwan Crawford 
18218b244e21SEwan Crawford   // Iterate over struct fields.
18228b244e21SEwan Crawford   const uint32_t field_count = *elem.field_count.get();
1823b9c1b51eSKate Stone   for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
18248b244e21SEwan Crawford     Element child;
1825b9c1b51eSKate Stone     for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
182680af0b9eSLuke Drummond       const char *fmt_str =
1827b9c1b51eSKate Stone           JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
182880af0b9eSLuke Drummond       int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
182980af0b9eSLuke Drummond                              field_count, field_count, field_count, context,
183080af0b9eSLuke Drummond                              *elem.element_ptr.get(), field_count, field_index);
183180af0b9eSLuke Drummond       if (written < 0) {
18328b244e21SEwan Crawford         if (log)
1833b3f7f69dSAidan Dodds           log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
18348b244e21SEwan Crawford         return false;
183580af0b9eSLuke Drummond       } else if (written >= jit_max_expr_size) {
18368b244e21SEwan Crawford         if (log)
1837b3f7f69dSAidan Dodds           log->Printf("%s - expression too long.", __FUNCTION__);
18388b244e21SEwan Crawford         return false;
18398b244e21SEwan Crawford       }
18408b244e21SEwan Crawford 
18418b244e21SEwan Crawford       // Perform expression evaluation
18428b244e21SEwan Crawford       if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
18438b244e21SEwan Crawford         return false;
18448b244e21SEwan Crawford 
18458b244e21SEwan Crawford       if (log)
1846b3f7f69dSAidan Dodds         log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
18478b244e21SEwan Crawford 
1848b9c1b51eSKate Stone       switch (expr_index) {
18498b244e21SEwan Crawford       case 0: // Element* of child
18508b244e21SEwan Crawford         child.element_ptr = static_cast<addr_t>(results);
18518b244e21SEwan Crawford         break;
18528b244e21SEwan Crawford       case 1: // Name of child
18538b244e21SEwan Crawford       {
18548b244e21SEwan Crawford         lldb::addr_t address = static_cast<addr_t>(results);
18558b244e21SEwan Crawford         Error err;
18568b244e21SEwan Crawford         std::string name;
18578b244e21SEwan Crawford         GetProcess()->ReadCStringFromMemory(address, name, err);
18588b244e21SEwan Crawford         if (!err.Fail())
18598b244e21SEwan Crawford           child.type_name = ConstString(name);
1860b9c1b51eSKate Stone         else {
18618b244e21SEwan Crawford           if (log)
1862b9c1b51eSKate Stone             log->Printf("%s - warning: Couldn't read field name.",
1863b9c1b51eSKate Stone                         __FUNCTION__);
18648b244e21SEwan Crawford         }
18658b244e21SEwan Crawford         break;
18668b244e21SEwan Crawford       }
18678b244e21SEwan Crawford       case 2: // Array size of child
18688b244e21SEwan Crawford         child.array_size = static_cast<uint32_t>(results);
18698b244e21SEwan Crawford         break;
18708b244e21SEwan Crawford       }
18718b244e21SEwan Crawford     }
18728b244e21SEwan Crawford 
18738b244e21SEwan Crawford     // We need to recursively JIT each Element field of the struct since
18748b244e21SEwan Crawford     // structs can be nested inside structs.
18758b244e21SEwan Crawford     if (!JITElementPacked(child, context, frame_ptr))
18768b244e21SEwan Crawford       return false;
18778b244e21SEwan Crawford     elem.children.push_back(child);
18788b244e21SEwan Crawford   }
18798b244e21SEwan Crawford 
1880b9c1b51eSKate Stone   // Try to infer the name of the struct type so we can pretty print the
1881b9c1b51eSKate Stone   // allocation contents.
18828b244e21SEwan Crawford   FindStructTypeName(elem, frame_ptr);
188315f2bd95SEwan Crawford 
188415f2bd95SEwan Crawford   return true;
188515f2bd95SEwan Crawford }
188615f2bd95SEwan Crawford 
1887a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
1888b9c1b51eSKate Stone // The `elem_size` parameter represents the size of a single element, including
188980af0b9eSLuke Drummond // padding. Which is needed as an offset from the last element pointer. Using
189080af0b9eSLuke Drummond // this offset minus the starting address we can calculate the size of the
189180af0b9eSLuke Drummond // allocation. Returns true on success, false otherwise
189280af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
1893b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
1894a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1895a0f08674SEwan Crawford 
189680af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
189780af0b9eSLuke Drummond       !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
1898a0f08674SEwan Crawford     if (log)
1899b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1900a0f08674SEwan Crawford     return false;
1901a0f08674SEwan Crawford   }
1902a0f08674SEwan Crawford 
1903a0f08674SEwan Crawford   // Find dimensions
190480af0b9eSLuke Drummond   uint32_t dim_x = alloc->dimension.get()->dim_1;
190580af0b9eSLuke Drummond   uint32_t dim_y = alloc->dimension.get()->dim_2;
190680af0b9eSLuke Drummond   uint32_t dim_z = alloc->dimension.get()->dim_3;
1907a0f08674SEwan Crawford 
1908b9c1b51eSKate Stone   // Our plan of jitting the last element address doesn't seem to work for
190980af0b9eSLuke Drummond   // struct Allocations` Instead try to infer the size ourselves without any
191080af0b9eSLuke Drummond   // inter element padding.
191180af0b9eSLuke Drummond   if (alloc->element.children.size() > 0) {
1912b9c1b51eSKate Stone     if (dim_x == 0)
1913b9c1b51eSKate Stone       dim_x = 1;
1914b9c1b51eSKate Stone     if (dim_y == 0)
1915b9c1b51eSKate Stone       dim_y = 1;
1916b9c1b51eSKate Stone     if (dim_z == 0)
1917b9c1b51eSKate Stone       dim_z = 1;
19188b244e21SEwan Crawford 
191980af0b9eSLuke Drummond     alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
19208b244e21SEwan Crawford 
19218b244e21SEwan Crawford     if (log)
1922b9c1b51eSKate Stone       log->Printf("%s - inferred size of struct allocation %" PRIu32 ".",
192380af0b9eSLuke Drummond                   __FUNCTION__, *alloc->size.get());
19248b244e21SEwan Crawford     return true;
19258b244e21SEwan Crawford   }
19268b244e21SEwan Crawford 
192780af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
192880af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
19298b244e21SEwan Crawford 
1930a0f08674SEwan Crawford   // Calculate last element
1931a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 0 : dim_x - 1;
1932a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 0 : dim_y - 1;
1933a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 0 : dim_z - 1;
1934a0f08674SEwan Crawford 
193580af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
193680af0b9eSLuke Drummond                          *alloc->address.get(), dim_x, dim_y, dim_z);
193780af0b9eSLuke Drummond   if (written < 0) {
1938a0f08674SEwan Crawford     if (log)
1939b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1940a0f08674SEwan Crawford     return false;
194180af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
1942a0f08674SEwan Crawford     if (log)
1943b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
1944a0f08674SEwan Crawford     return false;
1945a0f08674SEwan Crawford   }
1946a0f08674SEwan Crawford 
1947a0f08674SEwan Crawford   uint64_t result = 0;
194880af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1949a0f08674SEwan Crawford     return false;
1950a0f08674SEwan Crawford 
1951a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1952a0f08674SEwan Crawford   // Find pointer to last element and add on size of an element
195380af0b9eSLuke Drummond   alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
195480af0b9eSLuke Drummond                 *alloc->element.datum_size.get();
1955a0f08674SEwan Crawford 
1956a0f08674SEwan Crawford   return true;
1957a0f08674SEwan Crawford }
1958a0f08674SEwan Crawford 
1959b9c1b51eSKate Stone // JITs the RS runtime for information about the stride between rows in the
196080af0b9eSLuke Drummond // allocation. This is done to detect padding, since allocated memory is 16-byte
196180af0b9eSLuke Drummond // aligned.
1962a0f08674SEwan Crawford // Returns true on success, false otherwise
196380af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
1964b9c1b51eSKate Stone                                               StackFrame *frame_ptr) {
1965a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1966a0f08674SEwan Crawford 
196780af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
1968a0f08674SEwan Crawford     if (log)
1969b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1970a0f08674SEwan Crawford     return false;
1971a0f08674SEwan Crawford   }
1972a0f08674SEwan Crawford 
197380af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
197480af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
1975a0f08674SEwan Crawford 
197680af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
197780af0b9eSLuke Drummond                          *alloc->address.get(), 0, 1, 0);
197880af0b9eSLuke Drummond   if (written < 0) {
1979a0f08674SEwan Crawford     if (log)
1980b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1981a0f08674SEwan Crawford     return false;
198280af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
1983a0f08674SEwan Crawford     if (log)
1984b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
1985a0f08674SEwan Crawford     return false;
1986a0f08674SEwan Crawford   }
1987a0f08674SEwan Crawford 
1988a0f08674SEwan Crawford   uint64_t result = 0;
198980af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1990a0f08674SEwan Crawford     return false;
1991a0f08674SEwan Crawford 
1992a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
199380af0b9eSLuke Drummond   alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
1994a0f08674SEwan Crawford 
1995a0f08674SEwan Crawford   return true;
1996a0f08674SEwan Crawford }
1997a0f08674SEwan Crawford 
199815f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
199980af0b9eSLuke Drummond bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2000b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
200115f2bd95SEwan Crawford   // GetOffsetPointer()
200280af0b9eSLuke Drummond   if (!JITDataPointer(alloc, frame_ptr))
200315f2bd95SEwan Crawford     return false;
200415f2bd95SEwan Crawford 
200515f2bd95SEwan Crawford   // rsaAllocationGetType()
200680af0b9eSLuke Drummond   if (!JITTypePointer(alloc, frame_ptr))
200715f2bd95SEwan Crawford     return false;
200815f2bd95SEwan Crawford 
200915f2bd95SEwan Crawford   // rsaTypeGetNativeData()
201080af0b9eSLuke Drummond   if (!JITTypePacked(alloc, frame_ptr))
201115f2bd95SEwan Crawford     return false;
201215f2bd95SEwan Crawford 
201315f2bd95SEwan Crawford   // rsaElementGetNativeData()
201480af0b9eSLuke Drummond   if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
201515f2bd95SEwan Crawford     return false;
201615f2bd95SEwan Crawford 
20178b244e21SEwan Crawford   // Sets the datum_size member in Element
201880af0b9eSLuke Drummond   SetElementSize(alloc->element);
20198b244e21SEwan Crawford 
202055232f09SEwan Crawford   // Use GetOffsetPointer() to infer size of the allocation
202180af0b9eSLuke Drummond   if (!JITAllocationSize(alloc, frame_ptr))
202255232f09SEwan Crawford     return false;
202355232f09SEwan Crawford 
202455232f09SEwan Crawford   return true;
202555232f09SEwan Crawford }
202655232f09SEwan Crawford 
2027b9c1b51eSKate Stone // Function attempts to set the type_name member of the paramaterised Element
2028b9c1b51eSKate Stone // object.
20298b244e21SEwan Crawford // This string should be the name of the struct type the Element represents.
20308b244e21SEwan Crawford // We need this string for pretty printing the Element to users.
2031b9c1b51eSKate Stone void RenderScriptRuntime::FindStructTypeName(Element &elem,
2032b9c1b51eSKate Stone                                              StackFrame *frame_ptr) {
20338b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
20348b244e21SEwan Crawford 
20358b244e21SEwan Crawford   if (!elem.type_name.IsEmpty()) // Name already set
20368b244e21SEwan Crawford     return;
20378b244e21SEwan Crawford   else
2038b9c1b51eSKate Stone     elem.type_name = Element::GetFallbackStructName(); // Default type name if
2039b9c1b51eSKate Stone                                                        // we don't succeed
20408b244e21SEwan Crawford 
20418b244e21SEwan Crawford   // Find all the global variables from the script rs modules
204280af0b9eSLuke Drummond   VariableList var_list;
20438b244e21SEwan Crawford   for (auto module_sp : m_rsmodules)
204495eae423SZachary Turner     module_sp->m_module->FindGlobalVariables(
204580af0b9eSLuke Drummond         RegularExpression(llvm::StringRef(".")), true, UINT32_MAX, var_list);
20468b244e21SEwan Crawford 
2047b9c1b51eSKate Stone   // Iterate over all the global variables looking for one with a matching type
2048b9c1b51eSKate Stone   // to the Element.
2049b9c1b51eSKate Stone   // We make the assumption a match exists since there needs to be a global
205080af0b9eSLuke Drummond   // variable to reflect the struct type back into java host code.
205180af0b9eSLuke Drummond   for (uint32_t i = 0; i < var_list.GetSize(); ++i) {
205280af0b9eSLuke Drummond     const VariableSP var_sp(var_list.GetVariableAtIndex(i));
20538b244e21SEwan Crawford     if (!var_sp)
20548b244e21SEwan Crawford       continue;
20558b244e21SEwan Crawford 
20568b244e21SEwan Crawford     ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
20578b244e21SEwan Crawford     if (!valobj_sp)
20588b244e21SEwan Crawford       continue;
20598b244e21SEwan Crawford 
20608b244e21SEwan Crawford     // Find the number of variable fields.
2061b9c1b51eSKate Stone     // If it has no fields, or more fields than our Element, then it can't be
2062b9c1b51eSKate Stone     // the struct we're looking for.
2063b9c1b51eSKate Stone     // Don't check for equality since RS can add extra struct members for
2064b9c1b51eSKate Stone     // padding.
20658b244e21SEwan Crawford     size_t num_children = valobj_sp->GetNumChildren();
20668b244e21SEwan Crawford     if (num_children > elem.children.size() || num_children == 0)
20678b244e21SEwan Crawford       continue;
20688b244e21SEwan Crawford 
20698b244e21SEwan Crawford     // Iterate over children looking for members with matching field names.
20708b244e21SEwan Crawford     // If all the field names match, this is likely the struct we want.
2071b9c1b51eSKate Stone     //   TODO: This could be made more robust by also checking children data
2072b9c1b51eSKate Stone     //   sizes, or array size
20738b244e21SEwan Crawford     bool found = true;
207480af0b9eSLuke Drummond     for (size_t i = 0; i < num_children; ++i) {
207580af0b9eSLuke Drummond       ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
207680af0b9eSLuke Drummond       if (!child || (child->GetName() != elem.children[i].type_name)) {
20778b244e21SEwan Crawford         found = false;
20788b244e21SEwan Crawford         break;
20798b244e21SEwan Crawford       }
20808b244e21SEwan Crawford     }
20818b244e21SEwan Crawford 
2082b9c1b51eSKate Stone     // RS can add extra struct members for padding in the format
2083b9c1b51eSKate Stone     // '#rs_padding_[0-9]+'
2084b9c1b51eSKate Stone     if (found && num_children < elem.children.size()) {
2085b3f7f69dSAidan Dodds       const uint32_t size_diff = elem.children.size() - num_children;
20868b244e21SEwan Crawford       if (log)
2087b9c1b51eSKate Stone         log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2088b9c1b51eSKate Stone                     size_diff);
20898b244e21SEwan Crawford 
209080af0b9eSLuke Drummond       for (uint32_t i = 0; i < size_diff; ++i) {
209180af0b9eSLuke Drummond         const ConstString &name = elem.children[num_children + i].type_name;
20928b244e21SEwan Crawford         if (strcmp(name.AsCString(), "#rs_padding") < 0)
20938b244e21SEwan Crawford           found = false;
20948b244e21SEwan Crawford       }
20958b244e21SEwan Crawford     }
20968b244e21SEwan Crawford 
209780af0b9eSLuke Drummond     // We've found a global variable with matching type
2098b9c1b51eSKate Stone     if (found) {
20998b244e21SEwan Crawford       // Dereference since our Element type isn't a pointer.
2100b9c1b51eSKate Stone       if (valobj_sp->IsPointerType()) {
21018b244e21SEwan Crawford         Error err;
21028b244e21SEwan Crawford         ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
21038b244e21SEwan Crawford         if (!err.Fail())
21048b244e21SEwan Crawford           valobj_sp = deref_valobj;
21058b244e21SEwan Crawford       }
21068b244e21SEwan Crawford 
21078b244e21SEwan Crawford       // Save name of variable in Element.
21088b244e21SEwan Crawford       elem.type_name = valobj_sp->GetTypeName();
21098b244e21SEwan Crawford       if (log)
2110b9c1b51eSKate Stone         log->Printf("%s - element name set to %s", __FUNCTION__,
2111b9c1b51eSKate Stone                     elem.type_name.AsCString());
21128b244e21SEwan Crawford 
21138b244e21SEwan Crawford       return;
21148b244e21SEwan Crawford     }
21158b244e21SEwan Crawford   }
21168b244e21SEwan Crawford }
21178b244e21SEwan Crawford 
2118b9c1b51eSKate Stone // Function sets the datum_size member of Element. Representing the size of a
2119b9c1b51eSKate Stone // single instance including padding.
21208b244e21SEwan Crawford // Assumes the relevant allocation information has already been jitted.
2121b9c1b51eSKate Stone void RenderScriptRuntime::SetElementSize(Element &elem) {
21228b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
21238b244e21SEwan Crawford   const Element::DataType type = *elem.type.get();
2124b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2125b9c1b51eSKate Stone          "Invalid allocation type");
212655232f09SEwan Crawford 
2127b3f7f69dSAidan Dodds   const uint32_t vec_size = *elem.type_vec_size.get();
2128b3f7f69dSAidan Dodds   uint32_t data_size = 0;
2129b3f7f69dSAidan Dodds   uint32_t padding = 0;
213055232f09SEwan Crawford 
21318b244e21SEwan Crawford   // Element is of a struct type, calculate size recursively.
2132b9c1b51eSKate Stone   if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2133b9c1b51eSKate Stone     for (Element &child : elem.children) {
21348b244e21SEwan Crawford       SetElementSize(child);
2135b9c1b51eSKate Stone       const uint32_t array_size =
2136b9c1b51eSKate Stone           child.array_size.isValid() ? *child.array_size.get() : 1;
21378b244e21SEwan Crawford       data_size += *child.datum_size.get() * array_size;
21388b244e21SEwan Crawford     }
21398b244e21SEwan Crawford   }
2140b3f7f69dSAidan Dodds   // These have been packed already
2141b3f7f69dSAidan Dodds   else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2142b3f7f69dSAidan Dodds            type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2143b9c1b51eSKate Stone            type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
21442e920715SEwan Crawford     data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2145b9c1b51eSKate Stone   } else if (type < Element::RS_TYPE_ELEMENT) {
2146b9c1b51eSKate Stone     data_size =
2147b9c1b51eSKate Stone         vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
21482e920715SEwan Crawford     if (vec_size == 3)
21492e920715SEwan Crawford       padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2150b9c1b51eSKate Stone   } else
2151b9c1b51eSKate Stone     data_size =
2152b9c1b51eSKate Stone         GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
21538b244e21SEwan Crawford 
21548b244e21SEwan Crawford   elem.padding = padding;
21558b244e21SEwan Crawford   elem.datum_size = data_size + padding;
21568b244e21SEwan Crawford   if (log)
2157b9c1b51eSKate Stone     log->Printf("%s - element size set to %" PRIu32, __FUNCTION__,
2158b9c1b51eSKate Stone                 data_size + padding);
215955232f09SEwan Crawford }
216055232f09SEwan Crawford 
2161b9c1b51eSKate Stone // Given an allocation, this function copies the allocation contents from device
2162b9c1b51eSKate Stone // into a buffer on the heap.
216355232f09SEwan Crawford // Returning a shared pointer to the buffer containing the data.
216455232f09SEwan Crawford std::shared_ptr<uint8_t>
216580af0b9eSLuke Drummond RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2166b9c1b51eSKate Stone                                        StackFrame *frame_ptr) {
216755232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
216855232f09SEwan Crawford 
216955232f09SEwan Crawford   // JIT all the allocation details
217080af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
217155232f09SEwan Crawford     if (log)
2172b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info",
2173b9c1b51eSKate Stone                   __FUNCTION__);
217455232f09SEwan Crawford 
217580af0b9eSLuke Drummond     if (!RefreshAllocation(alloc, frame_ptr)) {
217655232f09SEwan Crawford       if (log)
2177b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
217855232f09SEwan Crawford       return nullptr;
217955232f09SEwan Crawford     }
218055232f09SEwan Crawford   }
218155232f09SEwan Crawford 
218280af0b9eSLuke Drummond   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
218380af0b9eSLuke Drummond          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
218480af0b9eSLuke Drummond          "Allocation information not available");
218555232f09SEwan Crawford 
218655232f09SEwan Crawford   // Allocate a buffer to copy data into
218780af0b9eSLuke Drummond   const uint32_t size = *alloc->size.get();
218855232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2189b9c1b51eSKate Stone   if (!buffer) {
219055232f09SEwan Crawford     if (log)
2191b9c1b51eSKate Stone       log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer",
2192b9c1b51eSKate Stone                   __FUNCTION__, size);
219355232f09SEwan Crawford     return nullptr;
219455232f09SEwan Crawford   }
219555232f09SEwan Crawford 
219655232f09SEwan Crawford   // Read the inferior memory
219780af0b9eSLuke Drummond   Error err;
219880af0b9eSLuke Drummond   lldb::addr_t data_ptr = *alloc->data_ptr.get();
219980af0b9eSLuke Drummond   GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
220080af0b9eSLuke Drummond   if (err.Fail()) {
220155232f09SEwan Crawford     if (log)
2202b9c1b51eSKate Stone       log->Printf("%s - '%s' Couldn't read %" PRIu32
2203b9c1b51eSKate Stone                   " bytes of allocation data from 0x%" PRIx64,
220480af0b9eSLuke Drummond                   __FUNCTION__, err.AsCString(), size, data_ptr);
220555232f09SEwan Crawford     return nullptr;
220655232f09SEwan Crawford   }
220755232f09SEwan Crawford 
220855232f09SEwan Crawford   return buffer;
220955232f09SEwan Crawford }
221055232f09SEwan Crawford 
221155232f09SEwan Crawford // Function copies data from a binary file into an allocation.
2212b9c1b51eSKate Stone // There is a header at the start of the file, FileHeader, before the data
2213b9c1b51eSKate Stone // content itself.
2214b9c1b51eSKate Stone // Information from this header is used to display warnings to the user about
2215b9c1b51eSKate Stone // incompatibilities
2216b9c1b51eSKate Stone bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
221780af0b9eSLuke Drummond                                          const char *path,
2218b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
221955232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
222055232f09SEwan Crawford 
222155232f09SEwan Crawford   // Find allocation with the given id
222255232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
222355232f09SEwan Crawford   if (!alloc)
222455232f09SEwan Crawford     return false;
222555232f09SEwan Crawford 
222655232f09SEwan Crawford   if (log)
2227b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2228b9c1b51eSKate Stone                 *alloc->address.get());
222955232f09SEwan Crawford 
223055232f09SEwan Crawford   // JIT all the allocation details
223180af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
223255232f09SEwan Crawford     if (log)
2233b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2234b9c1b51eSKate Stone                   __FUNCTION__);
223555232f09SEwan Crawford 
2236b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
223755232f09SEwan Crawford       if (log)
2238b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
22394cfc9198SSylvestre Ledru       return false;
224055232f09SEwan Crawford     }
224155232f09SEwan Crawford   }
224255232f09SEwan Crawford 
2243b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2244b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2245b9c1b51eSKate Stone          alloc->element.datum_size.isValid() &&
2246b9c1b51eSKate Stone          "Allocation information not available");
224755232f09SEwan Crawford 
224855232f09SEwan Crawford   // Check we can read from file
224980af0b9eSLuke Drummond   FileSpec file(path, true);
2250b9c1b51eSKate Stone   if (!file.Exists()) {
225180af0b9eSLuke Drummond     strm.Printf("Error: File %s does not exist", path);
225255232f09SEwan Crawford     strm.EOL();
225355232f09SEwan Crawford     return false;
225455232f09SEwan Crawford   }
225555232f09SEwan Crawford 
2256b9c1b51eSKate Stone   if (!file.Readable()) {
225780af0b9eSLuke Drummond     strm.Printf("Error: File %s does not have readable permissions", path);
225855232f09SEwan Crawford     strm.EOL();
225955232f09SEwan Crawford     return false;
226055232f09SEwan Crawford   }
226155232f09SEwan Crawford 
226255232f09SEwan Crawford   // Read file into data buffer
226355232f09SEwan Crawford   DataBufferSP data_sp(file.ReadFileContents());
226455232f09SEwan Crawford 
226555232f09SEwan Crawford   // Cast start of buffer to FileHeader and use pointer to read metadata
226680af0b9eSLuke Drummond   void *file_buf = data_sp->GetBytes();
226780af0b9eSLuke Drummond   if (file_buf == nullptr ||
2268b9c1b51eSKate Stone       data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2269b9c1b51eSKate Stone                                 sizeof(AllocationDetails::ElementHeader))) {
227080af0b9eSLuke Drummond     strm.Printf("Error: File %s does not contain enough data for header", path);
227126e52a70SEwan Crawford     strm.EOL();
227226e52a70SEwan Crawford     return false;
227326e52a70SEwan Crawford   }
2274b9c1b51eSKate Stone   const AllocationDetails::FileHeader *file_header =
227580af0b9eSLuke Drummond       static_cast<AllocationDetails::FileHeader *>(file_buf);
227655232f09SEwan Crawford 
227726e52a70SEwan Crawford   // Check file starts with ascii characters "RSAD"
2278b9c1b51eSKate Stone   if (memcmp(file_header->ident, "RSAD", 4)) {
2279b9c1b51eSKate Stone     strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2280b9c1b51eSKate Stone                 "dump. Are you sure this is the correct file?");
228126e52a70SEwan Crawford     strm.EOL();
228226e52a70SEwan Crawford     return false;
228326e52a70SEwan Crawford   }
228426e52a70SEwan Crawford 
228526e52a70SEwan Crawford   // Look at the type of the root element in the header
228680af0b9eSLuke Drummond   AllocationDetails::ElementHeader root_el_hdr;
228780af0b9eSLuke Drummond   memcpy(&root_el_hdr, static_cast<uint8_t *>(file_buf) +
2288b9c1b51eSKate Stone                            sizeof(AllocationDetails::FileHeader),
228926e52a70SEwan Crawford          sizeof(AllocationDetails::ElementHeader));
229055232f09SEwan Crawford 
229155232f09SEwan Crawford   if (log)
2292b9c1b51eSKate Stone     log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32,
229380af0b9eSLuke Drummond                 __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
229455232f09SEwan Crawford 
2295b9c1b51eSKate Stone   // Check if the target allocation and file both have the same number of bytes
2296b9c1b51eSKate Stone   // for an Element
229780af0b9eSLuke Drummond   if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2298b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2299b9c1b51eSKate Stone                 " bytes, allocation %" PRIu32 " bytes",
230080af0b9eSLuke Drummond                 root_el_hdr.element_size, *alloc->element.datum_size.get());
230155232f09SEwan Crawford     strm.EOL();
230255232f09SEwan Crawford   }
230355232f09SEwan Crawford 
230426e52a70SEwan Crawford   // Check if the target allocation and file both have the same type
2305b3f7f69dSAidan Dodds   const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
230680af0b9eSLuke Drummond   const uint32_t file_type = root_el_hdr.type;
230726e52a70SEwan Crawford 
2308b9c1b51eSKate Stone   if (file_type > Element::RS_TYPE_FONT) {
230926e52a70SEwan Crawford     strm.Printf("Warning: File has unknown allocation type");
231026e52a70SEwan Crawford     strm.EOL();
2311b9c1b51eSKate Stone   } else if (alloc_type != file_type) {
2312b9c1b51eSKate Stone     // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2313b9c1b51eSKate Stone     // array
231480af0b9eSLuke Drummond     uint32_t target_type_name_idx = alloc_type;
231580af0b9eSLuke Drummond     uint32_t head_type_name_idx = file_type;
2316b9c1b51eSKate Stone     if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2317b9c1b51eSKate Stone         alloc_type <= Element::RS_TYPE_FONT)
231880af0b9eSLuke Drummond       target_type_name_idx = static_cast<Element::DataType>(
2319b9c1b51eSKate Stone           (alloc_type - Element::RS_TYPE_ELEMENT) +
2320b3f7f69dSAidan Dodds           Element::RS_TYPE_MATRIX_2X2 + 1);
23212e920715SEwan Crawford 
2322b9c1b51eSKate Stone     if (file_type >= Element::RS_TYPE_ELEMENT &&
2323b9c1b51eSKate Stone         file_type <= Element::RS_TYPE_FONT)
232480af0b9eSLuke Drummond       head_type_name_idx = static_cast<Element::DataType>(
2325b9c1b51eSKate Stone           (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2326b9c1b51eSKate Stone           1);
23272e920715SEwan Crawford 
232880af0b9eSLuke Drummond     const char *head_type_name =
232980af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
233080af0b9eSLuke Drummond     const char *target_type_name =
233180af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
233255232f09SEwan Crawford 
2333b9c1b51eSKate Stone     strm.Printf(
2334b9c1b51eSKate Stone         "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
233580af0b9eSLuke Drummond         head_type_name, target_type_name);
233655232f09SEwan Crawford     strm.EOL();
233755232f09SEwan Crawford   }
233855232f09SEwan Crawford 
233926e52a70SEwan Crawford   // Advance buffer past header
234080af0b9eSLuke Drummond   file_buf = static_cast<uint8_t *>(file_buf) + file_header->hdr_size;
234126e52a70SEwan Crawford 
234255232f09SEwan Crawford   // Calculate size of allocation data in file
234380af0b9eSLuke Drummond   size_t size = data_sp->GetByteSize() - file_header->hdr_size;
234455232f09SEwan Crawford 
234555232f09SEwan Crawford   // Check if the target allocation and file both have the same total data size.
2346b3f7f69dSAidan Dodds   const uint32_t alloc_size = *alloc->size.get();
234780af0b9eSLuke Drummond   if (alloc_size != size) {
2348b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2349b9c1b51eSKate Stone                 " bytes, allocation 0x%" PRIx32 " bytes",
235080af0b9eSLuke Drummond                 (uint64_t)size, alloc_size);
235155232f09SEwan Crawford     strm.EOL();
235280af0b9eSLuke Drummond     // Set length to copy to minimum
235380af0b9eSLuke Drummond     size = alloc_size < size ? alloc_size : size;
235455232f09SEwan Crawford   }
235555232f09SEwan Crawford 
235655232f09SEwan Crawford   // Copy file data from our buffer into the target allocation.
235755232f09SEwan Crawford   lldb::addr_t alloc_data = *alloc->data_ptr.get();
235880af0b9eSLuke Drummond   Error err;
235980af0b9eSLuke Drummond   size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
236080af0b9eSLuke Drummond   if (!err.Success() || written != size) {
236180af0b9eSLuke Drummond     strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
236255232f09SEwan Crawford     strm.EOL();
236355232f09SEwan Crawford     return false;
236455232f09SEwan Crawford   }
236555232f09SEwan Crawford 
236680af0b9eSLuke Drummond   strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2367b9c1b51eSKate Stone               alloc->id);
236855232f09SEwan Crawford   strm.EOL();
236955232f09SEwan Crawford 
237055232f09SEwan Crawford   return true;
237155232f09SEwan Crawford }
237255232f09SEwan Crawford 
2373b9c1b51eSKate Stone // Function takes as parameters a byte buffer, which will eventually be written
237480af0b9eSLuke Drummond // to file as the element header, an offset into that buffer, and an Element
237580af0b9eSLuke Drummond // that will be saved into the buffer at the parametrised offset.
237626e52a70SEwan Crawford // Return value is the new offset after writing the element into the buffer.
2377b9c1b51eSKate Stone // Elements are saved to the file as the ElementHeader struct followed by
237880af0b9eSLuke Drummond // offsets to the structs of all the element's children.
2379b9c1b51eSKate Stone size_t RenderScriptRuntime::PopulateElementHeaders(
2380b9c1b51eSKate Stone     const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2381b9c1b51eSKate Stone     const Element &elem) {
2382b9c1b51eSKate Stone   // File struct for an element header with all the relevant details copied from
238380af0b9eSLuke Drummond   // elem. We assume members are valid already.
238426e52a70SEwan Crawford   AllocationDetails::ElementHeader elem_header;
238526e52a70SEwan Crawford   elem_header.type = *elem.type.get();
238626e52a70SEwan Crawford   elem_header.kind = *elem.type_kind.get();
238726e52a70SEwan Crawford   elem_header.element_size = *elem.datum_size.get();
238826e52a70SEwan Crawford   elem_header.vector_size = *elem.type_vec_size.get();
2389b9c1b51eSKate Stone   elem_header.array_size =
2390b9c1b51eSKate Stone       elem.array_size.isValid() ? *elem.array_size.get() : 0;
239126e52a70SEwan Crawford   const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
239226e52a70SEwan Crawford 
239326e52a70SEwan Crawford   // Copy struct into buffer and advance offset
2394b9c1b51eSKate Stone   // We assume that header_buffer has been checked for nullptr before this
2395b9c1b51eSKate Stone   // method is called
239626e52a70SEwan Crawford   memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
239726e52a70SEwan Crawford   offset += elem_header_size;
239826e52a70SEwan Crawford 
239926e52a70SEwan Crawford   // Starting offset of child ElementHeader struct
2400b9c1b51eSKate Stone   size_t child_offset =
2401b9c1b51eSKate Stone       offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2402b9c1b51eSKate Stone   for (const RenderScriptRuntime::Element &child : elem.children) {
2403b9c1b51eSKate Stone     // Recursively populate the buffer with the element header structs of
240480af0b9eSLuke Drummond     // children. Then save the offsets where they were set after the parent
240580af0b9eSLuke Drummond     // element header.
240626e52a70SEwan Crawford     memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
240726e52a70SEwan Crawford     offset += sizeof(uint32_t);
240826e52a70SEwan Crawford 
240926e52a70SEwan Crawford     child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
241026e52a70SEwan Crawford   }
241126e52a70SEwan Crawford 
241226e52a70SEwan Crawford   // Zero indicates no more children
241326e52a70SEwan Crawford   memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
241426e52a70SEwan Crawford 
241526e52a70SEwan Crawford   return child_offset;
241626e52a70SEwan Crawford }
241726e52a70SEwan Crawford 
2418b9c1b51eSKate Stone // Given an Element object this function returns the total size needed in the
241980af0b9eSLuke Drummond // file header to store the element's details. Taking into account the size of
242080af0b9eSLuke Drummond // the element header struct, plus the offsets to all the element's children.
2421b9c1b51eSKate Stone // Function is recursive so that the size of all ancestors is taken into
2422b9c1b51eSKate Stone // account.
2423b9c1b51eSKate Stone size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
242480af0b9eSLuke Drummond   // Offsets to children plus zero terminator
242580af0b9eSLuke Drummond   size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
242680af0b9eSLuke Drummond   // Size of header struct with type details
242780af0b9eSLuke Drummond   size += sizeof(AllocationDetails::ElementHeader);
242826e52a70SEwan Crawford 
242926e52a70SEwan Crawford   // Calculate recursively for all descendants
243026e52a70SEwan Crawford   for (const Element &child : elem.children)
243126e52a70SEwan Crawford     size += CalculateElementHeaderSize(child);
243226e52a70SEwan Crawford 
243326e52a70SEwan Crawford   return size;
243426e52a70SEwan Crawford }
243526e52a70SEwan Crawford 
243680af0b9eSLuke Drummond // Function copies allocation contents into a binary file. This file can then be
243780af0b9eSLuke Drummond // loaded later into a different allocation. There is a header, FileHeader,
243880af0b9eSLuke Drummond // before the allocation data containing meta-data.
2439b9c1b51eSKate Stone bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
244080af0b9eSLuke Drummond                                          const char *path,
2441b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
244255232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
244355232f09SEwan Crawford 
244455232f09SEwan Crawford   // Find allocation with the given id
244555232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
244655232f09SEwan Crawford   if (!alloc)
244755232f09SEwan Crawford     return false;
244855232f09SEwan Crawford 
244955232f09SEwan Crawford   if (log)
2450b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2451b9c1b51eSKate Stone                 *alloc->address.get());
245255232f09SEwan Crawford 
245355232f09SEwan Crawford   // JIT all the allocation details
245480af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
245555232f09SEwan Crawford     if (log)
2456b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2457b9c1b51eSKate Stone                   __FUNCTION__);
245855232f09SEwan Crawford 
2459b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
246055232f09SEwan Crawford       if (log)
2461b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
24624cfc9198SSylvestre Ledru       return false;
246355232f09SEwan Crawford     }
246455232f09SEwan Crawford   }
246555232f09SEwan Crawford 
2466b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2467b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() &&
2468b9c1b51eSKate Stone          alloc->element.datum_size.get() &&
2469b9c1b51eSKate Stone          alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2470b3f7f69dSAidan Dodds          "Allocation information not available");
247155232f09SEwan Crawford 
247255232f09SEwan Crawford   // Check we can create writable file
247380af0b9eSLuke Drummond   FileSpec file_spec(path, true);
2474b9c1b51eSKate Stone   File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate |
2475b9c1b51eSKate Stone                            File::eOpenOptionTruncate);
2476b9c1b51eSKate Stone   if (!file) {
247780af0b9eSLuke Drummond     strm.Printf("Error: Failed to open '%s' for writing", path);
247855232f09SEwan Crawford     strm.EOL();
247955232f09SEwan Crawford     return false;
248055232f09SEwan Crawford   }
248155232f09SEwan Crawford 
248255232f09SEwan Crawford   // Read allocation into buffer of heap memory
248355232f09SEwan Crawford   const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2484b9c1b51eSKate Stone   if (!buffer) {
248555232f09SEwan Crawford     strm.Printf("Error: Couldn't read allocation data into buffer");
248655232f09SEwan Crawford     strm.EOL();
248755232f09SEwan Crawford     return false;
248855232f09SEwan Crawford   }
248955232f09SEwan Crawford 
249055232f09SEwan Crawford   // Create the file header
249155232f09SEwan Crawford   AllocationDetails::FileHeader head;
2492b3f7f69dSAidan Dodds   memcpy(head.ident, "RSAD", 4);
24932d62328aSEwan Crawford   head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
24942d62328aSEwan Crawford   head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
24952d62328aSEwan Crawford   head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
249626e52a70SEwan Crawford 
249726e52a70SEwan Crawford   const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2498b9c1b51eSKate Stone   assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2499b9c1b51eSKate Stone              UINT16_MAX &&
2500b9c1b51eSKate Stone          "Element header too large");
2501b9c1b51eSKate Stone   head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2502b9c1b51eSKate Stone                                         element_header_size);
250355232f09SEwan Crawford 
250455232f09SEwan Crawford   // Write the file header
250555232f09SEwan Crawford   size_t num_bytes = sizeof(AllocationDetails::FileHeader);
250626e52a70SEwan Crawford   if (log)
2507b9c1b51eSKate Stone     log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2508b9c1b51eSKate Stone                 (uint64_t)num_bytes);
250926e52a70SEwan Crawford 
251026e52a70SEwan Crawford   Error err = file.Write(&head, num_bytes);
2511b9c1b51eSKate Stone   if (!err.Success()) {
251280af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
251326e52a70SEwan Crawford     strm.EOL();
251426e52a70SEwan Crawford     return false;
251526e52a70SEwan Crawford   }
251626e52a70SEwan Crawford 
251726e52a70SEwan Crawford   // Create the headers describing the element type of the allocation.
2518b9c1b51eSKate Stone   std::shared_ptr<uint8_t> element_header_buffer(
2519b9c1b51eSKate Stone       new uint8_t[element_header_size]);
2520b9c1b51eSKate Stone   if (element_header_buffer == nullptr) {
2521b9c1b51eSKate Stone     strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2522b9c1b51eSKate Stone                 " bytes on the heap",
2523b9c1b51eSKate Stone                 (uint64_t)element_header_size);
252426e52a70SEwan Crawford     strm.EOL();
252526e52a70SEwan Crawford     return false;
252626e52a70SEwan Crawford   }
252726e52a70SEwan Crawford 
252826e52a70SEwan Crawford   PopulateElementHeaders(element_header_buffer, 0, alloc->element);
252926e52a70SEwan Crawford 
253026e52a70SEwan Crawford   // Write headers for allocation element type to file
253126e52a70SEwan Crawford   num_bytes = element_header_size;
253226e52a70SEwan Crawford   if (log)
2533b9c1b51eSKate Stone     log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.",
2534b9c1b51eSKate Stone                 __FUNCTION__, (uint64_t)num_bytes);
253526e52a70SEwan Crawford 
253626e52a70SEwan Crawford   err = file.Write(element_header_buffer.get(), num_bytes);
2537b9c1b51eSKate Stone   if (!err.Success()) {
253880af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
253955232f09SEwan Crawford     strm.EOL();
254055232f09SEwan Crawford     return false;
254155232f09SEwan Crawford   }
254255232f09SEwan Crawford 
254355232f09SEwan Crawford   // Write allocation data to file
254455232f09SEwan Crawford   num_bytes = static_cast<size_t>(*alloc->size.get());
254555232f09SEwan Crawford   if (log)
2546b9c1b51eSKate Stone     log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2547b9c1b51eSKate Stone                 (uint64_t)num_bytes);
254855232f09SEwan Crawford 
254955232f09SEwan Crawford   err = file.Write(buffer.get(), num_bytes);
2550b9c1b51eSKate Stone   if (!err.Success()) {
255180af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
255255232f09SEwan Crawford     strm.EOL();
255355232f09SEwan Crawford     return false;
255455232f09SEwan Crawford   }
255555232f09SEwan Crawford 
255680af0b9eSLuke Drummond   strm.Printf("Allocation written to file '%s'", path);
255755232f09SEwan Crawford   strm.EOL();
255815f2bd95SEwan Crawford   return true;
255915f2bd95SEwan Crawford }
256015f2bd95SEwan Crawford 
2561b9c1b51eSKate Stone bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
25624640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
25634640cde1SColin Riley 
2564b9c1b51eSKate Stone   if (module_sp) {
2565b9c1b51eSKate Stone     for (const auto &rs_module : m_rsmodules) {
2566b9c1b51eSKate Stone       if (rs_module->m_module == module_sp) {
25677dc7771cSEwan Crawford         // Check if the user has enabled automatically breaking on
25687dc7771cSEwan Crawford         // all RS kernels.
25697dc7771cSEwan Crawford         if (m_breakAllKernels)
25707dc7771cSEwan Crawford           BreakOnModuleKernels(rs_module);
25717dc7771cSEwan Crawford 
25725ec532a9SColin Riley         return false;
25735ec532a9SColin Riley       }
25747dc7771cSEwan Crawford     }
2575ef20b08fSColin Riley     bool module_loaded = false;
2576b9c1b51eSKate Stone     switch (GetModuleKind(module_sp)) {
2577b9c1b51eSKate Stone     case eModuleKindKernelObj: {
25784640cde1SColin Riley       RSModuleDescriptorSP module_desc;
25794640cde1SColin Riley       module_desc.reset(new RSModuleDescriptor(module_sp));
2580b9c1b51eSKate Stone       if (module_desc->ParseRSInfo()) {
25815ec532a9SColin Riley         m_rsmodules.push_back(module_desc);
2582ef20b08fSColin Riley         module_loaded = true;
25835ec532a9SColin Riley       }
2584b9c1b51eSKate Stone       if (module_loaded) {
25854640cde1SColin Riley         FixupScriptDetails(module_desc);
25864640cde1SColin Riley       }
2587ef20b08fSColin Riley       break;
2588ef20b08fSColin Riley     }
2589b9c1b51eSKate Stone     case eModuleKindDriver: {
2590b9c1b51eSKate Stone       if (!m_libRSDriver) {
25914640cde1SColin Riley         m_libRSDriver = module_sp;
25924640cde1SColin Riley         LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
25934640cde1SColin Riley       }
25944640cde1SColin Riley       break;
25954640cde1SColin Riley     }
2596b9c1b51eSKate Stone     case eModuleKindImpl: {
25974640cde1SColin Riley       m_libRSCpuRef = module_sp;
25984640cde1SColin Riley       break;
25994640cde1SColin Riley     }
2600b9c1b51eSKate Stone     case eModuleKindLibRS: {
2601b9c1b51eSKate Stone       if (!m_libRS) {
26024640cde1SColin Riley         m_libRS = module_sp;
26034640cde1SColin Riley         static ConstString gDbgPresentStr("gDebuggerPresent");
2604b9c1b51eSKate Stone         const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2605b9c1b51eSKate Stone             gDbgPresentStr, eSymbolTypeData);
2606b9c1b51eSKate Stone         if (debug_present) {
260780af0b9eSLuke Drummond           Error err;
26084640cde1SColin Riley           uint32_t flag = 0x00000001U;
26094640cde1SColin Riley           Target &target = GetProcess()->GetTarget();
2610358cf1eaSGreg Clayton           addr_t addr = debug_present->GetLoadAddress(&target);
261180af0b9eSLuke Drummond           GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
261280af0b9eSLuke Drummond           if (err.Success()) {
26134640cde1SColin Riley             if (log)
2614b9c1b51eSKate Stone               log->Printf("%s - debugger present flag set on debugee.",
2615b9c1b51eSKate Stone                           __FUNCTION__);
26164640cde1SColin Riley 
26174640cde1SColin Riley             m_debuggerPresentFlagged = true;
2618b9c1b51eSKate Stone           } else if (log) {
2619b9c1b51eSKate Stone             log->Printf("%s - error writing debugger present flags '%s' ",
262080af0b9eSLuke Drummond                         __FUNCTION__, err.AsCString());
26214640cde1SColin Riley           }
2622b9c1b51eSKate Stone         } else if (log) {
2623b9c1b51eSKate Stone           log->Printf(
2624b9c1b51eSKate Stone               "%s - error writing debugger present flags - symbol not found",
2625b9c1b51eSKate Stone               __FUNCTION__);
26264640cde1SColin Riley         }
26274640cde1SColin Riley       }
26284640cde1SColin Riley       break;
26294640cde1SColin Riley     }
2630ef20b08fSColin Riley     default:
2631ef20b08fSColin Riley       break;
2632ef20b08fSColin Riley     }
2633ef20b08fSColin Riley     if (module_loaded)
2634ef20b08fSColin Riley       Update();
2635ef20b08fSColin Riley     return module_loaded;
26365ec532a9SColin Riley   }
26375ec532a9SColin Riley   return false;
26385ec532a9SColin Riley }
26395ec532a9SColin Riley 
2640b9c1b51eSKate Stone void RenderScriptRuntime::Update() {
2641b9c1b51eSKate Stone   if (m_rsmodules.size() > 0) {
2642b9c1b51eSKate Stone     if (!m_initiated) {
2643ef20b08fSColin Riley       Initiate();
2644ef20b08fSColin Riley     }
2645ef20b08fSColin Riley   }
2646ef20b08fSColin Riley }
2647ef20b08fSColin Riley 
26487f193d69SLuke Drummond bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
26497f193d69SLuke Drummond                                           size_t n_lines) {
26507f193d69SLuke Drummond   // Skip the pragma prototype line
26517f193d69SLuke Drummond   ++lines;
26527f193d69SLuke Drummond   for (; n_lines--; ++lines) {
26537f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
26547f193d69SLuke Drummond     m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
26557f193d69SLuke Drummond   }
26567f193d69SLuke Drummond   return true;
26577f193d69SLuke Drummond }
26587f193d69SLuke Drummond 
26597f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
26607f193d69SLuke Drummond                                                 size_t n_lines) {
26617f193d69SLuke Drummond   // The list of reduction kernels in the `.rs.info` symbol is of the form
26627f193d69SLuke Drummond   // "signature - accumulatordatasize - reduction_name - initializer_name -
26637f193d69SLuke Drummond   // accumulator_name - combiner_name -
26647f193d69SLuke Drummond   // outconverter_name - halter_name"
26657f193d69SLuke Drummond   // Where a function is not explicitly named by the user, or is not generated
26667f193d69SLuke Drummond   // by the compiler, it is named "." so the
26677f193d69SLuke Drummond   // dash separated list should always be 8 items long
26687f193d69SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
26697f193d69SLuke Drummond   // Skip the exportReduceCount line
26707f193d69SLuke Drummond   ++lines;
26717f193d69SLuke Drummond   for (; n_lines--; ++lines) {
26727f193d69SLuke Drummond     llvm::SmallVector<llvm::StringRef, 8> spec;
26737f193d69SLuke Drummond     lines->split(spec, " - ");
26747f193d69SLuke Drummond     if (spec.size() != 8) {
26757f193d69SLuke Drummond       if (spec.size() < 8) {
26767f193d69SLuke Drummond         if (log)
26777f193d69SLuke Drummond           log->Error("Error parsing RenderScript reduction spec. wrong number "
26787f193d69SLuke Drummond                      "of fields");
26797f193d69SLuke Drummond         return false;
26807f193d69SLuke Drummond       } else if (log)
26817f193d69SLuke Drummond         log->Warning("Extraneous members in reduction spec: '%s'",
26827f193d69SLuke Drummond                      lines->str().c_str());
26837f193d69SLuke Drummond     }
26847f193d69SLuke Drummond 
26857f193d69SLuke Drummond     const auto sig_s = spec[0];
26867f193d69SLuke Drummond     uint32_t sig;
26877f193d69SLuke Drummond     if (sig_s.getAsInteger(10, sig)) {
26887f193d69SLuke Drummond       if (log)
26897f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid kernel "
26907f193d69SLuke Drummond                    "signature: '%s'",
26917f193d69SLuke Drummond                    sig_s.str().c_str());
26927f193d69SLuke Drummond       return false;
26937f193d69SLuke Drummond     }
26947f193d69SLuke Drummond 
26957f193d69SLuke Drummond     const auto accum_data_size_s = spec[1];
26967f193d69SLuke Drummond     uint32_t accum_data_size;
26977f193d69SLuke Drummond     if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
26987f193d69SLuke Drummond       if (log)
26997f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid "
27007f193d69SLuke Drummond                    "accumulator data size %s",
27017f193d69SLuke Drummond                    accum_data_size_s.str().c_str());
27027f193d69SLuke Drummond       return false;
27037f193d69SLuke Drummond     }
27047f193d69SLuke Drummond 
27057f193d69SLuke Drummond     if (log)
27067f193d69SLuke Drummond       log->Printf("Found RenderScript reduction '%s'", spec[2].str().c_str());
27077f193d69SLuke Drummond 
27087f193d69SLuke Drummond     m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
27097f193d69SLuke Drummond                                                  spec[2], spec[3], spec[4],
27107f193d69SLuke Drummond                                                  spec[5], spec[6], spec[7]));
27117f193d69SLuke Drummond   }
27127f193d69SLuke Drummond   return true;
27137f193d69SLuke Drummond }
27147f193d69SLuke Drummond 
27157f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
27167f193d69SLuke Drummond                                                  size_t n_lines) {
27177f193d69SLuke Drummond   // Skip the exportForeachCount line
27187f193d69SLuke Drummond   ++lines;
27197f193d69SLuke Drummond   for (; n_lines--; ++lines) {
27207f193d69SLuke Drummond     uint32_t slot;
27217f193d69SLuke Drummond     // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
27227f193d69SLuke Drummond     // pair per line
27237f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
27247f193d69SLuke Drummond     if (kv_pair.first.getAsInteger(10, slot))
27257f193d69SLuke Drummond       return false;
27267f193d69SLuke Drummond     m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
27277f193d69SLuke Drummond   }
27287f193d69SLuke Drummond   return true;
27297f193d69SLuke Drummond }
27307f193d69SLuke Drummond 
27317f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
27327f193d69SLuke Drummond                                              size_t n_lines) {
27337f193d69SLuke Drummond   // Skip the ExportVarCount line
27347f193d69SLuke Drummond   ++lines;
27357f193d69SLuke Drummond   for (; n_lines--; ++lines)
27367f193d69SLuke Drummond     m_globals.push_back(RSGlobalDescriptor(this, *lines));
27377f193d69SLuke Drummond   return true;
27387f193d69SLuke Drummond }
27395ec532a9SColin Riley 
2740b9c1b51eSKate Stone // The .rs.info symbol in renderscript modules contains a string which needs to
2741b9c1b51eSKate Stone // be parsed.
27425ec532a9SColin Riley // The string is basic and is parsed on a line by line basis.
2743b9c1b51eSKate Stone bool RSModuleDescriptor::ParseRSInfo() {
2744b0be30f7SAidan Dodds   assert(m_module);
27457f193d69SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2746b9c1b51eSKate Stone   const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
2747b9c1b51eSKate Stone       ConstString(".rs.info"), eSymbolTypeData);
2748b0be30f7SAidan Dodds   if (!info_sym)
2749b0be30f7SAidan Dodds     return false;
2750b0be30f7SAidan Dodds 
2751358cf1eaSGreg Clayton   const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
2752b0be30f7SAidan Dodds   if (addr == LLDB_INVALID_ADDRESS)
2753b0be30f7SAidan Dodds     return false;
2754b0be30f7SAidan Dodds 
27555ec532a9SColin Riley   const addr_t size = info_sym->GetByteSize();
27565ec532a9SColin Riley   const FileSpec fs = m_module->GetFileSpec();
27575ec532a9SColin Riley 
2758b0be30f7SAidan Dodds   const DataBufferSP buffer = fs.ReadFileContents(addr, size);
27595ec532a9SColin Riley   if (!buffer)
27605ec532a9SColin Riley     return false;
27615ec532a9SColin Riley 
2762b0be30f7SAidan Dodds   // split rs.info. contents into lines
27637f193d69SLuke Drummond   llvm::SmallVector<llvm::StringRef, 128> info_lines;
27645ec532a9SColin Riley   {
27657f193d69SLuke Drummond     const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
27667f193d69SLuke Drummond     raw_rs_info.split(info_lines, '\n');
27677f193d69SLuke Drummond     if (log)
27687f193d69SLuke Drummond       log->Printf("'.rs.info symbol for '%s':\n%s",
27697f193d69SLuke Drummond                   m_module->GetFileSpec().GetCString(),
27707f193d69SLuke Drummond                   raw_rs_info.str().c_str());
2771b0be30f7SAidan Dodds   }
2772b0be30f7SAidan Dodds 
27737f193d69SLuke Drummond   enum {
27747f193d69SLuke Drummond     eExportVar,
27757f193d69SLuke Drummond     eExportForEach,
27767f193d69SLuke Drummond     eExportReduce,
27777f193d69SLuke Drummond     ePragma,
27787f193d69SLuke Drummond     eBuildChecksum,
27797f193d69SLuke Drummond     eObjectSlot
27807f193d69SLuke Drummond   };
27817f193d69SLuke Drummond 
2782*b3bbcb12SLuke Drummond   const auto rs_info_handler = [](llvm::StringRef name) -> int {
2783*b3bbcb12SLuke Drummond     return llvm::StringSwitch<int>(name)
2784*b3bbcb12SLuke Drummond         // The number of visible global variables in the script
2785*b3bbcb12SLuke Drummond         .Case("exportVarCount", eExportVar)
27867f193d69SLuke Drummond         // The number of RenderScrip `forEach` kernels __attribute__((kernel))
2787*b3bbcb12SLuke Drummond         .Case("exportForEachCount", eExportForEach)
2788*b3bbcb12SLuke Drummond         // The number of generalreductions: This marked in the script by
2789*b3bbcb12SLuke Drummond         // `#pragma reduce()`
2790*b3bbcb12SLuke Drummond         .Case("exportReduceCount", eExportReduce)
2791*b3bbcb12SLuke Drummond         // Total count of all RenderScript specific `#pragmas` used in the
2792*b3bbcb12SLuke Drummond         // script
2793*b3bbcb12SLuke Drummond         .Case("pragmaCount", ePragma)
2794*b3bbcb12SLuke Drummond         .Case("objectSlotCount", eObjectSlot)
2795*b3bbcb12SLuke Drummond         .Default(-1);
2796*b3bbcb12SLuke Drummond   };
2797b0be30f7SAidan Dodds 
2798b0be30f7SAidan Dodds   // parse all text lines of .rs.info
2799b9c1b51eSKate Stone   for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
28007f193d69SLuke Drummond     const auto kv_pair = line->split(": ");
28017f193d69SLuke Drummond     const auto key = kv_pair.first;
28027f193d69SLuke Drummond     const auto val = kv_pair.second.trim();
28035ec532a9SColin Riley 
2804*b3bbcb12SLuke Drummond     const auto handler = rs_info_handler(key);
2805*b3bbcb12SLuke Drummond     if (handler == -1)
28067f193d69SLuke Drummond       continue;
28077f193d69SLuke Drummond     // getAsInteger returns `true` on an error condition - we're only interested
2808*b3bbcb12SLuke Drummond     // in numeric fields at the moment
28097f193d69SLuke Drummond     uint64_t n_lines;
28107f193d69SLuke Drummond     if (val.getAsInteger(10, n_lines)) {
28117f193d69SLuke Drummond       if (log)
28127f193d69SLuke Drummond         log->Debug("Failed to parse non-numeric '.rs.info' section %s",
28137f193d69SLuke Drummond                    line->str().c_str());
28147f193d69SLuke Drummond       continue;
28157f193d69SLuke Drummond     }
28167f193d69SLuke Drummond     if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
28177f193d69SLuke Drummond       return false;
28187f193d69SLuke Drummond 
28197f193d69SLuke Drummond     bool success = false;
2820*b3bbcb12SLuke Drummond     switch (handler) {
28217f193d69SLuke Drummond     case eExportVar:
28227f193d69SLuke Drummond       success = ParseExportVarCount(line, n_lines);
28237f193d69SLuke Drummond       break;
28247f193d69SLuke Drummond     case eExportForEach:
28257f193d69SLuke Drummond       success = ParseExportForeachCount(line, n_lines);
28267f193d69SLuke Drummond       break;
28277f193d69SLuke Drummond     case eExportReduce:
28287f193d69SLuke Drummond       success = ParseExportReduceCount(line, n_lines);
28297f193d69SLuke Drummond       break;
28307f193d69SLuke Drummond     case ePragma:
28317f193d69SLuke Drummond       success = ParsePragmaCount(line, n_lines);
28327f193d69SLuke Drummond       break;
28337f193d69SLuke Drummond     default: {
28347f193d69SLuke Drummond       if (log)
28357f193d69SLuke Drummond         log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__,
28367f193d69SLuke Drummond                     line->str().c_str());
28377f193d69SLuke Drummond       continue;
28387f193d69SLuke Drummond     }
28397f193d69SLuke Drummond     }
28407f193d69SLuke Drummond     if (!success)
28417f193d69SLuke Drummond       return false;
28427f193d69SLuke Drummond     line += n_lines;
28437f193d69SLuke Drummond   }
28447f193d69SLuke Drummond   return info_lines.size() > 0;
28455ec532a9SColin Riley }
28465ec532a9SColin Riley 
2847b9c1b51eSKate Stone void RenderScriptRuntime::Status(Stream &strm) const {
2848b9c1b51eSKate Stone   if (m_libRS) {
28494640cde1SColin Riley     strm.Printf("Runtime Library discovered.");
28504640cde1SColin Riley     strm.EOL();
28514640cde1SColin Riley   }
2852b9c1b51eSKate Stone   if (m_libRSDriver) {
28534640cde1SColin Riley     strm.Printf("Runtime Driver discovered.");
28544640cde1SColin Riley     strm.EOL();
28554640cde1SColin Riley   }
2856b9c1b51eSKate Stone   if (m_libRSCpuRef) {
28574640cde1SColin Riley     strm.Printf("CPU Reference Implementation discovered.");
28584640cde1SColin Riley     strm.EOL();
28594640cde1SColin Riley   }
28604640cde1SColin Riley 
2861b9c1b51eSKate Stone   if (m_runtimeHooks.size()) {
28624640cde1SColin Riley     strm.Printf("Runtime functions hooked:");
28634640cde1SColin Riley     strm.EOL();
2864b9c1b51eSKate Stone     for (auto b : m_runtimeHooks) {
28654640cde1SColin Riley       strm.Indent(b.second->defn->name);
28664640cde1SColin Riley       strm.EOL();
28674640cde1SColin Riley     }
2868b9c1b51eSKate Stone   } else {
28694640cde1SColin Riley     strm.Printf("Runtime is not hooked.");
28704640cde1SColin Riley     strm.EOL();
28714640cde1SColin Riley   }
28724640cde1SColin Riley }
28734640cde1SColin Riley 
2874b9c1b51eSKate Stone void RenderScriptRuntime::DumpContexts(Stream &strm) const {
28754640cde1SColin Riley   strm.Printf("Inferred RenderScript Contexts:");
28764640cde1SColin Riley   strm.EOL();
28774640cde1SColin Riley   strm.IndentMore();
28784640cde1SColin Riley 
28794640cde1SColin Riley   std::map<addr_t, uint64_t> contextReferences;
28804640cde1SColin Riley 
288178f339d1SEwan Crawford   // Iterate over all of the currently discovered scripts.
2882b9c1b51eSKate Stone   // Note: We cant push or pop from m_scripts inside this loop or it may
2883b9c1b51eSKate Stone   // invalidate script.
2884b9c1b51eSKate Stone   for (const auto &script : m_scripts) {
288578f339d1SEwan Crawford     if (!script->context.isValid())
288678f339d1SEwan Crawford       continue;
288778f339d1SEwan Crawford     lldb::addr_t context = *script->context;
288878f339d1SEwan Crawford 
2889b9c1b51eSKate Stone     if (contextReferences.find(context) != contextReferences.end()) {
289078f339d1SEwan Crawford       contextReferences[context]++;
2891b9c1b51eSKate Stone     } else {
289278f339d1SEwan Crawford       contextReferences[context] = 1;
28934640cde1SColin Riley     }
28944640cde1SColin Riley   }
28954640cde1SColin Riley 
2896b9c1b51eSKate Stone   for (const auto &cRef : contextReferences) {
2897b9c1b51eSKate Stone     strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
2898b9c1b51eSKate Stone                 cRef.first, cRef.second);
28994640cde1SColin Riley     strm.EOL();
29004640cde1SColin Riley   }
29014640cde1SColin Riley   strm.IndentLess();
29024640cde1SColin Riley }
29034640cde1SColin Riley 
2904b9c1b51eSKate Stone void RenderScriptRuntime::DumpKernels(Stream &strm) const {
29054640cde1SColin Riley   strm.Printf("RenderScript Kernels:");
29064640cde1SColin Riley   strm.EOL();
29074640cde1SColin Riley   strm.IndentMore();
2908b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
29094640cde1SColin Riley     strm.Printf("Resource '%s':", module->m_resname.c_str());
29104640cde1SColin Riley     strm.EOL();
2911b9c1b51eSKate Stone     for (const auto &kernel : module->m_kernels) {
29124640cde1SColin Riley       strm.Indent(kernel.m_name.AsCString());
29134640cde1SColin Riley       strm.EOL();
29144640cde1SColin Riley     }
29154640cde1SColin Riley   }
29164640cde1SColin Riley   strm.IndentLess();
29174640cde1SColin Riley }
29184640cde1SColin Riley 
2919a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails *
2920b9c1b51eSKate Stone RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
2921a0f08674SEwan Crawford   AllocationDetails *alloc = nullptr;
2922a0f08674SEwan Crawford 
2923a0f08674SEwan Crawford   // See if we can find allocation using id as an index;
2924b9c1b51eSKate Stone   if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
2925b9c1b51eSKate Stone       m_allocations[alloc_id - 1]->id == alloc_id) {
2926a0f08674SEwan Crawford     alloc = m_allocations[alloc_id - 1].get();
2927a0f08674SEwan Crawford     return alloc;
2928a0f08674SEwan Crawford   }
2929a0f08674SEwan Crawford 
2930a0f08674SEwan Crawford   // Fallback to searching
2931b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
2932b9c1b51eSKate Stone     if (a->id == alloc_id) {
2933a0f08674SEwan Crawford       alloc = a.get();
2934a0f08674SEwan Crawford       break;
2935a0f08674SEwan Crawford     }
2936a0f08674SEwan Crawford   }
2937a0f08674SEwan Crawford 
2938b9c1b51eSKate Stone   if (alloc == nullptr) {
2939b9c1b51eSKate Stone     strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
2940b9c1b51eSKate Stone                 alloc_id);
2941a0f08674SEwan Crawford     strm.EOL();
2942a0f08674SEwan Crawford   }
2943a0f08674SEwan Crawford 
2944a0f08674SEwan Crawford   return alloc;
2945a0f08674SEwan Crawford }
2946a0f08674SEwan Crawford 
2947b9c1b51eSKate Stone // Prints the contents of an allocation to the output stream, which may be a
2948b9c1b51eSKate Stone // file
2949b9c1b51eSKate Stone bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
2950b9c1b51eSKate Stone                                          const uint32_t id) {
2951a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2952a0f08674SEwan Crawford 
2953a0f08674SEwan Crawford   // Check we can find the desired allocation
2954a0f08674SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, id);
2955a0f08674SEwan Crawford   if (!alloc)
2956a0f08674SEwan Crawford     return false; // FindAllocByID() will print error message for us here
2957a0f08674SEwan Crawford 
2958a0f08674SEwan Crawford   if (log)
2959b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2960b9c1b51eSKate Stone                 *alloc->address.get());
2961a0f08674SEwan Crawford 
2962a0f08674SEwan Crawford   // Check we have information about the allocation, if not calculate it
296380af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
2964a0f08674SEwan Crawford     if (log)
2965b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2966b9c1b51eSKate Stone                   __FUNCTION__);
2967a0f08674SEwan Crawford 
2968a0f08674SEwan Crawford     // JIT all the allocation information
2969b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
2970a0f08674SEwan Crawford       strm.Printf("Error: Couldn't JIT allocation details");
2971a0f08674SEwan Crawford       strm.EOL();
2972a0f08674SEwan Crawford       return false;
2973a0f08674SEwan Crawford     }
2974a0f08674SEwan Crawford   }
2975a0f08674SEwan Crawford 
2976a0f08674SEwan Crawford   // Establish format and size of each data element
2977b3f7f69dSAidan Dodds   const uint32_t vec_size = *alloc->element.type_vec_size.get();
29788b244e21SEwan Crawford   const Element::DataType type = *alloc->element.type.get();
2979a0f08674SEwan Crawford 
2980b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2981b9c1b51eSKate Stone          "Invalid allocation type");
2982a0f08674SEwan Crawford 
29832e920715SEwan Crawford   lldb::Format format;
29842e920715SEwan Crawford   if (type >= Element::RS_TYPE_ELEMENT)
29852e920715SEwan Crawford     format = eFormatHex;
29862e920715SEwan Crawford   else
2987b9c1b51eSKate Stone     format = vec_size == 1
2988b9c1b51eSKate Stone                  ? static_cast<lldb::Format>(
2989b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatSingle])
2990b9c1b51eSKate Stone                  : static_cast<lldb::Format>(
2991b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatVector]);
2992a0f08674SEwan Crawford 
2993b3f7f69dSAidan Dodds   const uint32_t data_size = *alloc->element.datum_size.get();
2994a0f08674SEwan Crawford 
2995a0f08674SEwan Crawford   if (log)
2996b9c1b51eSKate Stone     log->Printf("%s - element size %" PRIu32 " bytes, including padding",
2997b9c1b51eSKate Stone                 __FUNCTION__, data_size);
2998a0f08674SEwan Crawford 
299955232f09SEwan Crawford   // Allocate a buffer to copy data into
300055232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3001b9c1b51eSKate Stone   if (!buffer) {
30022e920715SEwan Crawford     strm.Printf("Error: Couldn't read allocation data");
300355232f09SEwan Crawford     strm.EOL();
300455232f09SEwan Crawford     return false;
300555232f09SEwan Crawford   }
300655232f09SEwan Crawford 
3007a0f08674SEwan Crawford   // Calculate stride between rows as there may be padding at end of rows since
3008a0f08674SEwan Crawford   // allocated memory is 16-byte aligned
3009b9c1b51eSKate Stone   if (!alloc->stride.isValid()) {
3010a0f08674SEwan Crawford     if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
3011a0f08674SEwan Crawford       alloc->stride = 0;
3012b9c1b51eSKate Stone     else if (!JITAllocationStride(alloc, frame_ptr)) {
3013a0f08674SEwan Crawford       strm.Printf("Error: Couldn't calculate allocation row stride");
3014a0f08674SEwan Crawford       strm.EOL();
3015a0f08674SEwan Crawford       return false;
3016a0f08674SEwan Crawford     }
3017a0f08674SEwan Crawford   }
3018b3f7f69dSAidan Dodds   const uint32_t stride = *alloc->stride.get();
3019b3f7f69dSAidan Dodds   const uint32_t size = *alloc->size.get(); // Size of whole allocation
3020b9c1b51eSKate Stone   const uint32_t padding =
3021b9c1b51eSKate Stone       alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3022a0f08674SEwan Crawford   if (log)
3023b9c1b51eSKate Stone     log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32
3024b9c1b51eSKate Stone                 " bytes, padding %" PRIu32,
3025b3f7f69dSAidan Dodds                 __FUNCTION__, stride, size, padding);
3026a0f08674SEwan Crawford 
3027a0f08674SEwan Crawford   // Find dimensions used to index loops, so need to be non-zero
3028b3f7f69dSAidan Dodds   uint32_t dim_x = alloc->dimension.get()->dim_1;
3029a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 1 : dim_x;
3030a0f08674SEwan Crawford 
3031b3f7f69dSAidan Dodds   uint32_t dim_y = alloc->dimension.get()->dim_2;
3032a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 1 : dim_y;
3033a0f08674SEwan Crawford 
3034b3f7f69dSAidan Dodds   uint32_t dim_z = alloc->dimension.get()->dim_3;
3035a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 1 : dim_z;
3036a0f08674SEwan Crawford 
303755232f09SEwan Crawford   // Use data extractor to format output
303880af0b9eSLuke Drummond   const uint32_t target_ptr_size =
3039b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3040b9c1b51eSKate Stone   DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
304180af0b9eSLuke Drummond                            target_ptr_size);
304255232f09SEwan Crawford 
3043b3f7f69dSAidan Dodds   uint32_t offset = 0;   // Offset in buffer to next element to be printed
3044b3f7f69dSAidan Dodds   uint32_t prev_row = 0; // Offset to the start of the previous row
3045a0f08674SEwan Crawford 
3046a0f08674SEwan Crawford   // Iterate over allocation dimensions, printing results to user
3047a0f08674SEwan Crawford   strm.Printf("Data (X, Y, Z):");
3048b9c1b51eSKate Stone   for (uint32_t z = 0; z < dim_z; ++z) {
3049b9c1b51eSKate Stone     for (uint32_t y = 0; y < dim_y; ++y) {
3050a0f08674SEwan Crawford       // Use stride to index start of next row.
3051a0f08674SEwan Crawford       if (!(y == 0 && z == 0))
3052a0f08674SEwan Crawford         offset = prev_row + stride;
3053a0f08674SEwan Crawford       prev_row = offset;
3054a0f08674SEwan Crawford 
3055a0f08674SEwan Crawford       // Print each element in the row individually
3056b9c1b51eSKate Stone       for (uint32_t x = 0; x < dim_x; ++x) {
3057b3f7f69dSAidan Dodds         strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3058b9c1b51eSKate Stone         if ((type == Element::RS_TYPE_NONE) &&
3059b9c1b51eSKate Stone             (alloc->element.children.size() > 0) &&
3060b9c1b51eSKate Stone             (alloc->element.type_name != Element::GetFallbackStructName())) {
30618b244e21SEwan Crawford           // Here we are dumping an Element of struct type.
3062b9c1b51eSKate Stone           // This is done using expression evaluation with the name of the
3063b9c1b51eSKate Stone           // struct type and pointer to element.
3064b9c1b51eSKate Stone           // Don't print the name of the resulting expression, since this will
3065b9c1b51eSKate Stone           // be '$[0-9]+'
30668b244e21SEwan Crawford           DumpValueObjectOptions expr_options;
30678b244e21SEwan Crawford           expr_options.SetHideName(true);
30688b244e21SEwan Crawford 
30698b244e21SEwan Crawford           // Setup expression as derefrencing a pointer cast to element address.
3070ea0636b5SEwan Crawford           char expr_char_buffer[jit_max_expr_size];
307180af0b9eSLuke Drummond           int written =
3072b9c1b51eSKate Stone               snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3073b9c1b51eSKate Stone                        alloc->element.type_name.AsCString(),
3074b9c1b51eSKate Stone                        *alloc->data_ptr.get() + offset);
30758b244e21SEwan Crawford 
307680af0b9eSLuke Drummond           if (written < 0 || written >= jit_max_expr_size) {
30778b244e21SEwan Crawford             if (log)
3078b3f7f69dSAidan Dodds               log->Printf("%s - error in snprintf().", __FUNCTION__);
30798b244e21SEwan Crawford             continue;
30808b244e21SEwan Crawford           }
30818b244e21SEwan Crawford 
30828b244e21SEwan Crawford           // Evaluate expression
30838b244e21SEwan Crawford           ValueObjectSP expr_result;
3084b9c1b51eSKate Stone           GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3085b9c1b51eSKate Stone                                                        frame_ptr, expr_result);
30868b244e21SEwan Crawford 
30878b244e21SEwan Crawford           // Print the results to our stream.
30888b244e21SEwan Crawford           expr_result->Dump(strm, expr_options);
3089b9c1b51eSKate Stone         } else {
3090b9c1b51eSKate Stone           alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1,
3091b9c1b51eSKate Stone                           LLDB_INVALID_ADDRESS, 0, 0);
30928b244e21SEwan Crawford         }
30938b244e21SEwan Crawford         offset += data_size;
3094a0f08674SEwan Crawford       }
3095a0f08674SEwan Crawford     }
3096a0f08674SEwan Crawford   }
3097a0f08674SEwan Crawford   strm.EOL();
3098a0f08674SEwan Crawford 
3099a0f08674SEwan Crawford   return true;
3100a0f08674SEwan Crawford }
3101a0f08674SEwan Crawford 
3102b9c1b51eSKate Stone // Function recalculates all our cached information about allocations by jitting
310380af0b9eSLuke Drummond // the RS runtime regarding each allocation we know about. Returns true if all
310480af0b9eSLuke Drummond // allocations could be recomputed, false otherwise.
3105b9c1b51eSKate Stone bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3106b9c1b51eSKate Stone                                                   StackFrame *frame_ptr) {
31070d2bfcfbSEwan Crawford   bool success = true;
3108b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
31090d2bfcfbSEwan Crawford     // JIT current allocation information
3110b9c1b51eSKate Stone     if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3111b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3112b9c1b51eSKate Stone                   "\n",
3113b9c1b51eSKate Stone                   alloc->id);
31140d2bfcfbSEwan Crawford       success = false;
31150d2bfcfbSEwan Crawford     }
31160d2bfcfbSEwan Crawford   }
31170d2bfcfbSEwan Crawford 
31180d2bfcfbSEwan Crawford   if (success)
31190d2bfcfbSEwan Crawford     strm.Printf("All allocations successfully recomputed");
31200d2bfcfbSEwan Crawford   strm.EOL();
31210d2bfcfbSEwan Crawford 
31220d2bfcfbSEwan Crawford   return success;
31230d2bfcfbSEwan Crawford }
31240d2bfcfbSEwan Crawford 
312580af0b9eSLuke Drummond // Prints information regarding currently loaded allocations. These details are
312680af0b9eSLuke Drummond // gathered by jitting the runtime, which has as latency. Index parameter
312780af0b9eSLuke Drummond // specifies a single allocation ID to print, or a zero value to print them all
3128b9c1b51eSKate Stone void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3129b9c1b51eSKate Stone                                           const uint32_t index) {
313015f2bd95SEwan Crawford   strm.Printf("RenderScript Allocations:");
313115f2bd95SEwan Crawford   strm.EOL();
313215f2bd95SEwan Crawford   strm.IndentMore();
313315f2bd95SEwan Crawford 
3134b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
3135b649b005SEwan Crawford     // index will only be zero if we want to print all allocations
3136b649b005SEwan Crawford     if (index != 0 && index != alloc->id)
3137b649b005SEwan Crawford       continue;
313815f2bd95SEwan Crawford 
313915f2bd95SEwan Crawford     // JIT current allocation information
314080af0b9eSLuke Drummond     if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3141b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3142b9c1b51eSKate Stone                   alloc->id);
3143b3f7f69dSAidan Dodds       strm.EOL();
314415f2bd95SEwan Crawford       continue;
314515f2bd95SEwan Crawford     }
314615f2bd95SEwan Crawford 
3147b3f7f69dSAidan Dodds     strm.Printf("%" PRIu32 ":", alloc->id);
3148b3f7f69dSAidan Dodds     strm.EOL();
314915f2bd95SEwan Crawford     strm.IndentMore();
315015f2bd95SEwan Crawford 
315115f2bd95SEwan Crawford     strm.Indent("Context: ");
315215f2bd95SEwan Crawford     if (!alloc->context.isValid())
315315f2bd95SEwan Crawford       strm.Printf("unknown\n");
315415f2bd95SEwan Crawford     else
315515f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
315615f2bd95SEwan Crawford 
315715f2bd95SEwan Crawford     strm.Indent("Address: ");
315815f2bd95SEwan Crawford     if (!alloc->address.isValid())
315915f2bd95SEwan Crawford       strm.Printf("unknown\n");
316015f2bd95SEwan Crawford     else
316115f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
316215f2bd95SEwan Crawford 
316315f2bd95SEwan Crawford     strm.Indent("Data pointer: ");
316415f2bd95SEwan Crawford     if (!alloc->data_ptr.isValid())
316515f2bd95SEwan Crawford       strm.Printf("unknown\n");
316615f2bd95SEwan Crawford     else
316715f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
316815f2bd95SEwan Crawford 
316915f2bd95SEwan Crawford     strm.Indent("Dimensions: ");
317015f2bd95SEwan Crawford     if (!alloc->dimension.isValid())
317115f2bd95SEwan Crawford       strm.Printf("unknown\n");
317215f2bd95SEwan Crawford     else
3173b3f7f69dSAidan Dodds       strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3174b9c1b51eSKate Stone                   alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3175b9c1b51eSKate Stone                   alloc->dimension.get()->dim_3);
317615f2bd95SEwan Crawford 
317715f2bd95SEwan Crawford     strm.Indent("Data Type: ");
3178b9c1b51eSKate Stone     if (!alloc->element.type.isValid() ||
3179b9c1b51eSKate Stone         !alloc->element.type_vec_size.isValid())
318015f2bd95SEwan Crawford       strm.Printf("unknown\n");
3181b9c1b51eSKate Stone     else {
31828b244e21SEwan Crawford       const int vector_size = *alloc->element.type_vec_size.get();
31832e920715SEwan Crawford       Element::DataType type = *alloc->element.type.get();
318415f2bd95SEwan Crawford 
31858b244e21SEwan Crawford       if (!alloc->element.type_name.IsEmpty())
31868b244e21SEwan Crawford         strm.Printf("%s\n", alloc->element.type_name.AsCString());
3187b9c1b51eSKate Stone       else {
3188b9c1b51eSKate Stone         // Enum value isn't monotonous, so doesn't always index
3189b9c1b51eSKate Stone         // RsDataTypeToString array
31902e920715SEwan Crawford         if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3191b9c1b51eSKate Stone           type =
3192b9c1b51eSKate Stone               static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3193b3f7f69dSAidan Dodds                                              Element::RS_TYPE_MATRIX_2X2 + 1);
31942e920715SEwan Crawford 
3195b3f7f69dSAidan Dodds         if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3196b3f7f69dSAidan Dodds                      sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3197b3f7f69dSAidan Dodds             vector_size > 4 || vector_size < 1)
319815f2bd95SEwan Crawford           strm.Printf("invalid type\n");
319915f2bd95SEwan Crawford         else
3200b9c1b51eSKate Stone           strm.Printf(
3201b9c1b51eSKate Stone               "%s\n",
3202b9c1b51eSKate Stone               AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3203b3f7f69dSAidan Dodds                                                    [vector_size - 1]);
320415f2bd95SEwan Crawford       }
32052e920715SEwan Crawford     }
320615f2bd95SEwan Crawford 
320715f2bd95SEwan Crawford     strm.Indent("Data Kind: ");
32088b244e21SEwan Crawford     if (!alloc->element.type_kind.isValid())
320915f2bd95SEwan Crawford       strm.Printf("unknown\n");
3210b9c1b51eSKate Stone     else {
32118b244e21SEwan Crawford       const Element::DataKind kind = *alloc->element.type_kind.get();
32128b244e21SEwan Crawford       if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
321315f2bd95SEwan Crawford         strm.Printf("invalid kind\n");
321415f2bd95SEwan Crawford       else
3215b9c1b51eSKate Stone         strm.Printf(
3216b9c1b51eSKate Stone             "%s\n",
3217b9c1b51eSKate Stone             AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
321815f2bd95SEwan Crawford     }
321915f2bd95SEwan Crawford 
322015f2bd95SEwan Crawford     strm.EOL();
322115f2bd95SEwan Crawford     strm.IndentLess();
322215f2bd95SEwan Crawford   }
322315f2bd95SEwan Crawford   strm.IndentLess();
322415f2bd95SEwan Crawford }
322515f2bd95SEwan Crawford 
32267dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
3227b9c1b51eSKate Stone void RenderScriptRuntime::BreakOnModuleKernels(
3228b9c1b51eSKate Stone     const RSModuleDescriptorSP rsmodule_sp) {
3229b9c1b51eSKate Stone   for (const auto &kernel : rsmodule_sp->m_kernels) {
32307dc7771cSEwan Crawford     // Don't set breakpoint on 'root' kernel
32317dc7771cSEwan Crawford     if (strcmp(kernel.m_name.AsCString(), "root") == 0)
32327dc7771cSEwan Crawford       continue;
32337dc7771cSEwan Crawford 
32347dc7771cSEwan Crawford     CreateKernelBreakpoint(kernel.m_name);
32357dc7771cSEwan Crawford   }
32367dc7771cSEwan Crawford }
32377dc7771cSEwan Crawford 
323880af0b9eSLuke Drummond // Method is internally called by the 'kernel breakpoint all' command to enable
323980af0b9eSLuke Drummond // or disable breaking on all kernels. When do_break is true we want to enable
324080af0b9eSLuke Drummond // this functionality. When do_break is false we want to disable it.
3241b9c1b51eSKate Stone void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3242b9c1b51eSKate Stone   Log *log(
3243b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
32447dc7771cSEwan Crawford 
32457dc7771cSEwan Crawford   InitSearchFilter(target);
32467dc7771cSEwan Crawford 
32477dc7771cSEwan Crawford   // Set breakpoints on all the kernels
3248b9c1b51eSKate Stone   if (do_break && !m_breakAllKernels) {
32497dc7771cSEwan Crawford     m_breakAllKernels = true;
32507dc7771cSEwan Crawford 
32517dc7771cSEwan Crawford     for (const auto &module : m_rsmodules)
32527dc7771cSEwan Crawford       BreakOnModuleKernels(module);
32537dc7771cSEwan Crawford 
32547dc7771cSEwan Crawford     if (log)
3255b9c1b51eSKate Stone       log->Printf("%s(True) - breakpoints set on all currently loaded kernels.",
3256b9c1b51eSKate Stone                   __FUNCTION__);
3257b9c1b51eSKate Stone   } else if (!do_break &&
3258b9c1b51eSKate Stone              m_breakAllKernels) // Breakpoints won't be set on any new kernels.
32597dc7771cSEwan Crawford   {
32607dc7771cSEwan Crawford     m_breakAllKernels = false;
32617dc7771cSEwan Crawford 
32627dc7771cSEwan Crawford     if (log)
3263b9c1b51eSKate Stone       log->Printf("%s(False) - breakpoints no longer automatically set.",
3264b9c1b51eSKate Stone                   __FUNCTION__);
32657dc7771cSEwan Crawford   }
32667dc7771cSEwan Crawford }
32677dc7771cSEwan Crawford 
32687dc7771cSEwan Crawford // Given the name of a kernel this function creates a breakpoint using our
32697dc7771cSEwan Crawford // own breakpoint resolver, and returns the Breakpoint shared pointer.
32707dc7771cSEwan Crawford BreakpointSP
3271b9c1b51eSKate Stone RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) {
3272b9c1b51eSKate Stone   Log *log(
3273b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
32747dc7771cSEwan Crawford 
3275b9c1b51eSKate Stone   if (!m_filtersp) {
32767dc7771cSEwan Crawford     if (log)
3277b3f7f69dSAidan Dodds       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
32787dc7771cSEwan Crawford     return nullptr;
32797dc7771cSEwan Crawford   }
32807dc7771cSEwan Crawford 
32817dc7771cSEwan Crawford   BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3282b9c1b51eSKate Stone   BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
3283b9c1b51eSKate Stone       m_filtersp, resolver_sp, false, false, false);
32847dc7771cSEwan Crawford 
3285b9c1b51eSKate Stone   // Give RS breakpoints a specific name, so the user can manipulate them as a
3286b9c1b51eSKate Stone   // group.
328754782db7SEwan Crawford   Error err;
3288*b3bbcb12SLuke Drummond   if (!bp->AddName("RenderScriptKernel", err))
3289*b3bbcb12SLuke Drummond     if (log)
3290*b3bbcb12SLuke Drummond       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3291*b3bbcb12SLuke Drummond                   err.AsCString());
3292*b3bbcb12SLuke Drummond 
3293*b3bbcb12SLuke Drummond   return bp;
3294*b3bbcb12SLuke Drummond }
3295*b3bbcb12SLuke Drummond 
3296*b3bbcb12SLuke Drummond BreakpointSP
3297*b3bbcb12SLuke Drummond RenderScriptRuntime::CreateReductionBreakpoint(const ConstString &name,
3298*b3bbcb12SLuke Drummond                                                int kernel_types) {
3299*b3bbcb12SLuke Drummond   Log *log(
3300*b3bbcb12SLuke Drummond       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3301*b3bbcb12SLuke Drummond 
3302*b3bbcb12SLuke Drummond   if (!m_filtersp) {
3303*b3bbcb12SLuke Drummond     if (log)
3304*b3bbcb12SLuke Drummond       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3305*b3bbcb12SLuke Drummond     return nullptr;
3306*b3bbcb12SLuke Drummond   }
3307*b3bbcb12SLuke Drummond 
3308*b3bbcb12SLuke Drummond   BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3309*b3bbcb12SLuke Drummond       nullptr, name, &m_rsmodules, kernel_types));
3310*b3bbcb12SLuke Drummond   BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
3311*b3bbcb12SLuke Drummond       m_filtersp, resolver_sp, false, false, false);
3312*b3bbcb12SLuke Drummond 
3313*b3bbcb12SLuke Drummond   // Give RS breakpoints a specific name, so the user can manipulate them as a
3314*b3bbcb12SLuke Drummond   // group.
3315*b3bbcb12SLuke Drummond   Error err;
3316*b3bbcb12SLuke Drummond   if (!bp->AddName("RenderScriptReduction", err))
3317*b3bbcb12SLuke Drummond     if (log)
3318b9c1b51eSKate Stone       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3319b9c1b51eSKate Stone                   err.AsCString());
332054782db7SEwan Crawford 
33217dc7771cSEwan Crawford   return bp;
33227dc7771cSEwan Crawford }
33237dc7771cSEwan Crawford 
3324b9c1b51eSKate Stone // Given an expression for a variable this function tries to calculate the
332580af0b9eSLuke Drummond // variable's value. If this is possible it returns true and sets the uint64_t
332680af0b9eSLuke Drummond // parameter to the variables unsigned value. Otherwise function returns false.
3327b9c1b51eSKate Stone bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3328b9c1b51eSKate Stone                                                 const char *var_name,
3329b9c1b51eSKate Stone                                                 uint64_t &val) {
3330018f5a7eSEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
333180af0b9eSLuke Drummond   Error err;
3332018f5a7eSEwan Crawford   VariableSP var_sp;
3333018f5a7eSEwan Crawford 
3334018f5a7eSEwan Crawford   // Find variable in stack frame
3335b3f7f69dSAidan Dodds   ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3336b3f7f69dSAidan Dodds       var_name, eNoDynamicValues,
3337b9c1b51eSKate Stone       StackFrame::eExpressionPathOptionCheckPtrVsMember |
3338b9c1b51eSKate Stone           StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
333980af0b9eSLuke Drummond       var_sp, err));
334080af0b9eSLuke Drummond   if (!err.Success()) {
3341018f5a7eSEwan Crawford     if (log)
3342b9c1b51eSKate Stone       log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__,
3343b9c1b51eSKate Stone                   var_name);
3344018f5a7eSEwan Crawford     return false;
3345018f5a7eSEwan Crawford   }
3346018f5a7eSEwan Crawford 
3347b3f7f69dSAidan Dodds   // Find the uint32_t value for the variable
3348018f5a7eSEwan Crawford   bool success = false;
3349018f5a7eSEwan Crawford   val = value_sp->GetValueAsUnsigned(0, &success);
3350b9c1b51eSKate Stone   if (!success) {
3351018f5a7eSEwan Crawford     if (log)
3352b9c1b51eSKate Stone       log->Printf("%s - error, couldn't parse '%s' as an uint32_t.",
3353b9c1b51eSKate Stone                   __FUNCTION__, var_name);
3354018f5a7eSEwan Crawford     return false;
3355018f5a7eSEwan Crawford   }
3356018f5a7eSEwan Crawford 
3357018f5a7eSEwan Crawford   return true;
3358018f5a7eSEwan Crawford }
3359018f5a7eSEwan Crawford 
3360b9c1b51eSKate Stone // Function attempts to find the current coordinate of a kernel invocation by
336180af0b9eSLuke Drummond // investigating the values of frame variables in the .expand function. These
336280af0b9eSLuke Drummond // coordinates are returned via the coord array reference parameter. Returns
336380af0b9eSLuke Drummond // true if the coordinates could be found, and false otherwise.
3364b9c1b51eSKate Stone bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3365b9c1b51eSKate Stone                                               Thread *thread_ptr) {
336600f56eebSLuke Drummond   static const char *const x_expr = "rsIndex";
336700f56eebSLuke Drummond   static const char *const y_expr = "p->current.y";
336800f56eebSLuke Drummond   static const char *const z_expr = "p->current.z";
33691e05c3bcSGreg Clayton 
33704f8817c2SEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
33714f8817c2SEwan Crawford 
3372b9c1b51eSKate Stone   if (!thread_ptr) {
33734f8817c2SEwan Crawford     if (log)
33744f8817c2SEwan Crawford       log->Printf("%s - Error, No thread pointer", __FUNCTION__);
33754f8817c2SEwan Crawford 
33764f8817c2SEwan Crawford     return false;
33774f8817c2SEwan Crawford   }
33784f8817c2SEwan Crawford 
3379b9c1b51eSKate Stone   // Walk the call stack looking for a function whose name has the suffix
338080af0b9eSLuke Drummond   // '.expand' and contains the variables we're looking for.
3381b9c1b51eSKate Stone   for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
33824f8817c2SEwan Crawford     if (!thread_ptr->SetSelectedFrameByIndex(i))
33834f8817c2SEwan Crawford       continue;
33844f8817c2SEwan Crawford 
33854f8817c2SEwan Crawford     StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
33864f8817c2SEwan Crawford     if (!frame_sp)
33874f8817c2SEwan Crawford       continue;
33884f8817c2SEwan Crawford 
33894f8817c2SEwan Crawford     // Find the function name
33904f8817c2SEwan Crawford     const SymbolContext sym_ctx = frame_sp->GetSymbolContext(false);
339100f56eebSLuke Drummond     const ConstString func_name = sym_ctx.GetFunctionName();
339200f56eebSLuke Drummond     if (!func_name)
33934f8817c2SEwan Crawford       continue;
33944f8817c2SEwan Crawford 
33954f8817c2SEwan Crawford     if (log)
3396b9c1b51eSKate Stone       log->Printf("%s - Inspecting function '%s'", __FUNCTION__,
339700f56eebSLuke Drummond                   func_name.GetCString());
33984f8817c2SEwan Crawford 
33994f8817c2SEwan Crawford     // Check if function name has .expand suffix
340000f56eebSLuke Drummond     if (!func_name.GetStringRef().endswith(".expand"))
34014f8817c2SEwan Crawford       continue;
34024f8817c2SEwan Crawford 
34034f8817c2SEwan Crawford     if (log)
3404b9c1b51eSKate Stone       log->Printf("%s - Found .expand function '%s'", __FUNCTION__,
340500f56eebSLuke Drummond                   func_name.GetCString());
34064f8817c2SEwan Crawford 
3407b9c1b51eSKate Stone     // Get values for variables in .expand frame that tell us the current kernel
3408b9c1b51eSKate Stone     // invocation
340900f56eebSLuke Drummond     uint64_t x, y, z;
341000f56eebSLuke Drummond     bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
341100f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
341200f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, z_expr, z);
34134f8817c2SEwan Crawford 
341400f56eebSLuke Drummond     if (found) {
341500f56eebSLuke Drummond       // The RenderScript runtime uses uint32_t for these vars. If they're not
341600f56eebSLuke Drummond       // within bounds, our frame parsing is garbage
341700f56eebSLuke Drummond       assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
341800f56eebSLuke Drummond       coord.x = (uint32_t)x;
341900f56eebSLuke Drummond       coord.y = (uint32_t)y;
342000f56eebSLuke Drummond       coord.z = (uint32_t)z;
34214f8817c2SEwan Crawford       return true;
34224f8817c2SEwan Crawford     }
342300f56eebSLuke Drummond   }
34244f8817c2SEwan Crawford   return false;
34254f8817c2SEwan Crawford }
34264f8817c2SEwan Crawford 
3427b9c1b51eSKate Stone // Callback when a kernel breakpoint hits and we're looking for a specific
342880af0b9eSLuke Drummond // coordinate. Baton parameter contains a pointer to the target coordinate we
342980af0b9eSLuke Drummond // want to break on.
3430b9c1b51eSKate Stone // Function then checks the .expand frame for the current coordinate and breaks
3431b9c1b51eSKate Stone // to user if it matches.
3432018f5a7eSEwan Crawford // Parameter 'break_id' is the id of the Breakpoint which made the callback.
3433018f5a7eSEwan Crawford // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
3434018f5a7eSEwan Crawford // a single logical breakpoint can have multiple addresses.
3435b9c1b51eSKate Stone bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3436b9c1b51eSKate Stone                                               StoppointCallbackContext *ctx,
3437b9c1b51eSKate Stone                                               user_id_t break_id,
3438b9c1b51eSKate Stone                                               user_id_t break_loc_id) {
3439b9c1b51eSKate Stone   Log *log(
3440b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3441018f5a7eSEwan Crawford 
3442b9c1b51eSKate Stone   assert(baton &&
3443b9c1b51eSKate Stone          "Error: null baton in conditional kernel breakpoint callback");
3444018f5a7eSEwan Crawford 
3445018f5a7eSEwan Crawford   // Coordinate we want to stop on
344600f56eebSLuke Drummond   RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3447018f5a7eSEwan Crawford 
3448018f5a7eSEwan Crawford   if (log)
344900f56eebSLuke Drummond     log->Printf("%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__, break_id,
345000f56eebSLuke Drummond                 target_coord.x, target_coord.y, target_coord.z);
3451018f5a7eSEwan Crawford 
34524f8817c2SEwan Crawford   // Select current thread
3453018f5a7eSEwan Crawford   ExecutionContext context(ctx->exe_ctx_ref);
34544f8817c2SEwan Crawford   Thread *thread_ptr = context.GetThreadPtr();
34554f8817c2SEwan Crawford   assert(thread_ptr && "Null thread pointer");
34564f8817c2SEwan Crawford 
34574f8817c2SEwan Crawford   // Find current kernel invocation from .expand frame variables
345800f56eebSLuke Drummond   RSCoordinate current_coord{};
3459b9c1b51eSKate Stone   if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3460018f5a7eSEwan Crawford     if (log)
3461b9c1b51eSKate Stone       log->Printf("%s - Error, couldn't select .expand stack frame",
3462b9c1b51eSKate Stone                   __FUNCTION__);
3463018f5a7eSEwan Crawford     return false;
3464018f5a7eSEwan Crawford   }
3465018f5a7eSEwan Crawford 
3466018f5a7eSEwan Crawford   if (log)
346700f56eebSLuke Drummond     log->Printf("%s - " FMT_COORD, __FUNCTION__, current_coord.x,
346800f56eebSLuke Drummond                 current_coord.y, current_coord.z);
3469018f5a7eSEwan Crawford 
3470b9c1b51eSKate Stone   // Check if the current kernel invocation coordinate matches our target
3471b9c1b51eSKate Stone   // coordinate
347200f56eebSLuke Drummond   if (target_coord == current_coord) {
3473018f5a7eSEwan Crawford     if (log)
347400f56eebSLuke Drummond       log->Printf("%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
347500f56eebSLuke Drummond                   current_coord.y, current_coord.z);
3476018f5a7eSEwan Crawford 
3477b9c1b51eSKate Stone     BreakpointSP breakpoint_sp =
3478b9c1b51eSKate Stone         context.GetTargetPtr()->GetBreakpointByID(break_id);
3479b9c1b51eSKate Stone     assert(breakpoint_sp != nullptr &&
3480b9c1b51eSKate Stone            "Error: Couldn't find breakpoint matching break id for callback");
3481b9c1b51eSKate Stone     breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3482b9c1b51eSKate Stone                                       // should only be hit once.
3483018f5a7eSEwan Crawford     return true;
3484018f5a7eSEwan Crawford   }
3485018f5a7eSEwan Crawford 
3486018f5a7eSEwan Crawford   // No match on coordinate
3487018f5a7eSEwan Crawford   return false;
3488018f5a7eSEwan Crawford }
3489018f5a7eSEwan Crawford 
349000f56eebSLuke Drummond void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
349100f56eebSLuke Drummond                                          const RSCoordinate &coord) {
349200f56eebSLuke Drummond   messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
349300f56eebSLuke Drummond                   coord.x, coord.y, coord.z);
349400f56eebSLuke Drummond   messages.EOL();
349500f56eebSLuke Drummond 
349600f56eebSLuke Drummond   // Allocate memory for the baton, and copy over coordinate
349700f56eebSLuke Drummond   RSCoordinate *baton = new RSCoordinate(coord);
349800f56eebSLuke Drummond 
349900f56eebSLuke Drummond   // Create a callback that will be invoked every time the breakpoint is hit.
350000f56eebSLuke Drummond   // The baton object passed to the handler is the target coordinate we want to
350100f56eebSLuke Drummond   // break on.
350200f56eebSLuke Drummond   bp->SetCallback(KernelBreakpointHit, baton, true);
350300f56eebSLuke Drummond 
350400f56eebSLuke Drummond   // Store a shared pointer to the baton, so the memory will eventually be
350500f56eebSLuke Drummond   // cleaned up after destruction
350600f56eebSLuke Drummond   m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
350700f56eebSLuke Drummond }
350800f56eebSLuke Drummond 
3509b9c1b51eSKate Stone // Tries to set a breakpoint on the start of a kernel, resolved using the kernel
351080af0b9eSLuke Drummond // name. Argument 'coords', represents a three dimensional coordinate which can
351180af0b9eSLuke Drummond // be
351280af0b9eSLuke Drummond // used to specify a single kernel instance to break on. If this is set then we
351380af0b9eSLuke Drummond // add a callback
3514b9c1b51eSKate Stone // to the breakpoint.
351500f56eebSLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
351600f56eebSLuke Drummond                                                   Stream &messages,
351700f56eebSLuke Drummond                                                   const char *name,
351800f56eebSLuke Drummond                                                   const RSCoordinate *coord) {
351900f56eebSLuke Drummond   if (!name)
352000f56eebSLuke Drummond     return false;
35214640cde1SColin Riley 
35227dc7771cSEwan Crawford   InitSearchFilter(target);
352398156583SEwan Crawford 
35244640cde1SColin Riley   ConstString kernel_name(name);
35257dc7771cSEwan Crawford   BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
352600f56eebSLuke Drummond   if (!bp)
352700f56eebSLuke Drummond     return false;
3528018f5a7eSEwan Crawford 
3529018f5a7eSEwan Crawford   // We have a conditional breakpoint on a specific coordinate
353000f56eebSLuke Drummond   if (coord)
353100f56eebSLuke Drummond     SetConditional(bp, messages, *coord);
3532018f5a7eSEwan Crawford 
353300f56eebSLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3534018f5a7eSEwan Crawford 
353500f56eebSLuke Drummond   return true;
35364640cde1SColin Riley }
35374640cde1SColin Riley 
3538*b3bbcb12SLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3539*b3bbcb12SLuke Drummond                                                      Stream &messages,
3540*b3bbcb12SLuke Drummond                                                      const char *reduce_name,
3541*b3bbcb12SLuke Drummond                                                      const RSCoordinate *coord,
3542*b3bbcb12SLuke Drummond                                                      int kernel_types) {
3543*b3bbcb12SLuke Drummond   if (!reduce_name)
3544*b3bbcb12SLuke Drummond     return false;
3545*b3bbcb12SLuke Drummond 
3546*b3bbcb12SLuke Drummond   InitSearchFilter(target);
3547*b3bbcb12SLuke Drummond   BreakpointSP bp =
3548*b3bbcb12SLuke Drummond       CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3549*b3bbcb12SLuke Drummond   if (!bp)
3550*b3bbcb12SLuke Drummond     return false;
3551*b3bbcb12SLuke Drummond 
3552*b3bbcb12SLuke Drummond   if (coord)
3553*b3bbcb12SLuke Drummond     SetConditional(bp, messages, *coord);
3554*b3bbcb12SLuke Drummond 
3555*b3bbcb12SLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3556*b3bbcb12SLuke Drummond 
3557*b3bbcb12SLuke Drummond   return true;
3558*b3bbcb12SLuke Drummond }
3559*b3bbcb12SLuke Drummond 
3560b9c1b51eSKate Stone void RenderScriptRuntime::DumpModules(Stream &strm) const {
35615ec532a9SColin Riley   strm.Printf("RenderScript Modules:");
35625ec532a9SColin Riley   strm.EOL();
35635ec532a9SColin Riley   strm.IndentMore();
3564b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
35654640cde1SColin Riley     module->Dump(strm);
35665ec532a9SColin Riley   }
35675ec532a9SColin Riley   strm.IndentLess();
35685ec532a9SColin Riley }
35695ec532a9SColin Riley 
357078f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails *
3571b9c1b51eSKate Stone RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3572b9c1b51eSKate Stone   for (const auto &s : m_scripts) {
357378f339d1SEwan Crawford     if (s->script.isValid())
357478f339d1SEwan Crawford       if (*s->script == address)
357578f339d1SEwan Crawford         return s.get();
357678f339d1SEwan Crawford   }
3577b9c1b51eSKate Stone   if (create) {
357878f339d1SEwan Crawford     std::unique_ptr<ScriptDetails> s(new ScriptDetails);
357978f339d1SEwan Crawford     s->script = address;
358078f339d1SEwan Crawford     m_scripts.push_back(std::move(s));
3581d10ca9deSEwan Crawford     return m_scripts.back().get();
358278f339d1SEwan Crawford   }
358378f339d1SEwan Crawford   return nullptr;
358478f339d1SEwan Crawford }
358578f339d1SEwan Crawford 
358678f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails *
3587b9c1b51eSKate Stone RenderScriptRuntime::LookUpAllocation(addr_t address) {
3588b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
358978f339d1SEwan Crawford     if (a->address.isValid())
359078f339d1SEwan Crawford       if (*a->address == address)
359178f339d1SEwan Crawford         return a.get();
359278f339d1SEwan Crawford   }
35935d057637SLuke Drummond   return nullptr;
35945d057637SLuke Drummond }
35955d057637SLuke Drummond 
35965d057637SLuke Drummond RenderScriptRuntime::AllocationDetails *
3597b9c1b51eSKate Stone RenderScriptRuntime::CreateAllocation(addr_t address) {
35985d057637SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
35995d057637SLuke Drummond 
36005d057637SLuke Drummond   // Remove any previous allocation which contains the same address
36015d057637SLuke Drummond   auto it = m_allocations.begin();
3602b9c1b51eSKate Stone   while (it != m_allocations.end()) {
3603b9c1b51eSKate Stone     if (*((*it)->address) == address) {
36045d057637SLuke Drummond       if (log)
3605b9c1b51eSKate Stone         log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64,
3606b9c1b51eSKate Stone                     __FUNCTION__, (*it)->id, address);
36075d057637SLuke Drummond 
36085d057637SLuke Drummond       it = m_allocations.erase(it);
3609b9c1b51eSKate Stone     } else {
36105d057637SLuke Drummond       it++;
36115d057637SLuke Drummond     }
36125d057637SLuke Drummond   }
36135d057637SLuke Drummond 
361478f339d1SEwan Crawford   std::unique_ptr<AllocationDetails> a(new AllocationDetails);
361578f339d1SEwan Crawford   a->address = address;
361678f339d1SEwan Crawford   m_allocations.push_back(std::move(a));
3617d10ca9deSEwan Crawford   return m_allocations.back().get();
361878f339d1SEwan Crawford }
361978f339d1SEwan Crawford 
3620b9c1b51eSKate Stone void RSModuleDescriptor::Dump(Stream &strm) const {
36217f193d69SLuke Drummond   int indent = strm.GetIndentLevel();
36227f193d69SLuke Drummond 
36235ec532a9SColin Riley   strm.Indent();
36245ec532a9SColin Riley   m_module->GetFileSpec().Dump(&strm);
36257f193d69SLuke Drummond   strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
36267f193d69SLuke Drummond                                              : "Debug info does not exist.");
36275ec532a9SColin Riley   strm.EOL();
36285ec532a9SColin Riley   strm.IndentMore();
36297f193d69SLuke Drummond 
36305ec532a9SColin Riley   strm.Indent();
3631189598edSColin Riley   strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
36325ec532a9SColin Riley   strm.EOL();
36335ec532a9SColin Riley   strm.IndentMore();
3634b9c1b51eSKate Stone   for (const auto &global : m_globals) {
36355ec532a9SColin Riley     global.Dump(strm);
36365ec532a9SColin Riley   }
36375ec532a9SColin Riley   strm.IndentLess();
36387f193d69SLuke Drummond 
36395ec532a9SColin Riley   strm.Indent();
3640189598edSColin Riley   strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
36415ec532a9SColin Riley   strm.EOL();
36425ec532a9SColin Riley   strm.IndentMore();
3643b9c1b51eSKate Stone   for (const auto &kernel : m_kernels) {
36445ec532a9SColin Riley     kernel.Dump(strm);
36455ec532a9SColin Riley   }
36467f193d69SLuke Drummond   strm.IndentLess();
36477f193d69SLuke Drummond 
36487f193d69SLuke Drummond   strm.Indent();
36494640cde1SColin Riley   strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
36504640cde1SColin Riley   strm.EOL();
36514640cde1SColin Riley   strm.IndentMore();
3652b9c1b51eSKate Stone   for (const auto &key_val : m_pragmas) {
36537f193d69SLuke Drummond     strm.Indent();
36544640cde1SColin Riley     strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
36554640cde1SColin Riley     strm.EOL();
36564640cde1SColin Riley   }
36577f193d69SLuke Drummond   strm.IndentLess();
36587f193d69SLuke Drummond 
36597f193d69SLuke Drummond   strm.Indent();
36607f193d69SLuke Drummond   strm.Printf("Reductions: %" PRIu64,
36617f193d69SLuke Drummond               static_cast<uint64_t>(m_reductions.size()));
36627f193d69SLuke Drummond   strm.EOL();
36637f193d69SLuke Drummond   strm.IndentMore();
36647f193d69SLuke Drummond   for (const auto &reduction : m_reductions) {
36657f193d69SLuke Drummond     reduction.Dump(strm);
36667f193d69SLuke Drummond   }
36677f193d69SLuke Drummond 
36687f193d69SLuke Drummond   strm.SetIndentLevel(indent);
36695ec532a9SColin Riley }
36705ec532a9SColin Riley 
3671b9c1b51eSKate Stone void RSGlobalDescriptor::Dump(Stream &strm) const {
36725ec532a9SColin Riley   strm.Indent(m_name.AsCString());
36734640cde1SColin Riley   VariableList var_list;
36744640cde1SColin Riley   m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
3675b9c1b51eSKate Stone   if (var_list.GetSize() == 1) {
36764640cde1SColin Riley     auto var = var_list.GetVariableAtIndex(0);
36774640cde1SColin Riley     auto type = var->GetType();
3678b9c1b51eSKate Stone     if (type) {
36794640cde1SColin Riley       strm.Printf(" - ");
36804640cde1SColin Riley       type->DumpTypeName(&strm);
3681b9c1b51eSKate Stone     } else {
36824640cde1SColin Riley       strm.Printf(" - Unknown Type");
36834640cde1SColin Riley     }
3684b9c1b51eSKate Stone   } else {
36854640cde1SColin Riley     strm.Printf(" - variable identified, but not found in binary");
3686b9c1b51eSKate Stone     const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
3687b9c1b51eSKate Stone         m_name, eSymbolTypeData);
3688b9c1b51eSKate Stone     if (s) {
36894640cde1SColin Riley       strm.Printf(" (symbol exists) ");
36904640cde1SColin Riley     }
36914640cde1SColin Riley   }
36924640cde1SColin Riley 
36935ec532a9SColin Riley   strm.EOL();
36945ec532a9SColin Riley }
36955ec532a9SColin Riley 
3696b9c1b51eSKate Stone void RSKernelDescriptor::Dump(Stream &strm) const {
36975ec532a9SColin Riley   strm.Indent(m_name.AsCString());
36985ec532a9SColin Riley   strm.EOL();
36995ec532a9SColin Riley }
37005ec532a9SColin Riley 
37017f193d69SLuke Drummond void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
37027f193d69SLuke Drummond   stream.Indent(m_reduce_name.AsCString());
37037f193d69SLuke Drummond   stream.IndentMore();
37047f193d69SLuke Drummond   stream.EOL();
37057f193d69SLuke Drummond   stream.Indent();
37067f193d69SLuke Drummond   stream.Printf("accumulator: %s", m_accum_name.AsCString());
37077f193d69SLuke Drummond   stream.EOL();
37087f193d69SLuke Drummond   stream.Indent();
37097f193d69SLuke Drummond   stream.Printf("initializer: %s", m_init_name.AsCString());
37107f193d69SLuke Drummond   stream.EOL();
37117f193d69SLuke Drummond   stream.Indent();
37127f193d69SLuke Drummond   stream.Printf("combiner: %s", m_comb_name.AsCString());
37137f193d69SLuke Drummond   stream.EOL();
37147f193d69SLuke Drummond   stream.Indent();
37157f193d69SLuke Drummond   stream.Printf("outconverter: %s", m_outc_name.AsCString());
37167f193d69SLuke Drummond   stream.EOL();
37177f193d69SLuke Drummond   // XXX This is currently unspecified by RenderScript, and unused
37187f193d69SLuke Drummond   // stream.Indent();
37197f193d69SLuke Drummond   // stream.Printf("halter: '%s'", m_init_name.AsCString());
37207f193d69SLuke Drummond   // stream.EOL();
37217f193d69SLuke Drummond   stream.IndentLess();
37227f193d69SLuke Drummond }
37237f193d69SLuke Drummond 
3724b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
37255ec532a9SColin Riley public:
37265ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
3727b9c1b51eSKate Stone       : CommandObjectParsed(
3728b9c1b51eSKate Stone             interpreter, "renderscript module dump",
3729b9c1b51eSKate Stone             "Dumps renderscript specific information for all modules.",
3730b9c1b51eSKate Stone             "renderscript module dump",
3731b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
37325ec532a9SColin Riley 
3733222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
37345ec532a9SColin Riley 
3735b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
37365ec532a9SColin Riley     RenderScriptRuntime *runtime =
3737b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
3738b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
37395ec532a9SColin Riley     runtime->DumpModules(result.GetOutputStream());
37405ec532a9SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
37415ec532a9SColin Riley     return true;
37425ec532a9SColin Riley   }
37435ec532a9SColin Riley };
37445ec532a9SColin Riley 
3745b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
37465ec532a9SColin Riley public:
37475ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
3748b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript module",
3749b9c1b51eSKate Stone                                "Commands that deal with RenderScript modules.",
3750b9c1b51eSKate Stone                                nullptr) {
3751b9c1b51eSKate Stone     LoadSubCommand(
3752b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
3753b9c1b51eSKate Stone                     interpreter)));
37545ec532a9SColin Riley   }
37555ec532a9SColin Riley 
3756222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModule() override = default;
37575ec532a9SColin Riley };
37585ec532a9SColin Riley 
3759b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
37604640cde1SColin Riley public:
37614640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
3762b9c1b51eSKate Stone       : CommandObjectParsed(
3763b9c1b51eSKate Stone             interpreter, "renderscript kernel list",
3764b3f7f69dSAidan Dodds             "Lists renderscript kernel names and associated script resources.",
3765b9c1b51eSKate Stone             "renderscript kernel list",
3766b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
37674640cde1SColin Riley 
3768222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelList() override = default;
37694640cde1SColin Riley 
3770b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
37714640cde1SColin Riley     RenderScriptRuntime *runtime =
3772b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
3773b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
37744640cde1SColin Riley     runtime->DumpKernels(result.GetOutputStream());
37754640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
37764640cde1SColin Riley     return true;
37774640cde1SColin Riley   }
37784640cde1SColin Riley };
37794640cde1SColin Riley 
3780*b3bbcb12SLuke Drummond static OptionDefinition g_renderscript_reduction_bp_set_options[] = {
3781*b3bbcb12SLuke Drummond     {LLDB_OPT_SET_1, false, "function-role", 't',
3782*b3bbcb12SLuke Drummond      OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOneLiner,
3783*b3bbcb12SLuke Drummond      "Break on a comma separated set of reduction kernel types "
3784*b3bbcb12SLuke Drummond      "(accumulator,outcoverter,combiner,initializer"},
3785*b3bbcb12SLuke Drummond     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
3786*b3bbcb12SLuke Drummond      nullptr, nullptr, 0, eArgTypeValue,
3787*b3bbcb12SLuke Drummond      "Set a breakpoint on a single invocation of the kernel with specified "
3788*b3bbcb12SLuke Drummond      "coordinate.\n"
3789*b3bbcb12SLuke Drummond      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
3790*b3bbcb12SLuke Drummond      "integers representing kernel dimensions. "
3791*b3bbcb12SLuke Drummond      "Any unset dimensions will be defaulted to zero."}};
3792*b3bbcb12SLuke Drummond 
3793*b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReductionBreakpointSet
3794*b3bbcb12SLuke Drummond     : public CommandObjectParsed {
3795*b3bbcb12SLuke Drummond public:
3796*b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReductionBreakpointSet(
3797*b3bbcb12SLuke Drummond       CommandInterpreter &interpreter)
3798*b3bbcb12SLuke Drummond       : CommandObjectParsed(
3799*b3bbcb12SLuke Drummond             interpreter, "renderscript reduction breakpoint set",
3800*b3bbcb12SLuke Drummond             "Set a breakpoint on named RenderScript general reductions",
3801*b3bbcb12SLuke Drummond             "renderscript reduction breakpoint set  <kernel_name> [-t "
3802*b3bbcb12SLuke Drummond             "<reduction_kernel_type,...>]",
3803*b3bbcb12SLuke Drummond             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
3804*b3bbcb12SLuke Drummond                 eCommandProcessMustBePaused),
3805*b3bbcb12SLuke Drummond         m_options(){};
3806*b3bbcb12SLuke Drummond 
3807*b3bbcb12SLuke Drummond   class CommandOptions : public Options {
3808*b3bbcb12SLuke Drummond   public:
3809*b3bbcb12SLuke Drummond     CommandOptions()
3810*b3bbcb12SLuke Drummond         : Options(),
3811*b3bbcb12SLuke Drummond           m_kernel_types(RSReduceBreakpointResolver::eKernelTypeAll) {}
3812*b3bbcb12SLuke Drummond 
3813*b3bbcb12SLuke Drummond     ~CommandOptions() override = default;
3814*b3bbcb12SLuke Drummond 
3815*b3bbcb12SLuke Drummond     Error SetOptionValue(uint32_t option_idx, const char *option_val,
3816*b3bbcb12SLuke Drummond                          ExecutionContext *exe_ctx) override {
3817*b3bbcb12SLuke Drummond       Error err;
3818*b3bbcb12SLuke Drummond       StreamString err_str;
3819*b3bbcb12SLuke Drummond       const int short_option = m_getopt_table[option_idx].val;
3820*b3bbcb12SLuke Drummond       switch (short_option) {
3821*b3bbcb12SLuke Drummond       case 't':
3822*b3bbcb12SLuke Drummond         if (!ParseReductionTypes(option_val, err_str))
3823*b3bbcb12SLuke Drummond           err.SetErrorStringWithFormat(
3824*b3bbcb12SLuke Drummond               "Unable to deduce reduction types for %s: %s", option_val,
3825*b3bbcb12SLuke Drummond               err_str.GetData());
3826*b3bbcb12SLuke Drummond         break;
3827*b3bbcb12SLuke Drummond       case 'c': {
3828*b3bbcb12SLuke Drummond         auto coord = RSCoordinate{};
3829*b3bbcb12SLuke Drummond         if (!ParseCoordinate(option_val, coord))
3830*b3bbcb12SLuke Drummond           err.SetErrorStringWithFormat("unable to parse coordinate for %s",
3831*b3bbcb12SLuke Drummond                                        option_val);
3832*b3bbcb12SLuke Drummond         else {
3833*b3bbcb12SLuke Drummond           m_have_coord = true;
3834*b3bbcb12SLuke Drummond           m_coord = coord;
3835*b3bbcb12SLuke Drummond         }
3836*b3bbcb12SLuke Drummond         break;
3837*b3bbcb12SLuke Drummond       }
3838*b3bbcb12SLuke Drummond       default:
3839*b3bbcb12SLuke Drummond         err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
3840*b3bbcb12SLuke Drummond       }
3841*b3bbcb12SLuke Drummond       return err;
3842*b3bbcb12SLuke Drummond     }
3843*b3bbcb12SLuke Drummond 
3844*b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
3845*b3bbcb12SLuke Drummond       m_have_coord = false;
3846*b3bbcb12SLuke Drummond     }
3847*b3bbcb12SLuke Drummond 
3848*b3bbcb12SLuke Drummond     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
3849*b3bbcb12SLuke Drummond       return llvm::makeArrayRef(g_renderscript_reduction_bp_set_options);
3850*b3bbcb12SLuke Drummond     }
3851*b3bbcb12SLuke Drummond 
3852*b3bbcb12SLuke Drummond     bool ParseReductionTypes(const char *option_val, StreamString &err_str) {
3853*b3bbcb12SLuke Drummond       m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
3854*b3bbcb12SLuke Drummond       const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
3855*b3bbcb12SLuke Drummond         return llvm::StringSwitch<int>(name)
3856*b3bbcb12SLuke Drummond             .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
3857*b3bbcb12SLuke Drummond             .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
3858*b3bbcb12SLuke Drummond             .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
3859*b3bbcb12SLuke Drummond             .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
3860*b3bbcb12SLuke Drummond             .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
3861*b3bbcb12SLuke Drummond             // Currently not exposed by the runtime
3862*b3bbcb12SLuke Drummond             // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
3863*b3bbcb12SLuke Drummond             .Default(0);
3864*b3bbcb12SLuke Drummond       };
3865*b3bbcb12SLuke Drummond 
3866*b3bbcb12SLuke Drummond       // Matching a comma separated list of known words is fairly
3867*b3bbcb12SLuke Drummond       // straightforward with PCRE, but we're
3868*b3bbcb12SLuke Drummond       // using ERE, so we end up with a little ugliness...
3869*b3bbcb12SLuke Drummond       RegularExpression::Match match(/* max_matches */ 5);
3870*b3bbcb12SLuke Drummond       RegularExpression match_type_list(
3871*b3bbcb12SLuke Drummond           llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
3872*b3bbcb12SLuke Drummond 
3873*b3bbcb12SLuke Drummond       assert(match_type_list.IsValid());
3874*b3bbcb12SLuke Drummond 
3875*b3bbcb12SLuke Drummond       if (!match_type_list.Execute(llvm::StringRef(option_val), &match)) {
3876*b3bbcb12SLuke Drummond         err_str.PutCString(
3877*b3bbcb12SLuke Drummond             "a comma-separated list of kernel types is required");
3878*b3bbcb12SLuke Drummond         return false;
3879*b3bbcb12SLuke Drummond       }
3880*b3bbcb12SLuke Drummond 
3881*b3bbcb12SLuke Drummond       // splitting on commas is much easier with llvm::StringRef than regex
3882*b3bbcb12SLuke Drummond       llvm::SmallVector<llvm::StringRef, 5> type_names;
3883*b3bbcb12SLuke Drummond       llvm::StringRef(option_val).split(type_names, ',');
3884*b3bbcb12SLuke Drummond 
3885*b3bbcb12SLuke Drummond       for (const auto &name : type_names) {
3886*b3bbcb12SLuke Drummond         const int type = reduce_name_to_type(name);
3887*b3bbcb12SLuke Drummond         if (!type) {
3888*b3bbcb12SLuke Drummond           err_str.Printf("unknown kernel type name %s", name.str().c_str());
3889*b3bbcb12SLuke Drummond           return false;
3890*b3bbcb12SLuke Drummond         }
3891*b3bbcb12SLuke Drummond         m_kernel_types |= type;
3892*b3bbcb12SLuke Drummond       }
3893*b3bbcb12SLuke Drummond 
3894*b3bbcb12SLuke Drummond       return true;
3895*b3bbcb12SLuke Drummond     }
3896*b3bbcb12SLuke Drummond 
3897*b3bbcb12SLuke Drummond     int m_kernel_types;
3898*b3bbcb12SLuke Drummond     llvm::StringRef m_reduce_name;
3899*b3bbcb12SLuke Drummond     RSCoordinate m_coord;
3900*b3bbcb12SLuke Drummond     bool m_have_coord;
3901*b3bbcb12SLuke Drummond   };
3902*b3bbcb12SLuke Drummond 
3903*b3bbcb12SLuke Drummond   Options *GetOptions() override { return &m_options; }
3904*b3bbcb12SLuke Drummond 
3905*b3bbcb12SLuke Drummond   bool DoExecute(Args &command, CommandReturnObject &result) override {
3906*b3bbcb12SLuke Drummond     const size_t argc = command.GetArgumentCount();
3907*b3bbcb12SLuke Drummond     if (argc < 1) {
3908*b3bbcb12SLuke Drummond       result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
3909*b3bbcb12SLuke Drummond                                    "and an optional kernel type list",
3910*b3bbcb12SLuke Drummond                                    m_cmd_name.c_str());
3911*b3bbcb12SLuke Drummond       result.SetStatus(eReturnStatusFailed);
3912*b3bbcb12SLuke Drummond       return false;
3913*b3bbcb12SLuke Drummond     }
3914*b3bbcb12SLuke Drummond 
3915*b3bbcb12SLuke Drummond     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
3916*b3bbcb12SLuke Drummond         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
3917*b3bbcb12SLuke Drummond             eLanguageTypeExtRenderScript));
3918*b3bbcb12SLuke Drummond 
3919*b3bbcb12SLuke Drummond     auto &outstream = result.GetOutputStream();
3920*b3bbcb12SLuke Drummond     auto name = command.GetArgumentAtIndex(0);
3921*b3bbcb12SLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
3922*b3bbcb12SLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
3923*b3bbcb12SLuke Drummond     if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
3924*b3bbcb12SLuke Drummond                                              m_options.m_kernel_types)) {
3925*b3bbcb12SLuke Drummond       result.SetStatus(eReturnStatusFailed);
3926*b3bbcb12SLuke Drummond       result.AppendError("Error: unable to place breakpoint on reduction");
3927*b3bbcb12SLuke Drummond       return false;
3928*b3bbcb12SLuke Drummond     }
3929*b3bbcb12SLuke Drummond     result.AppendMessage("Breakpoint(s) created");
3930*b3bbcb12SLuke Drummond     result.SetStatus(eReturnStatusSuccessFinishResult);
3931*b3bbcb12SLuke Drummond     return true;
3932*b3bbcb12SLuke Drummond   }
3933*b3bbcb12SLuke Drummond 
3934*b3bbcb12SLuke Drummond private:
3935*b3bbcb12SLuke Drummond   CommandOptions m_options;
3936*b3bbcb12SLuke Drummond };
3937*b3bbcb12SLuke Drummond 
39381f0f5b5bSZachary Turner static OptionDefinition g_renderscript_kernel_bp_set_options[] = {
39391f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
39401f0f5b5bSZachary Turner      nullptr, nullptr, 0, eArgTypeValue,
39411f0f5b5bSZachary Turner      "Set a breakpoint on a single invocation of the kernel with specified "
39421f0f5b5bSZachary Turner      "coordinate.\n"
39431f0f5b5bSZachary Turner      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
39441f0f5b5bSZachary Turner      "integers representing kernel dimensions. "
39451f0f5b5bSZachary Turner      "Any unset dimensions will be defaulted to zero."}};
39461f0f5b5bSZachary Turner 
3947b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointSet
3948b9c1b51eSKate Stone     : public CommandObjectParsed {
39494640cde1SColin Riley public:
3950b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointSet(
3951b9c1b51eSKate Stone       CommandInterpreter &interpreter)
3952b9c1b51eSKate Stone       : CommandObjectParsed(
3953b9c1b51eSKate Stone             interpreter, "renderscript kernel breakpoint set",
3954b3f7f69dSAidan Dodds             "Sets a breakpoint on a renderscript kernel.",
3955b3f7f69dSAidan Dodds             "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
3956b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
3957b9c1b51eSKate Stone                 eCommandProcessMustBePaused),
3958b9c1b51eSKate Stone         m_options() {}
39594640cde1SColin Riley 
3960222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
3961222b937cSEugene Zelenko 
3962b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
3963018f5a7eSEwan Crawford 
3964b9c1b51eSKate Stone   class CommandOptions : public Options {
3965018f5a7eSEwan Crawford   public:
3966e1cfbc79STodd Fiala     CommandOptions() : Options() {}
3967018f5a7eSEwan Crawford 
3968222b937cSEugene Zelenko     ~CommandOptions() override = default;
3969018f5a7eSEwan Crawford 
3970b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
3971*b3bbcb12SLuke Drummond                          ExecutionContext *exe_ctx) override {
397280af0b9eSLuke Drummond       Error err;
3973018f5a7eSEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
3974018f5a7eSEwan Crawford 
3975b9c1b51eSKate Stone       switch (short_option) {
397600f56eebSLuke Drummond       case 'c': {
397700f56eebSLuke Drummond         auto coord = RSCoordinate{};
397800f56eebSLuke Drummond         if (!ParseCoordinate(option_arg, coord))
397980af0b9eSLuke Drummond           err.SetErrorStringWithFormat(
3980b9c1b51eSKate Stone               "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
3981b3f7f69dSAidan Dodds               option_arg);
398200f56eebSLuke Drummond         else {
398300f56eebSLuke Drummond           m_have_coord = true;
398400f56eebSLuke Drummond           m_coord = coord;
398500f56eebSLuke Drummond         }
3986018f5a7eSEwan Crawford         break;
398700f56eebSLuke Drummond       }
3988018f5a7eSEwan Crawford       default:
398980af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3990018f5a7eSEwan Crawford         break;
3991018f5a7eSEwan Crawford       }
399280af0b9eSLuke Drummond       return err;
3993018f5a7eSEwan Crawford     }
3994018f5a7eSEwan Crawford 
3995*b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
399600f56eebSLuke Drummond       m_have_coord = false;
3997018f5a7eSEwan Crawford     }
3998018f5a7eSEwan Crawford 
39991f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
400070602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
40011f0f5b5bSZachary Turner     }
4002018f5a7eSEwan Crawford 
400300f56eebSLuke Drummond     RSCoordinate m_coord;
400400f56eebSLuke Drummond     bool m_have_coord;
4005018f5a7eSEwan Crawford   };
4006018f5a7eSEwan Crawford 
4007b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
40084640cde1SColin Riley     const size_t argc = command.GetArgumentCount();
4009b9c1b51eSKate Stone     if (argc < 1) {
4010b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4011b9c1b51eSKate Stone           "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4012b3f7f69dSAidan Dodds           m_cmd_name.c_str());
4013018f5a7eSEwan Crawford       result.SetStatus(eReturnStatusFailed);
4014018f5a7eSEwan Crawford       return false;
4015018f5a7eSEwan Crawford     }
4016018f5a7eSEwan Crawford 
40174640cde1SColin Riley     RenderScriptRuntime *runtime =
4018b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4019b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
40204640cde1SColin Riley 
402100f56eebSLuke Drummond     auto &outstream = result.GetOutputStream();
402200f56eebSLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
402300f56eebSLuke Drummond     auto name = command.GetArgumentAtIndex(0);
402400f56eebSLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
402500f56eebSLuke Drummond     if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
402600f56eebSLuke Drummond       result.SetStatus(eReturnStatusFailed);
402700f56eebSLuke Drummond       result.AppendErrorWithFormat(
402800f56eebSLuke Drummond           "Error: unable to set breakpoint on kernel '%s'", name);
402900f56eebSLuke Drummond       return false;
403000f56eebSLuke Drummond     }
40314640cde1SColin Riley 
40324640cde1SColin Riley     result.AppendMessage("Breakpoint(s) created");
40334640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
40344640cde1SColin Riley     return true;
40354640cde1SColin Riley   }
40364640cde1SColin Riley 
4037018f5a7eSEwan Crawford private:
4038018f5a7eSEwan Crawford   CommandOptions m_options;
40394640cde1SColin Riley };
40404640cde1SColin Riley 
4041b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4042b9c1b51eSKate Stone     : public CommandObjectParsed {
40437dc7771cSEwan Crawford public:
4044b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4045b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4046b3f7f69dSAidan Dodds       : CommandObjectParsed(
4047b3f7f69dSAidan Dodds             interpreter, "renderscript kernel breakpoint all",
4048b9c1b51eSKate Stone             "Automatically sets a breakpoint on all renderscript kernels that "
4049b9c1b51eSKate Stone             "are or will be loaded.\n"
4050b9c1b51eSKate Stone             "Disabling option means breakpoints will no longer be set on any "
4051b9c1b51eSKate Stone             "kernels loaded in the future, "
40527dc7771cSEwan Crawford             "but does not remove currently set breakpoints.",
40537dc7771cSEwan Crawford             "renderscript kernel breakpoint all <enable/disable>",
4054b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4055b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
40567dc7771cSEwan Crawford 
4057222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
40587dc7771cSEwan Crawford 
4059b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
40607dc7771cSEwan Crawford     const size_t argc = command.GetArgumentCount();
4061b9c1b51eSKate Stone     if (argc != 1) {
4062b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4063b9c1b51eSKate Stone           "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
40647dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
40657dc7771cSEwan Crawford       return false;
40667dc7771cSEwan Crawford     }
40677dc7771cSEwan Crawford 
4068b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4069b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4070b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
40717dc7771cSEwan Crawford 
40727dc7771cSEwan Crawford     bool do_break = false;
40737dc7771cSEwan Crawford     const char *argument = command.GetArgumentAtIndex(0);
4074b9c1b51eSKate Stone     if (strcmp(argument, "enable") == 0) {
40757dc7771cSEwan Crawford       do_break = true;
40767dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will be set on all kernels.");
4077b9c1b51eSKate Stone     } else if (strcmp(argument, "disable") == 0) {
40787dc7771cSEwan Crawford       do_break = false;
40797dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will not be set on any new kernels.");
4080b9c1b51eSKate Stone     } else {
4081b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4082b9c1b51eSKate Stone           "Argument must be either 'enable' or 'disable'");
40837dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
40847dc7771cSEwan Crawford       return false;
40857dc7771cSEwan Crawford     }
40867dc7771cSEwan Crawford 
40877dc7771cSEwan Crawford     runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
40887dc7771cSEwan Crawford 
40897dc7771cSEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
40907dc7771cSEwan Crawford     return true;
40917dc7771cSEwan Crawford   }
40927dc7771cSEwan Crawford };
40937dc7771cSEwan Crawford 
4094*b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReductionBreakpoint
4095*b3bbcb12SLuke Drummond     : public CommandObjectMultiword {
4096*b3bbcb12SLuke Drummond public:
4097*b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReductionBreakpoint(
4098*b3bbcb12SLuke Drummond       CommandInterpreter &interpreter)
4099*b3bbcb12SLuke Drummond       : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4100*b3bbcb12SLuke Drummond                                "Commands that manipulate breakpoints on "
4101*b3bbcb12SLuke Drummond                                "renderscript general reductions.",
4102*b3bbcb12SLuke Drummond                                nullptr) {
4103*b3bbcb12SLuke Drummond     LoadSubCommand(
4104*b3bbcb12SLuke Drummond         "set", CommandObjectSP(
4105*b3bbcb12SLuke Drummond                    new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4106*b3bbcb12SLuke Drummond                        interpreter)));
4107*b3bbcb12SLuke Drummond   }
4108*b3bbcb12SLuke Drummond 
4109*b3bbcb12SLuke Drummond   ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4110*b3bbcb12SLuke Drummond };
4111*b3bbcb12SLuke Drummond 
4112b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelCoordinate
4113b9c1b51eSKate Stone     : public CommandObjectParsed {
41144f8817c2SEwan Crawford public:
4115b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelCoordinate(
4116b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4117b9c1b51eSKate Stone       : CommandObjectParsed(
4118b9c1b51eSKate Stone             interpreter, "renderscript kernel coordinate",
41194f8817c2SEwan Crawford             "Shows the (x,y,z) coordinate of the current kernel invocation.",
41204f8817c2SEwan Crawford             "renderscript kernel coordinate",
4121b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4122b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
41234f8817c2SEwan Crawford 
41244f8817c2SEwan Crawford   ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
41254f8817c2SEwan Crawford 
4126b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
412700f56eebSLuke Drummond     RSCoordinate coord{};
4128b9c1b51eSKate Stone     bool success = RenderScriptRuntime::GetKernelCoordinate(
4129b9c1b51eSKate Stone         coord, m_exe_ctx.GetThreadPtr());
41304f8817c2SEwan Crawford     Stream &stream = result.GetOutputStream();
41314f8817c2SEwan Crawford 
4132b9c1b51eSKate Stone     if (success) {
413300f56eebSLuke Drummond       stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
41344f8817c2SEwan Crawford       stream.EOL();
41354f8817c2SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4136b9c1b51eSKate Stone     } else {
41374f8817c2SEwan Crawford       stream.Printf("Error: Coordinate could not be found.");
41384f8817c2SEwan Crawford       stream.EOL();
41394f8817c2SEwan Crawford       result.SetStatus(eReturnStatusFailed);
41404f8817c2SEwan Crawford     }
41414f8817c2SEwan Crawford     return true;
41424f8817c2SEwan Crawford   }
41434f8817c2SEwan Crawford };
41444f8817c2SEwan Crawford 
4145b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpoint
4146b9c1b51eSKate Stone     : public CommandObjectMultiword {
41477dc7771cSEwan Crawford public:
4148b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpoint(
4149b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4150b9c1b51eSKate Stone       : CommandObjectMultiword(
4151b9c1b51eSKate Stone             interpreter, "renderscript kernel",
4152b9c1b51eSKate Stone             "Commands that generate breakpoints on renderscript kernels.",
4153b9c1b51eSKate Stone             nullptr) {
4154b9c1b51eSKate Stone     LoadSubCommand(
4155b9c1b51eSKate Stone         "set",
4156b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4157b9c1b51eSKate Stone             interpreter)));
4158b9c1b51eSKate Stone     LoadSubCommand(
4159b9c1b51eSKate Stone         "all",
4160b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4161b9c1b51eSKate Stone             interpreter)));
41627dc7771cSEwan Crawford   }
41637dc7771cSEwan Crawford 
4164222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
41657dc7771cSEwan Crawford };
41667dc7771cSEwan Crawford 
4167b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
41684640cde1SColin Riley public:
41694640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4170b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript kernel",
4171b9c1b51eSKate Stone                                "Commands that deal with RenderScript kernels.",
4172b9c1b51eSKate Stone                                nullptr) {
4173b9c1b51eSKate Stone     LoadSubCommand(
4174b9c1b51eSKate Stone         "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4175b9c1b51eSKate Stone                     interpreter)));
4176b9c1b51eSKate Stone     LoadSubCommand(
4177b9c1b51eSKate Stone         "coordinate",
4178b9c1b51eSKate Stone         CommandObjectSP(
4179b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4180b9c1b51eSKate Stone     LoadSubCommand(
4181b9c1b51eSKate Stone         "breakpoint",
4182b9c1b51eSKate Stone         CommandObjectSP(
4183b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
41844640cde1SColin Riley   }
41854640cde1SColin Riley 
4186222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernel() override = default;
41874640cde1SColin Riley };
41884640cde1SColin Riley 
4189b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
41904640cde1SColin Riley public:
41914640cde1SColin Riley   CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4192b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript context dump",
4193b9c1b51eSKate Stone                             "Dumps renderscript context information.",
4194b9c1b51eSKate Stone                             "renderscript context dump",
4195b9c1b51eSKate Stone                             eCommandRequiresProcess |
4196b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
41974640cde1SColin Riley 
4198222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContextDump() override = default;
41994640cde1SColin Riley 
4200b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
42014640cde1SColin Riley     RenderScriptRuntime *runtime =
4202b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4203b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
42044640cde1SColin Riley     runtime->DumpContexts(result.GetOutputStream());
42054640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
42064640cde1SColin Riley     return true;
42074640cde1SColin Riley   }
42084640cde1SColin Riley };
42094640cde1SColin Riley 
42101f0f5b5bSZachary Turner static OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
42111f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
42121f0f5b5bSZachary Turner      nullptr, nullptr, 0, eArgTypeFilename,
42131f0f5b5bSZachary Turner      "Print results to specified file instead of command line."}};
42141f0f5b5bSZachary Turner 
4215b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
42164640cde1SColin Riley public:
42174640cde1SColin Riley   CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4218b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript context",
4219b9c1b51eSKate Stone                                "Commands that deal with RenderScript contexts.",
4220b9c1b51eSKate Stone                                nullptr) {
4221b9c1b51eSKate Stone     LoadSubCommand(
4222b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4223b9c1b51eSKate Stone                     interpreter)));
42244640cde1SColin Riley   }
42254640cde1SColin Riley 
4226222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContext() override = default;
42274640cde1SColin Riley };
42284640cde1SColin Riley 
4229b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationDump
4230b9c1b51eSKate Stone     : public CommandObjectParsed {
4231a0f08674SEwan Crawford public:
4232b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationDump(
4233b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4234a0f08674SEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation dump",
4235b9c1b51eSKate Stone                             "Displays the contents of a particular allocation",
4236b9c1b51eSKate Stone                             "renderscript allocation dump <ID>",
4237b9c1b51eSKate Stone                             eCommandRequiresProcess |
4238b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched),
4239b9c1b51eSKate Stone         m_options() {}
4240a0f08674SEwan Crawford 
4241222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4242222b937cSEugene Zelenko 
4243b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
4244a0f08674SEwan Crawford 
4245b9c1b51eSKate Stone   class CommandOptions : public Options {
4246a0f08674SEwan Crawford   public:
4247e1cfbc79STodd Fiala     CommandOptions() : Options() {}
4248a0f08674SEwan Crawford 
4249222b937cSEugene Zelenko     ~CommandOptions() override = default;
4250a0f08674SEwan Crawford 
4251b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
4252*b3bbcb12SLuke Drummond                          ExecutionContext *exe_ctx) override {
425380af0b9eSLuke Drummond       Error err;
4254a0f08674SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
4255a0f08674SEwan Crawford 
4256b9c1b51eSKate Stone       switch (short_option) {
4257a0f08674SEwan Crawford       case 'f':
4258a0f08674SEwan Crawford         m_outfile.SetFile(option_arg, true);
4259b9c1b51eSKate Stone         if (m_outfile.Exists()) {
4260a0f08674SEwan Crawford           m_outfile.Clear();
426180af0b9eSLuke Drummond           err.SetErrorStringWithFormat("file already exists: '%s'", option_arg);
4262a0f08674SEwan Crawford         }
4263a0f08674SEwan Crawford         break;
4264a0f08674SEwan Crawford       default:
426580af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4266a0f08674SEwan Crawford         break;
4267a0f08674SEwan Crawford       }
426880af0b9eSLuke Drummond       return err;
4269a0f08674SEwan Crawford     }
4270a0f08674SEwan Crawford 
4271*b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4272a0f08674SEwan Crawford       m_outfile.Clear();
4273a0f08674SEwan Crawford     }
4274a0f08674SEwan Crawford 
42751f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
427670602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
42771f0f5b5bSZachary Turner     }
4278a0f08674SEwan Crawford 
4279a0f08674SEwan Crawford     FileSpec m_outfile;
4280a0f08674SEwan Crawford   };
4281a0f08674SEwan Crawford 
4282b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4283a0f08674SEwan Crawford     const size_t argc = command.GetArgumentCount();
4284b9c1b51eSKate Stone     if (argc < 1) {
4285b9c1b51eSKate Stone       result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4286b9c1b51eSKate Stone                                    "As well as an optional -f argument",
4287a0f08674SEwan Crawford                                    m_cmd_name.c_str());
4288a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4289a0f08674SEwan Crawford       return false;
4290a0f08674SEwan Crawford     }
4291a0f08674SEwan Crawford 
4292b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4293b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4294b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4295a0f08674SEwan Crawford 
4296a0f08674SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
429780af0b9eSLuke Drummond     bool success = false;
4298b9c1b51eSKate Stone     const uint32_t id =
429980af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
430080af0b9eSLuke Drummond     if (!success) {
4301b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4302b9c1b51eSKate Stone                                    id_cstr);
4303a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4304a0f08674SEwan Crawford       return false;
4305a0f08674SEwan Crawford     }
4306a0f08674SEwan Crawford 
4307a0f08674SEwan Crawford     Stream *output_strm = nullptr;
4308a0f08674SEwan Crawford     StreamFile outfile_stream;
4309b9c1b51eSKate Stone     const FileSpec &outfile_spec =
4310b9c1b51eSKate Stone         m_options.m_outfile; // Dump allocation to file instead
4311b9c1b51eSKate Stone     if (outfile_spec) {
4312a0f08674SEwan Crawford       // Open output file
4313a0f08674SEwan Crawford       char path[256];
4314a0f08674SEwan Crawford       outfile_spec.GetPath(path, sizeof(path));
4315b9c1b51eSKate Stone       if (outfile_stream.GetFile()
4316b9c1b51eSKate Stone               .Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate)
4317b9c1b51eSKate Stone               .Success()) {
4318a0f08674SEwan Crawford         output_strm = &outfile_stream;
4319a0f08674SEwan Crawford         result.GetOutputStream().Printf("Results written to '%s'", path);
4320a0f08674SEwan Crawford         result.GetOutputStream().EOL();
4321b9c1b51eSKate Stone       } else {
4322a0f08674SEwan Crawford         result.AppendErrorWithFormat("Couldn't open file '%s'", path);
4323a0f08674SEwan Crawford         result.SetStatus(eReturnStatusFailed);
4324a0f08674SEwan Crawford         return false;
4325a0f08674SEwan Crawford       }
4326b9c1b51eSKate Stone     } else
4327a0f08674SEwan Crawford       output_strm = &result.GetOutputStream();
4328a0f08674SEwan Crawford 
4329a0f08674SEwan Crawford     assert(output_strm != nullptr);
433080af0b9eSLuke Drummond     bool dumped =
4331b9c1b51eSKate Stone         runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4332a0f08674SEwan Crawford 
433380af0b9eSLuke Drummond     if (dumped)
4334a0f08674SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4335a0f08674SEwan Crawford     else
4336a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4337a0f08674SEwan Crawford 
4338a0f08674SEwan Crawford     return true;
4339a0f08674SEwan Crawford   }
4340a0f08674SEwan Crawford 
4341a0f08674SEwan Crawford private:
4342a0f08674SEwan Crawford   CommandOptions m_options;
4343a0f08674SEwan Crawford };
4344a0f08674SEwan Crawford 
43451f0f5b5bSZachary Turner static OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
43461f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
43471f0f5b5bSZachary Turner      nullptr, 0, eArgTypeIndex,
43481f0f5b5bSZachary Turner      "Only show details of a single allocation with specified id."}};
4349a0f08674SEwan Crawford 
4350b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationList
4351b9c1b51eSKate Stone     : public CommandObjectParsed {
435215f2bd95SEwan Crawford public:
4353b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationList(
4354b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4355b9c1b51eSKate Stone       : CommandObjectParsed(
4356b9c1b51eSKate Stone             interpreter, "renderscript allocation list",
4357b9c1b51eSKate Stone             "List renderscript allocations and their information.",
4358b9c1b51eSKate Stone             "renderscript allocation list",
4359b3f7f69dSAidan Dodds             eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4360b9c1b51eSKate Stone         m_options() {}
436115f2bd95SEwan Crawford 
4362222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4363222b937cSEugene Zelenko 
4364b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
436515f2bd95SEwan Crawford 
4366b9c1b51eSKate Stone   class CommandOptions : public Options {
436715f2bd95SEwan Crawford   public:
4368e1cfbc79STodd Fiala     CommandOptions() : Options(), m_id(0) {}
436915f2bd95SEwan Crawford 
4370222b937cSEugene Zelenko     ~CommandOptions() override = default;
437115f2bd95SEwan Crawford 
4372b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
4373*b3bbcb12SLuke Drummond                          ExecutionContext *exe_ctx) override {
437480af0b9eSLuke Drummond       Error err;
437515f2bd95SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
437615f2bd95SEwan Crawford 
4377b9c1b51eSKate Stone       switch (short_option) {
4378b649b005SEwan Crawford       case 'i':
4379b649b005SEwan Crawford         bool success;
4380b649b005SEwan Crawford         m_id = StringConvert::ToUInt32(option_arg, 0, 0, &success);
4381b649b005SEwan Crawford         if (!success)
438280af0b9eSLuke Drummond           err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4383b9c1b51eSKate Stone                                        short_option);
438415f2bd95SEwan Crawford         break;
438580af0b9eSLuke Drummond       default:
438680af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
438780af0b9eSLuke Drummond         break;
438815f2bd95SEwan Crawford       }
438980af0b9eSLuke Drummond       return err;
439015f2bd95SEwan Crawford     }
439115f2bd95SEwan Crawford 
4392*b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
439315f2bd95SEwan Crawford 
43941f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
439570602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
43961f0f5b5bSZachary Turner     }
439715f2bd95SEwan Crawford 
4398b649b005SEwan Crawford     uint32_t m_id;
439915f2bd95SEwan Crawford   };
440015f2bd95SEwan Crawford 
4401b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4402b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4403b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4404b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4405b9c1b51eSKate Stone     runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4406b9c1b51eSKate Stone                              m_options.m_id);
440715f2bd95SEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
440815f2bd95SEwan Crawford     return true;
440915f2bd95SEwan Crawford   }
441015f2bd95SEwan Crawford 
441115f2bd95SEwan Crawford private:
441215f2bd95SEwan Crawford   CommandOptions m_options;
441315f2bd95SEwan Crawford };
441415f2bd95SEwan Crawford 
4415b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationLoad
4416b9c1b51eSKate Stone     : public CommandObjectParsed {
441755232f09SEwan Crawford public:
4418b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationLoad(
4419b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4420b3f7f69dSAidan Dodds       : CommandObjectParsed(
4421b9c1b51eSKate Stone             interpreter, "renderscript allocation load",
4422b9c1b51eSKate Stone             "Loads renderscript allocation contents from a file.",
4423b9c1b51eSKate Stone             "renderscript allocation load <ID> <filename>",
4424b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
442555232f09SEwan Crawford 
4426222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
442755232f09SEwan Crawford 
4428b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
442955232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4430b9c1b51eSKate Stone     if (argc != 2) {
4431b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4432b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4433b3f7f69dSAidan Dodds           m_cmd_name.c_str());
443455232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
443555232f09SEwan Crawford       return false;
443655232f09SEwan Crawford     }
443755232f09SEwan Crawford 
4438b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4439b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4440b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
444155232f09SEwan Crawford 
444255232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
444380af0b9eSLuke Drummond     bool success = false;
4444b9c1b51eSKate Stone     const uint32_t id =
444580af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
444680af0b9eSLuke Drummond     if (!success) {
4447b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4448b9c1b51eSKate Stone                                    id_cstr);
444955232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
445055232f09SEwan Crawford       return false;
445155232f09SEwan Crawford     }
445255232f09SEwan Crawford 
445380af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
445480af0b9eSLuke Drummond     bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
445580af0b9eSLuke Drummond                                           m_exe_ctx.GetFramePtr());
445655232f09SEwan Crawford 
445780af0b9eSLuke Drummond     if (loaded)
445855232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
445955232f09SEwan Crawford     else
446055232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
446155232f09SEwan Crawford 
446255232f09SEwan Crawford     return true;
446355232f09SEwan Crawford   }
446455232f09SEwan Crawford };
446555232f09SEwan Crawford 
4466b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationSave
4467b9c1b51eSKate Stone     : public CommandObjectParsed {
446855232f09SEwan Crawford public:
4469b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationSave(
4470b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4471b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript allocation save",
4472b9c1b51eSKate Stone                             "Write renderscript allocation contents to a file.",
4473b9c1b51eSKate Stone                             "renderscript allocation save <ID> <filename>",
4474b9c1b51eSKate Stone                             eCommandRequiresProcess |
4475b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
447655232f09SEwan Crawford 
4477222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
447855232f09SEwan Crawford 
4479b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
448055232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4481b9c1b51eSKate Stone     if (argc != 2) {
4482b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4483b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4484b3f7f69dSAidan Dodds           m_cmd_name.c_str());
448555232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
448655232f09SEwan Crawford       return false;
448755232f09SEwan Crawford     }
448855232f09SEwan Crawford 
4489b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4490b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4491b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
449255232f09SEwan Crawford 
449355232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
449480af0b9eSLuke Drummond     bool success = false;
4495b9c1b51eSKate Stone     const uint32_t id =
449680af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
449780af0b9eSLuke Drummond     if (!success) {
4498b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4499b9c1b51eSKate Stone                                    id_cstr);
450055232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
450155232f09SEwan Crawford       return false;
450255232f09SEwan Crawford     }
450355232f09SEwan Crawford 
450480af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
450580af0b9eSLuke Drummond     bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
450680af0b9eSLuke Drummond                                          m_exe_ctx.GetFramePtr());
450755232f09SEwan Crawford 
450880af0b9eSLuke Drummond     if (saved)
450955232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
451055232f09SEwan Crawford     else
451155232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
451255232f09SEwan Crawford 
451355232f09SEwan Crawford     return true;
451455232f09SEwan Crawford   }
451555232f09SEwan Crawford };
451655232f09SEwan Crawford 
4517b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationRefresh
4518b9c1b51eSKate Stone     : public CommandObjectParsed {
45190d2bfcfbSEwan Crawford public:
4520b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationRefresh(
4521b9c1b51eSKate Stone       CommandInterpreter &interpreter)
45220d2bfcfbSEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4523b9c1b51eSKate Stone                             "Recomputes the details of all allocations.",
4524b9c1b51eSKate Stone                             "renderscript allocation refresh",
4525b9c1b51eSKate Stone                             eCommandRequiresProcess |
4526b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
45270d2bfcfbSEwan Crawford 
45280d2bfcfbSEwan Crawford   ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
45290d2bfcfbSEwan Crawford 
4530b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
45310d2bfcfbSEwan Crawford     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4532b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4533b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
45340d2bfcfbSEwan Crawford 
4535b9c1b51eSKate Stone     bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4536b9c1b51eSKate Stone                                                     m_exe_ctx.GetFramePtr());
45370d2bfcfbSEwan Crawford 
4538b9c1b51eSKate Stone     if (success) {
45390d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
45400d2bfcfbSEwan Crawford       return true;
4541b9c1b51eSKate Stone     } else {
45420d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusFailed);
45430d2bfcfbSEwan Crawford       return false;
45440d2bfcfbSEwan Crawford     }
45450d2bfcfbSEwan Crawford   }
45460d2bfcfbSEwan Crawford };
45470d2bfcfbSEwan Crawford 
4548b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocation
4549b9c1b51eSKate Stone     : public CommandObjectMultiword {
455015f2bd95SEwan Crawford public:
455115f2bd95SEwan Crawford   CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4552b9c1b51eSKate Stone       : CommandObjectMultiword(
4553b9c1b51eSKate Stone             interpreter, "renderscript allocation",
4554b9c1b51eSKate Stone             "Commands that deal with RenderScript allocations.", nullptr) {
4555b9c1b51eSKate Stone     LoadSubCommand(
4556b9c1b51eSKate Stone         "list",
4557b9c1b51eSKate Stone         CommandObjectSP(
4558b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4559b9c1b51eSKate Stone     LoadSubCommand(
4560b9c1b51eSKate Stone         "dump",
4561b9c1b51eSKate Stone         CommandObjectSP(
4562b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4563b9c1b51eSKate Stone     LoadSubCommand(
4564b9c1b51eSKate Stone         "save",
4565b9c1b51eSKate Stone         CommandObjectSP(
4566b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4567b9c1b51eSKate Stone     LoadSubCommand(
4568b9c1b51eSKate Stone         "load",
4569b9c1b51eSKate Stone         CommandObjectSP(
4570b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4571b9c1b51eSKate Stone     LoadSubCommand(
4572b9c1b51eSKate Stone         "refresh",
4573b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4574b9c1b51eSKate Stone             interpreter)));
457515f2bd95SEwan Crawford   }
457615f2bd95SEwan Crawford 
4577222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocation() override = default;
457815f2bd95SEwan Crawford };
457915f2bd95SEwan Crawford 
4580b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
45814640cde1SColin Riley public:
45824640cde1SColin Riley   CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4583b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript status",
4584b9c1b51eSKate Stone                             "Displays current RenderScript runtime status.",
4585b9c1b51eSKate Stone                             "renderscript status",
4586b9c1b51eSKate Stone                             eCommandRequiresProcess |
4587b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
45884640cde1SColin Riley 
4589222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeStatus() override = default;
45904640cde1SColin Riley 
4591b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
45924640cde1SColin Riley     RenderScriptRuntime *runtime =
4593b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4594b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
45954640cde1SColin Riley     runtime->Status(result.GetOutputStream());
45964640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
45974640cde1SColin Riley     return true;
45984640cde1SColin Riley   }
45994640cde1SColin Riley };
46004640cde1SColin Riley 
4601*b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReduction
4602*b3bbcb12SLuke Drummond     : public CommandObjectMultiword {
4603*b3bbcb12SLuke Drummond public:
4604*b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
4605*b3bbcb12SLuke Drummond       : CommandObjectMultiword(interpreter, "renderscript reduction",
4606*b3bbcb12SLuke Drummond                                "Commands that handle general reduction kernels",
4607*b3bbcb12SLuke Drummond                                nullptr) {
4608*b3bbcb12SLuke Drummond     LoadSubCommand(
4609*b3bbcb12SLuke Drummond         "breakpoint",
4610*b3bbcb12SLuke Drummond         CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
4611*b3bbcb12SLuke Drummond             interpreter)));
4612*b3bbcb12SLuke Drummond   }
4613*b3bbcb12SLuke Drummond   ~CommandObjectRenderScriptRuntimeReduction() override = default;
4614*b3bbcb12SLuke Drummond };
4615*b3bbcb12SLuke Drummond 
4616b9c1b51eSKate Stone class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
46175ec532a9SColin Riley public:
46185ec532a9SColin Riley   CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
4619b9c1b51eSKate Stone       : CommandObjectMultiword(
4620b9c1b51eSKate Stone             interpreter, "renderscript",
4621b9c1b51eSKate Stone             "Commands for operating on the RenderScript runtime.",
4622b9c1b51eSKate Stone             "renderscript <subcommand> [<subcommand-options>]") {
4623b9c1b51eSKate Stone     LoadSubCommand(
4624b9c1b51eSKate Stone         "module", CommandObjectSP(
4625b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeModule(interpreter)));
4626b9c1b51eSKate Stone     LoadSubCommand(
4627b9c1b51eSKate Stone         "status", CommandObjectSP(
4628b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeStatus(interpreter)));
4629b9c1b51eSKate Stone     LoadSubCommand(
4630b9c1b51eSKate Stone         "kernel", CommandObjectSP(
4631b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeKernel(interpreter)));
4632b9c1b51eSKate Stone     LoadSubCommand("context",
4633b9c1b51eSKate Stone                    CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
4634b9c1b51eSKate Stone                        interpreter)));
4635b9c1b51eSKate Stone     LoadSubCommand(
4636b9c1b51eSKate Stone         "allocation",
4637b9c1b51eSKate Stone         CommandObjectSP(
4638b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
4639*b3bbcb12SLuke Drummond     LoadSubCommand(
4640*b3bbcb12SLuke Drummond         "reduction",
4641*b3bbcb12SLuke Drummond         CommandObjectSP(
4642*b3bbcb12SLuke Drummond             new CommandObjectRenderScriptRuntimeReduction(interpreter)));
46435ec532a9SColin Riley   }
46445ec532a9SColin Riley 
4645222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntime() override = default;
46465ec532a9SColin Riley };
4647ef20b08fSColin Riley 
4648b9c1b51eSKate Stone void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
4649ef20b08fSColin Riley 
4650ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
4651b9c1b51eSKate Stone     : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
4652b9c1b51eSKate Stone       m_debuggerPresentFlagged(false), m_breakAllKernels(false),
4653b9c1b51eSKate Stone       m_ir_passes(nullptr) {
46544640cde1SColin Riley   ModulesDidLoad(process->GetTarget().GetImages());
4655ef20b08fSColin Riley }
46564640cde1SColin Riley 
4657b9c1b51eSKate Stone lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
4658b9c1b51eSKate Stone     lldb_private::CommandInterpreter &interpreter) {
46590a66e2f1SEnrico Granata   return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
46604640cde1SColin Riley }
46614640cde1SColin Riley 
466278f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
4663