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
137f193d69SLuke Drummond #include "llvm/ADT/StringMap.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
51*80af0b9eSLuke Drummond // allowing us to track if data has been discovered and stored or not. An
52*80af0b9eSLuke 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 
119*80af0b9eSLuke 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;
132*80af0b9eSLuke Drummond     Error err;
133b9c1b51eSKate Stone     size_t read =
134*80af0b9eSLuke Drummond         ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
135*80af0b9eSLuke Drummond     if (read != arg_size || !err.Success()) {
136f4786785SAidan Dodds       if (log)
137b9c1b51eSKate Stone         log->Printf("%s - error reading argument: %" PRIu64 " '%s'",
138*80af0b9eSLuke 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
149*80af0b9eSLuke Drummond   static const uint32_t args_in_reg = 6;
150f4786785SAidan Dodds   // register passing order
151*80af0b9eSLuke 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 
162*80af0b9eSLuke 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;
178*80af0b9eSLuke 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
189*80af0b9eSLuke Drummond     if (i < args_in_reg) {
190*80af0b9eSLuke Drummond       const RegisterInfo *reg =
191*80af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoByName(reg_names[i]);
192*80af0b9eSLuke Drummond       RegisterValue reg_val;
193*80af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
194*80af0b9eSLuke 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.
204*80af0b9eSLuke Drummond       size_t read = ctx.process->ReadMemory(sp, &arg.value, size, err);
205*80af0b9eSLuke 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",
213*80af0b9eSLuke 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
222*80af0b9eSLuke Drummond   static const uint32_t args_in_reg = 4;
223f4786785SAidan Dodds 
224f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
225f4786785SAidan Dodds 
226*80af0b9eSLuke 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
235*80af0b9eSLuke Drummond     if (i < args_in_reg) {
236*80af0b9eSLuke Drummond       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
237*80af0b9eSLuke Drummond       RegisterValue reg_val;
238*80af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
239*80af0b9eSLuke 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 =
249*80af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
250*80af0b9eSLuke 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",
258*80af0b9eSLuke 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
267*80af0b9eSLuke 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
275*80af0b9eSLuke Drummond     if (i < args_in_reg) {
276*80af0b9eSLuke Drummond       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
277*80af0b9eSLuke Drummond       RegisterValue reg_val;
278*80af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
279*80af0b9eSLuke 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
300*80af0b9eSLuke Drummond   static const uint32_t args_in_reg = 4;
301f4786785SAidan Dodds   // register file offset to first argument
302*80af0b9eSLuke Drummond   static const uint32_t reg_offset = 4;
303f4786785SAidan Dodds 
304f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
305f4786785SAidan Dodds 
306*80af0b9eSLuke 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
315*80af0b9eSLuke Drummond     if (i < args_in_reg) {
316*80af0b9eSLuke Drummond       const RegisterInfo *reg =
317*80af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
318*80af0b9eSLuke Drummond       RegisterValue reg_val;
319*80af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
320*80af0b9eSLuke 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 =
327*80af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
328*80af0b9eSLuke 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",
336*80af0b9eSLuke 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
345*80af0b9eSLuke Drummond   static const uint32_t args_in_reg = 8;
346f4786785SAidan Dodds   // register file offset to first argument
347*80af0b9eSLuke Drummond   static const uint32_t reg_offset = 4;
348f4786785SAidan Dodds 
349f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
350f4786785SAidan Dodds 
351*80af0b9eSLuke 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
360*80af0b9eSLuke Drummond     if (i < args_in_reg) {
361*80af0b9eSLuke Drummond       const RegisterInfo *reg =
362*80af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
363*80af0b9eSLuke Drummond       RegisterValue reg_val;
364*80af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
365*80af0b9eSLuke 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 =
375*80af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
376*80af0b9eSLuke 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",
384*80af0b9eSLuke 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 
391*80af0b9eSLuke 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
395*80af0b9eSLuke 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 
401*80af0b9eSLuke 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
405*80af0b9eSLuke 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__,
429*80af0b9eSLuke Drummond           exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
430f4786785SAidan Dodds     }
431f4786785SAidan Dodds     return false;
432f4786785SAidan Dodds   }
433f4786785SAidan Dodds }
43400f56eebSLuke Drummond 
43500f56eebSLuke Drummond bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
43600f56eebSLuke Drummond   // takes an argument of the form 'num[,num][,num]'.
43700f56eebSLuke Drummond   // Where 'coord_s' is a comma separated 1,2 or 3-dimensional coordinate
43800f56eebSLuke Drummond   // with the whitespace trimmed.
43900f56eebSLuke Drummond   // Missing coordinates are defaulted to zero.
44000f56eebSLuke Drummond   // If parsing of any elements fails the contents of &coord are undefined
44100f56eebSLuke Drummond   // and `false` is returned, `true` otherwise
44200f56eebSLuke Drummond 
44300f56eebSLuke Drummond   RegularExpression regex;
44400f56eebSLuke Drummond   RegularExpression::Match regex_match(3);
44500f56eebSLuke Drummond 
44600f56eebSLuke Drummond   bool matched = false;
44700f56eebSLuke Drummond   if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+),([0-9]+)$")) &&
44800f56eebSLuke Drummond       regex.Execute(coord_s, &regex_match))
44900f56eebSLuke Drummond     matched = true;
45000f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+)$")) &&
45100f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
45200f56eebSLuke Drummond     matched = true;
45300f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([0-9]+)$")) &&
45400f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
45500f56eebSLuke Drummond     matched = true;
45600f56eebSLuke Drummond 
45700f56eebSLuke Drummond   if (!matched)
45800f56eebSLuke Drummond     return false;
45900f56eebSLuke Drummond 
46000f56eebSLuke Drummond   auto get_index = [&](int idx, uint32_t &i) -> bool {
46100f56eebSLuke Drummond     std::string group;
46200f56eebSLuke Drummond     errno = 0;
46300f56eebSLuke Drummond     if (regex_match.GetMatchAtIndex(coord_s.str().c_str(), idx + 1, group))
46400f56eebSLuke Drummond       return !llvm::StringRef(group).getAsInteger<uint32_t>(10, i);
46500f56eebSLuke Drummond     return true;
46600f56eebSLuke Drummond   };
46700f56eebSLuke Drummond 
46800f56eebSLuke Drummond   return get_index(0, coord.x) && get_index(1, coord.y) &&
46900f56eebSLuke Drummond          get_index(2, coord.z);
47000f56eebSLuke Drummond }
471222b937cSEugene Zelenko } // anonymous namespace
47278f339d1SEwan Crawford 
473b9c1b51eSKate Stone // The ScriptDetails class collects data associated with a single script
474b9c1b51eSKate Stone // instance.
475b9c1b51eSKate Stone struct RenderScriptRuntime::ScriptDetails {
476222b937cSEugene Zelenko   ~ScriptDetails() = default;
47778f339d1SEwan Crawford 
478b9c1b51eSKate Stone   enum ScriptType { eScript, eScriptC };
47978f339d1SEwan Crawford 
48078f339d1SEwan Crawford   // The derived type of the script.
48178f339d1SEwan Crawford   empirical_type<ScriptType> type;
48278f339d1SEwan Crawford   // The name of the original source file.
483*80af0b9eSLuke Drummond   empirical_type<std::string> res_name;
48478f339d1SEwan Crawford   // Path to script .so file on the device.
485*80af0b9eSLuke Drummond   empirical_type<std::string> shared_lib;
48678f339d1SEwan Crawford   // Directory where kernel objects are cached on device.
487*80af0b9eSLuke Drummond   empirical_type<std::string> cache_dir;
48878f339d1SEwan Crawford   // Pointer to the context which owns this script.
48978f339d1SEwan Crawford   empirical_type<lldb::addr_t> context;
49078f339d1SEwan Crawford   // Pointer to the script object itself.
49178f339d1SEwan Crawford   empirical_type<lldb::addr_t> script;
49278f339d1SEwan Crawford };
49378f339d1SEwan Crawford 
494*80af0b9eSLuke Drummond // This Element class represents the Element object in RS, defining the type
495*80af0b9eSLuke Drummond // associated with an Allocation.
496b9c1b51eSKate Stone struct RenderScriptRuntime::Element {
49715f2bd95SEwan Crawford   // Taken from rsDefines.h
498b9c1b51eSKate Stone   enum DataKind {
49915f2bd95SEwan Crawford     RS_KIND_USER,
50015f2bd95SEwan Crawford     RS_KIND_PIXEL_L = 7,
50115f2bd95SEwan Crawford     RS_KIND_PIXEL_A,
50215f2bd95SEwan Crawford     RS_KIND_PIXEL_LA,
50315f2bd95SEwan Crawford     RS_KIND_PIXEL_RGB,
50415f2bd95SEwan Crawford     RS_KIND_PIXEL_RGBA,
50515f2bd95SEwan Crawford     RS_KIND_PIXEL_DEPTH,
50615f2bd95SEwan Crawford     RS_KIND_PIXEL_YUV,
50715f2bd95SEwan Crawford     RS_KIND_INVALID = 100
50815f2bd95SEwan Crawford   };
50978f339d1SEwan Crawford 
51015f2bd95SEwan Crawford   // Taken from rsDefines.h
511b9c1b51eSKate Stone   enum DataType {
51215f2bd95SEwan Crawford     RS_TYPE_NONE = 0,
51315f2bd95SEwan Crawford     RS_TYPE_FLOAT_16,
51415f2bd95SEwan Crawford     RS_TYPE_FLOAT_32,
51515f2bd95SEwan Crawford     RS_TYPE_FLOAT_64,
51615f2bd95SEwan Crawford     RS_TYPE_SIGNED_8,
51715f2bd95SEwan Crawford     RS_TYPE_SIGNED_16,
51815f2bd95SEwan Crawford     RS_TYPE_SIGNED_32,
51915f2bd95SEwan Crawford     RS_TYPE_SIGNED_64,
52015f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_8,
52115f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_16,
52215f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_32,
52315f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_64,
5242e920715SEwan Crawford     RS_TYPE_BOOLEAN,
5252e920715SEwan Crawford 
5262e920715SEwan Crawford     RS_TYPE_UNSIGNED_5_6_5,
5272e920715SEwan Crawford     RS_TYPE_UNSIGNED_5_5_5_1,
5282e920715SEwan Crawford     RS_TYPE_UNSIGNED_4_4_4_4,
5292e920715SEwan Crawford 
5302e920715SEwan Crawford     RS_TYPE_MATRIX_4X4,
5312e920715SEwan Crawford     RS_TYPE_MATRIX_3X3,
5322e920715SEwan Crawford     RS_TYPE_MATRIX_2X2,
5332e920715SEwan Crawford 
5342e920715SEwan Crawford     RS_TYPE_ELEMENT = 1000,
5352e920715SEwan Crawford     RS_TYPE_TYPE,
5362e920715SEwan Crawford     RS_TYPE_ALLOCATION,
5372e920715SEwan Crawford     RS_TYPE_SAMPLER,
5382e920715SEwan Crawford     RS_TYPE_SCRIPT,
5392e920715SEwan Crawford     RS_TYPE_MESH,
5402e920715SEwan Crawford     RS_TYPE_PROGRAM_FRAGMENT,
5412e920715SEwan Crawford     RS_TYPE_PROGRAM_VERTEX,
5422e920715SEwan Crawford     RS_TYPE_PROGRAM_RASTER,
5432e920715SEwan Crawford     RS_TYPE_PROGRAM_STORE,
5442e920715SEwan Crawford     RS_TYPE_FONT,
5452e920715SEwan Crawford 
5462e920715SEwan Crawford     RS_TYPE_INVALID = 10000
54778f339d1SEwan Crawford   };
54878f339d1SEwan Crawford 
5498b244e21SEwan Crawford   std::vector<Element> children; // Child Element fields for structs
550b9c1b51eSKate Stone   empirical_type<lldb::addr_t>
551b9c1b51eSKate Stone       element_ptr; // Pointer to the RS Element of the Type
552b9c1b51eSKate Stone   empirical_type<DataType>
553b9c1b51eSKate Stone       type; // Type of each data pointer stored by the allocation
554b9c1b51eSKate Stone   empirical_type<DataKind>
555b9c1b51eSKate Stone       type_kind; // Defines pixel type if Allocation is created from an image
556b9c1b51eSKate Stone   empirical_type<uint32_t>
557b9c1b51eSKate Stone       type_vec_size; // Vector size of each data point, e.g '4' for uchar4
5588b244e21SEwan Crawford   empirical_type<uint32_t> field_count; // Number of Subelements
5598b244e21SEwan Crawford   empirical_type<uint32_t> datum_size;  // Size of a single Element with padding
5608b244e21SEwan Crawford   empirical_type<uint32_t> padding;     // Number of padding bytes
561b9c1b51eSKate Stone   empirical_type<uint32_t>
562b9c1b51eSKate Stone       array_size;        // Number of items in array, only needed for strucrs
5638b244e21SEwan Crawford   ConstString type_name; // Name of type, only needed for structs
5648b244e21SEwan Crawford 
565b3f7f69dSAidan Dodds   static const ConstString &
566b3f7f69dSAidan Dodds   GetFallbackStructName(); // Print this as the type name of a struct Element
5678b244e21SEwan Crawford                            // If we can't resolve the actual struct name
5688b59062aSEwan Crawford 
569*80af0b9eSLuke Drummond   bool ShouldRefresh() const {
5708b59062aSEwan Crawford     const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
571b9c1b51eSKate Stone     const bool valid_type =
572b9c1b51eSKate Stone         type.isValid() && type_vec_size.isValid() && type_kind.isValid();
5738b59062aSEwan Crawford     return !valid_ptr || !valid_type || !datum_size.isValid();
5748b59062aSEwan Crawford   }
5758b244e21SEwan Crawford };
5768b244e21SEwan Crawford 
5778b244e21SEwan Crawford // This AllocationDetails class collects data associated with a single
5788b244e21SEwan Crawford // allocation instance.
579b9c1b51eSKate Stone struct RenderScriptRuntime::AllocationDetails {
580b9c1b51eSKate Stone   struct Dimension {
58115f2bd95SEwan Crawford     uint32_t dim_1;
58215f2bd95SEwan Crawford     uint32_t dim_2;
58315f2bd95SEwan Crawford     uint32_t dim_3;
584*80af0b9eSLuke Drummond     uint32_t cube_map;
58515f2bd95SEwan Crawford 
586b9c1b51eSKate Stone     Dimension() {
58715f2bd95SEwan Crawford       dim_1 = 0;
58815f2bd95SEwan Crawford       dim_2 = 0;
58915f2bd95SEwan Crawford       dim_3 = 0;
590*80af0b9eSLuke Drummond       cube_map = 0;
59115f2bd95SEwan Crawford     }
59278f339d1SEwan Crawford   };
59378f339d1SEwan Crawford 
594b9c1b51eSKate Stone   // The FileHeader struct specifies the header we use for writing allocations
595*80af0b9eSLuke Drummond   // to a binary file. Our format begins with the ASCII characters "RSAD",
596*80af0b9eSLuke Drummond   // identifying the file as an allocation dump. Member variables dims and
597*80af0b9eSLuke Drummond   // hdr_size are then written consecutively, immediately followed by an
598*80af0b9eSLuke Drummond   // instance of the ElementHeader struct. Because Elements can contain
599*80af0b9eSLuke Drummond   // subelements, there may be more than one instance of the ElementHeader
600*80af0b9eSLuke Drummond   // struct. With this first instance being the root element, and the other
601*80af0b9eSLuke Drummond   // instances being the root's descendants. To identify which instances are an
602*80af0b9eSLuke Drummond   // ElementHeader's children, each struct is immediately followed by a sequence
603*80af0b9eSLuke Drummond   // of consecutive offsets to the start of its child structs. These offsets are
604*80af0b9eSLuke Drummond   // 4 bytes in size, and the 0 offset signifies no more children.
605b9c1b51eSKate Stone   struct FileHeader {
60655232f09SEwan Crawford     uint8_t ident[4];  // ASCII 'RSAD' identifying the file
60726e52a70SEwan Crawford     uint32_t dims[3];  // Dimensions
60826e52a70SEwan Crawford     uint16_t hdr_size; // Header size in bytes, including all element headers
60926e52a70SEwan Crawford   };
61026e52a70SEwan Crawford 
611b9c1b51eSKate Stone   struct ElementHeader {
61255232f09SEwan Crawford     uint16_t type;         // DataType enum
61355232f09SEwan Crawford     uint32_t kind;         // DataKind enum
61455232f09SEwan Crawford     uint32_t element_size; // Size of a single element, including padding
61526e52a70SEwan Crawford     uint16_t vector_size;  // Vector width
61626e52a70SEwan Crawford     uint32_t array_size;   // Number of elements in array
61755232f09SEwan Crawford   };
61855232f09SEwan Crawford 
61915f2bd95SEwan Crawford   // Monotonically increasing from 1
620b3f7f69dSAidan Dodds   static uint32_t ID;
62115f2bd95SEwan Crawford 
62215f2bd95SEwan Crawford   // Maps Allocation DataType enum and vector size to printable strings
62315f2bd95SEwan Crawford   // using mapping from RenderScript numerical types summary documentation
62415f2bd95SEwan Crawford   static const char *RsDataTypeToString[][4];
62515f2bd95SEwan Crawford 
62615f2bd95SEwan Crawford   // Maps Allocation DataKind enum to printable strings
62715f2bd95SEwan Crawford   static const char *RsDataKindToString[];
62815f2bd95SEwan Crawford 
629a0f08674SEwan Crawford   // Maps allocation types to format sizes for printing.
630b3f7f69dSAidan Dodds   static const uint32_t RSTypeToFormat[][3];
631a0f08674SEwan Crawford 
63215f2bd95SEwan Crawford   // Give each allocation an ID as a way
63315f2bd95SEwan Crawford   // for commands to reference it.
634b3f7f69dSAidan Dodds   const uint32_t id;
63515f2bd95SEwan Crawford 
636*80af0b9eSLuke Drummond   // Allocation Element type
637*80af0b9eSLuke Drummond   RenderScriptRuntime::Element element;
638*80af0b9eSLuke Drummond   // Dimensions of the Allocation
639*80af0b9eSLuke Drummond   empirical_type<Dimension> dimension;
640*80af0b9eSLuke Drummond   // Pointer to address of the RS Allocation
641*80af0b9eSLuke Drummond   empirical_type<lldb::addr_t> address;
642*80af0b9eSLuke Drummond   // Pointer to the data held by the Allocation
643*80af0b9eSLuke Drummond   empirical_type<lldb::addr_t> data_ptr;
644*80af0b9eSLuke Drummond   // Pointer to the RS Type of the Allocation
645*80af0b9eSLuke Drummond   empirical_type<lldb::addr_t> type_ptr;
646*80af0b9eSLuke Drummond   // Pointer to the RS Context of the Allocation
647*80af0b9eSLuke Drummond   empirical_type<lldb::addr_t> context;
648*80af0b9eSLuke Drummond   // Size of the allocation
649*80af0b9eSLuke Drummond   empirical_type<uint32_t> size;
650*80af0b9eSLuke Drummond   // Stride between rows of the allocation
651*80af0b9eSLuke Drummond   empirical_type<uint32_t> stride;
65215f2bd95SEwan Crawford 
65315f2bd95SEwan Crawford   // Give each allocation an id, so we can reference it in user commands.
654b3f7f69dSAidan Dodds   AllocationDetails() : id(ID++) {}
6558b59062aSEwan Crawford 
656*80af0b9eSLuke Drummond   bool ShouldRefresh() const {
6578b59062aSEwan Crawford     bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
6588b59062aSEwan Crawford     valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
659b9c1b51eSKate Stone     return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
660*80af0b9eSLuke Drummond            element.ShouldRefresh();
6618b59062aSEwan Crawford   }
66215f2bd95SEwan Crawford };
66315f2bd95SEwan Crawford 
664b9c1b51eSKate Stone const ConstString &RenderScriptRuntime::Element::GetFallbackStructName() {
665fe06b5adSAdrian McCarthy   static const ConstString FallbackStructName("struct");
666fe06b5adSAdrian McCarthy   return FallbackStructName;
667fe06b5adSAdrian McCarthy }
6688b244e21SEwan Crawford 
669b3f7f69dSAidan Dodds uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
67015f2bd95SEwan Crawford 
671b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
672b9c1b51eSKate Stone     "User",       "Undefined",   "Undefined", "Undefined",
673b9c1b51eSKate Stone     "Undefined",  "Undefined",   "Undefined", // Enum jumps from 0 to 7
674b3f7f69dSAidan Dodds     "L Pixel",    "A Pixel",     "LA Pixel",  "RGB Pixel",
675b3f7f69dSAidan Dodds     "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
67615f2bd95SEwan Crawford 
677b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
67815f2bd95SEwan Crawford     {"None", "None", "None", "None"},
67915f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
68015f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
68115f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
68215f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
68315f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
68415f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
68515f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
68615f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
68715f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
68815f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
68915f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
6902e920715SEwan Crawford     {"bool", "bool2", "bool3", "bool4"},
6912e920715SEwan Crawford     {"packed_565", "packed_565", "packed_565", "packed_565"},
6922e920715SEwan Crawford     {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
6932e920715SEwan Crawford     {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
6942e920715SEwan Crawford     {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
6952e920715SEwan Crawford     {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
6962e920715SEwan Crawford     {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
6972e920715SEwan Crawford 
6982e920715SEwan Crawford     // Handlers
6992e920715SEwan Crawford     {"RS Element", "RS Element", "RS Element", "RS Element"},
7002e920715SEwan Crawford     {"RS Type", "RS Type", "RS Type", "RS Type"},
7012e920715SEwan Crawford     {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
7022e920715SEwan Crawford     {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
7032e920715SEwan Crawford     {"RS Script", "RS Script", "RS Script", "RS Script"},
7042e920715SEwan Crawford 
7052e920715SEwan Crawford     // Deprecated
7062e920715SEwan Crawford     {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
707b9c1b51eSKate Stone     {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
708b9c1b51eSKate Stone      "RS Program Fragment"},
709b9c1b51eSKate Stone     {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
710b9c1b51eSKate Stone      "RS Program Vertex"},
711b9c1b51eSKate Stone     {"RS Program Raster", "RS Program Raster", "RS Program Raster",
712b9c1b51eSKate Stone      "RS Program Raster"},
713b9c1b51eSKate Stone     {"RS Program Store", "RS Program Store", "RS Program Store",
714b9c1b51eSKate Stone      "RS Program Store"},
715b3f7f69dSAidan Dodds     {"RS Font", "RS Font", "RS Font", "RS Font"}};
71678f339d1SEwan Crawford 
717a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
718b9c1b51eSKate Stone enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
719a0f08674SEwan Crawford 
720b9c1b51eSKate Stone // { format enum of single element, format enum of element vector, size of
721b9c1b51eSKate Stone // element}
722b3f7f69dSAidan Dodds const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
723*80af0b9eSLuke Drummond     // RS_TYPE_NONE
724*80af0b9eSLuke Drummond     {eFormatHex, eFormatHex, 1},
725*80af0b9eSLuke Drummond     // RS_TYPE_FLOAT_16
726*80af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat16, 2},
727*80af0b9eSLuke Drummond     // RS_TYPE_FLOAT_32
728*80af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
729*80af0b9eSLuke Drummond     // RS_TYPE_FLOAT_64
730*80af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
731*80af0b9eSLuke Drummond     // RS_TYPE_SIGNED_8
732*80af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
733*80af0b9eSLuke Drummond     // RS_TYPE_SIGNED_16
734*80af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
735*80af0b9eSLuke Drummond     // RS_TYPE_SIGNED_32
736*80af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
737*80af0b9eSLuke Drummond     // RS_TYPE_SIGNED_64
738*80af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
739*80af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_8
740*80af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
741*80af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_16
742*80af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
743*80af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_32
744*80af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
745*80af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_64
746*80af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
747*80af0b9eSLuke Drummond     // RS_TYPE_BOOL
748*80af0b9eSLuke Drummond     {eFormatBoolean, eFormatBoolean, 1},
749*80af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_5_6_5
750*80af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
751*80af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_5_5_5_1
752*80af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
753*80af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_4_4_4_4
754*80af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
755*80af0b9eSLuke Drummond     // RS_TYPE_MATRIX_4X4
756*80af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
757*80af0b9eSLuke Drummond     // RS_TYPE_MATRIX_3X3
758*80af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
759*80af0b9eSLuke Drummond     // RS_TYPE_MATRIX_2X2
760*80af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
761a0f08674SEwan Crawford 
7625ec532a9SColin Riley //------------------------------------------------------------------
7635ec532a9SColin Riley // Static Functions
7645ec532a9SColin Riley //------------------------------------------------------------------
7655ec532a9SColin Riley LanguageRuntime *
766b9c1b51eSKate Stone RenderScriptRuntime::CreateInstance(Process *process,
767b9c1b51eSKate Stone                                     lldb::LanguageType language) {
7685ec532a9SColin Riley 
7695ec532a9SColin Riley   if (language == eLanguageTypeExtRenderScript)
7705ec532a9SColin Riley     return new RenderScriptRuntime(process);
7715ec532a9SColin Riley   else
772b3f7f69dSAidan Dodds     return nullptr;
7735ec532a9SColin Riley }
7745ec532a9SColin Riley 
775*80af0b9eSLuke Drummond // Callback with a module to search for matching symbols. We first check that
776*80af0b9eSLuke Drummond // the module contains RS kernels. Then look for a symbol which matches our
777*80af0b9eSLuke Drummond // kernel name. The breakpoint address is finally set using the address of this
778*80af0b9eSLuke Drummond // symbol.
77998156583SEwan Crawford Searcher::CallbackReturn
780b9c1b51eSKate Stone RSBreakpointResolver::SearchCallback(SearchFilter &filter,
781b9c1b51eSKate Stone                                      SymbolContext &context, Address *, bool) {
78298156583SEwan Crawford   ModuleSP module = context.module_sp;
78398156583SEwan Crawford 
78498156583SEwan Crawford   if (!module)
78598156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
78698156583SEwan Crawford 
78798156583SEwan Crawford   // Is this a module containing renderscript kernels?
788b9c1b51eSKate Stone   if (nullptr ==
789b9c1b51eSKate Stone       module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
790b9c1b51eSKate Stone                                              eSymbolTypeData))
79198156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
79298156583SEwan Crawford 
793b9c1b51eSKate Stone   // Attempt to set a breakpoint on the kernel name symbol within the module
794*80af0b9eSLuke Drummond   // library. If it's not found, it's likely debug info is unavailable - try to
795*80af0b9eSLuke Drummond   // set a breakpoint on <name>.expand.
796b9c1b51eSKate Stone   const Symbol *kernel_sym =
797b9c1b51eSKate Stone       module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
798b9c1b51eSKate Stone   if (!kernel_sym) {
79998156583SEwan Crawford     std::string kernel_name_expanded(m_kernel_name.AsCString());
80098156583SEwan Crawford     kernel_name_expanded.append(".expand");
801b9c1b51eSKate Stone     kernel_sym = module->FindFirstSymbolWithNameAndType(
802b9c1b51eSKate Stone         ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
80398156583SEwan Crawford   }
80498156583SEwan Crawford 
805b9c1b51eSKate Stone   if (kernel_sym) {
80698156583SEwan Crawford     Address bp_addr = kernel_sym->GetAddress();
80798156583SEwan Crawford     if (filter.AddressPasses(bp_addr))
80898156583SEwan Crawford       m_breakpoint->AddLocation(bp_addr);
80998156583SEwan Crawford   }
81098156583SEwan Crawford 
81198156583SEwan Crawford   return Searcher::eCallbackReturnContinue;
81298156583SEwan Crawford }
81398156583SEwan Crawford 
814b9c1b51eSKate Stone void RenderScriptRuntime::Initialize() {
815b9c1b51eSKate Stone   PluginManager::RegisterPlugin(GetPluginNameStatic(),
816b9c1b51eSKate Stone                                 "RenderScript language support", CreateInstance,
817b3f7f69dSAidan Dodds                                 GetCommandObject);
8185ec532a9SColin Riley }
8195ec532a9SColin Riley 
820b9c1b51eSKate Stone void RenderScriptRuntime::Terminate() {
8215ec532a9SColin Riley   PluginManager::UnregisterPlugin(CreateInstance);
8225ec532a9SColin Riley }
8235ec532a9SColin Riley 
824b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginNameStatic() {
825*80af0b9eSLuke Drummond   static ConstString plugin_name("renderscript");
826*80af0b9eSLuke Drummond   return plugin_name;
8275ec532a9SColin Riley }
8285ec532a9SColin Riley 
829ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
830b9c1b51eSKate Stone RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
831b9c1b51eSKate Stone   if (module_sp) {
832ef20b08fSColin Riley     // Is this a module containing renderscript kernels?
833b9c1b51eSKate Stone     const Symbol *info_sym = module_sp->FindFirstSymbolWithNameAndType(
834b9c1b51eSKate Stone         ConstString(".rs.info"), eSymbolTypeData);
835b9c1b51eSKate Stone     if (info_sym) {
836ef20b08fSColin Riley       return eModuleKindKernelObj;
837ef20b08fSColin Riley     }
8384640cde1SColin Riley 
8394640cde1SColin Riley     // Is this the main RS runtime library
8404640cde1SColin Riley     const ConstString rs_lib("libRS.so");
841b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
8424640cde1SColin Riley       return eModuleKindLibRS;
8434640cde1SColin Riley     }
8444640cde1SColin Riley 
8454640cde1SColin Riley     const ConstString rs_driverlib("libRSDriver.so");
846b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
8474640cde1SColin Riley       return eModuleKindDriver;
8484640cde1SColin Riley     }
8494640cde1SColin Riley 
85015f2bd95SEwan Crawford     const ConstString rs_cpureflib("libRSCpuRef.so");
851b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
8524640cde1SColin Riley       return eModuleKindImpl;
8534640cde1SColin Riley     }
854ef20b08fSColin Riley   }
855ef20b08fSColin Riley   return eModuleKindIgnored;
856ef20b08fSColin Riley }
857ef20b08fSColin Riley 
858b9c1b51eSKate Stone bool RenderScriptRuntime::IsRenderScriptModule(
859b9c1b51eSKate Stone     const lldb::ModuleSP &module_sp) {
860ef20b08fSColin Riley   return GetModuleKind(module_sp) != eModuleKindIgnored;
861ef20b08fSColin Riley }
862ef20b08fSColin Riley 
863b9c1b51eSKate Stone void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
864bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
865ef20b08fSColin Riley 
866ef20b08fSColin Riley   size_t num_modules = module_list.GetSize();
867b9c1b51eSKate Stone   for (size_t i = 0; i < num_modules; i++) {
868ef20b08fSColin Riley     auto mod = module_list.GetModuleAtIndex(i);
869b9c1b51eSKate Stone     if (IsRenderScriptModule(mod)) {
870ef20b08fSColin Riley       LoadModule(mod);
871ef20b08fSColin Riley     }
872ef20b08fSColin Riley   }
873ef20b08fSColin Riley }
874ef20b08fSColin Riley 
8755ec532a9SColin Riley //------------------------------------------------------------------
8765ec532a9SColin Riley // PluginInterface protocol
8775ec532a9SColin Riley //------------------------------------------------------------------
878b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginName() {
8795ec532a9SColin Riley   return GetPluginNameStatic();
8805ec532a9SColin Riley }
8815ec532a9SColin Riley 
882b9c1b51eSKate Stone uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; }
8835ec532a9SColin Riley 
884b9c1b51eSKate Stone bool RenderScriptRuntime::IsVTableName(const char *name) { return false; }
8855ec532a9SColin Riley 
886b9c1b51eSKate Stone bool RenderScriptRuntime::GetDynamicTypeAndAddress(
887b9c1b51eSKate Stone     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
8885f57b6eeSEnrico Granata     TypeAndOrName &class_type_or_name, Address &address,
889b9c1b51eSKate Stone     Value::ValueType &value_type) {
8905ec532a9SColin Riley   return false;
8915ec532a9SColin Riley }
8925ec532a9SColin Riley 
893c74275bcSEnrico Granata TypeAndOrName
894b9c1b51eSKate Stone RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
895b9c1b51eSKate Stone                                       ValueObject &static_value) {
896c74275bcSEnrico Granata   return type_and_or_name;
897c74275bcSEnrico Granata }
898c74275bcSEnrico Granata 
899b9c1b51eSKate Stone bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
9005ec532a9SColin Riley   return false;
9015ec532a9SColin Riley }
9025ec532a9SColin Riley 
9035ec532a9SColin Riley lldb::BreakpointResolverSP
904*80af0b9eSLuke Drummond RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bp, bool catch_bp,
905b9c1b51eSKate Stone                                              bool throw_bp) {
9065ec532a9SColin Riley   BreakpointResolverSP resolver_sp;
9075ec532a9SColin Riley   return resolver_sp;
9085ec532a9SColin Riley }
9095ec532a9SColin Riley 
910b9c1b51eSKate Stone const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
911b9c1b51eSKate Stone     {
9124640cde1SColin Riley         // rsdScript
913b9c1b51eSKate Stone         {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
914b9c1b51eSKate Stone                           "NS0_7ScriptCEPKcS7_PKhjj",
915b9c1b51eSKate Stone          "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
916b9c1b51eSKate Stone          "7ScriptCEPKcS7_PKhmj",
917b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
918b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInit},
919b9c1b51eSKate Stone         {"rsdScriptInvokeForEachMulti",
920b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
921b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
922b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
923b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
924b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
925b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
926b9c1b51eSKate Stone         {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
927b9c1b51eSKate Stone                                   "script7ContextEPKNS0_6ScriptEjPvj",
928b9c1b51eSKate Stone          "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
929b9c1b51eSKate Stone          "6ScriptEjPvm",
930b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
931b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
9324640cde1SColin Riley 
9334640cde1SColin Riley         // rsdAllocation
934b9c1b51eSKate Stone         {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
935b9c1b51eSKate Stone                               "ontextEPNS0_10AllocationEb",
936b9c1b51eSKate Stone          "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
937b9c1b51eSKate Stone          "10AllocationEb",
938b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
939b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
940b9c1b51eSKate Stone         {"rsdAllocationRead2D",
941b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
942b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
943b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
944b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
945b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver, nullptr},
946b9c1b51eSKate Stone         {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
947b9c1b51eSKate Stone                                  "ript7ContextEPNS0_10AllocationE",
948b9c1b51eSKate Stone          "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
949b9c1b51eSKate Stone          "10AllocationE",
950b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
951b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
9524640cde1SColin Riley };
9534640cde1SColin Riley 
954b9c1b51eSKate Stone const size_t RenderScriptRuntime::s_runtimeHookCount =
955b9c1b51eSKate Stone     sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
9564640cde1SColin Riley 
957b9c1b51eSKate Stone bool RenderScriptRuntime::HookCallback(void *baton,
958b9c1b51eSKate Stone                                        StoppointCallbackContext *ctx,
959b9c1b51eSKate Stone                                        lldb::user_id_t break_id,
960b9c1b51eSKate Stone                                        lldb::user_id_t break_loc_id) {
961*80af0b9eSLuke Drummond   RuntimeHook *hook = (RuntimeHook *)baton;
962*80af0b9eSLuke Drummond   ExecutionContext exe_ctx(ctx->exe_ctx_ref);
9634640cde1SColin Riley 
964b3f7f69dSAidan Dodds   RenderScriptRuntime *lang_rt =
965*80af0b9eSLuke Drummond       (RenderScriptRuntime *)exe_ctx.GetProcessPtr()->GetLanguageRuntime(
966b9c1b51eSKate Stone           eLanguageTypeExtRenderScript);
9674640cde1SColin Riley 
968*80af0b9eSLuke Drummond   lang_rt->HookCallback(hook, exe_ctx);
9694640cde1SColin Riley 
9704640cde1SColin Riley   return false;
9714640cde1SColin Riley }
9724640cde1SColin Riley 
973*80af0b9eSLuke Drummond void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
974*80af0b9eSLuke Drummond                                        ExecutionContext &exe_ctx) {
9754640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
9764640cde1SColin Riley 
9774640cde1SColin Riley   if (log)
978*80af0b9eSLuke Drummond     log->Printf("%s - '%s'", __FUNCTION__, hook->defn->name);
9794640cde1SColin Riley 
980*80af0b9eSLuke Drummond   if (hook->defn->grabber) {
981*80af0b9eSLuke Drummond     (this->*(hook->defn->grabber))(hook, exe_ctx);
9824640cde1SColin Riley   }
9834640cde1SColin Riley }
9844640cde1SColin Riley 
985b9c1b51eSKate Stone void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
986*80af0b9eSLuke Drummond     RuntimeHook *hook, ExecutionContext &exe_ctx) {
987e09c44b6SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
988e09c44b6SAidan Dodds 
989b9c1b51eSKate Stone   enum {
990f4786785SAidan Dodds     eRsContext = 0,
991f4786785SAidan Dodds     eRsScript,
992f4786785SAidan Dodds     eRsSlot,
993f4786785SAidan Dodds     eRsAIns,
994f4786785SAidan Dodds     eRsInLen,
995f4786785SAidan Dodds     eRsAOut,
996f4786785SAidan Dodds     eRsUsr,
997f4786785SAidan Dodds     eRsUsrLen,
998f4786785SAidan Dodds     eRsSc,
999f4786785SAidan Dodds   };
1000e09c44b6SAidan Dodds 
10011ee07253SSaleem Abdulrasool   std::array<ArgItem, 9> args{{
1002f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Context       *rsc
1003f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Script              *s
1004f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // uint32_t             slot
1005f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Allocation   **aIns
1006f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               inLen
1007f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Allocation          *aout
1008f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const void          *usr
1009f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               usrLen
1010f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall  *sc
10111ee07253SSaleem Abdulrasool   }};
1012e09c44b6SAidan Dodds 
1013*80af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1014b9c1b51eSKate Stone   if (!success) {
1015e09c44b6SAidan Dodds     if (log)
1016b9c1b51eSKate Stone       log->Printf("%s - Error while reading the function parameters",
1017b9c1b51eSKate Stone                   __FUNCTION__);
1018e09c44b6SAidan Dodds     return;
1019e09c44b6SAidan Dodds   }
1020e09c44b6SAidan Dodds 
1021e09c44b6SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1022*80af0b9eSLuke Drummond   Error err;
1023e09c44b6SAidan Dodds   std::vector<uint64_t> allocs;
1024e09c44b6SAidan Dodds 
1025e09c44b6SAidan Dodds   // traverse allocation list
1026b9c1b51eSKate Stone   for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1027e09c44b6SAidan Dodds     // calculate offest to allocation pointer
1028f4786785SAidan Dodds     const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1029e09c44b6SAidan Dodds 
1030*80af0b9eSLuke Drummond     // Note: due to little endian layout, reading 32bits or 64bits into res
1031*80af0b9eSLuke Drummond     // will give the correct results.
1032*80af0b9eSLuke Drummond     uint64_t result = 0;
1033*80af0b9eSLuke Drummond     size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
1034*80af0b9eSLuke Drummond     if (read != target_ptr_size || !err.Success()) {
1035e09c44b6SAidan Dodds       if (log)
1036b9c1b51eSKate Stone         log->Printf(
1037b9c1b51eSKate Stone             "%s - Error while reading allocation list argument %" PRIu64,
1038b9c1b51eSKate Stone             __FUNCTION__, i);
1039b9c1b51eSKate Stone     } else {
1040*80af0b9eSLuke Drummond       allocs.push_back(result);
1041e09c44b6SAidan Dodds     }
1042e09c44b6SAidan Dodds   }
1043e09c44b6SAidan Dodds 
1044e09c44b6SAidan Dodds   // if there is an output allocation track it
1045*80af0b9eSLuke Drummond   if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
1046*80af0b9eSLuke Drummond     allocs.push_back(alloc_out);
1047e09c44b6SAidan Dodds   }
1048e09c44b6SAidan Dodds 
1049e09c44b6SAidan Dodds   // for all allocations we have found
1050b9c1b51eSKate Stone   for (const uint64_t alloc_addr : allocs) {
10515d057637SLuke Drummond     AllocationDetails *alloc = LookUpAllocation(alloc_addr);
10525d057637SLuke Drummond     if (!alloc)
10535d057637SLuke Drummond       alloc = CreateAllocation(alloc_addr);
10545d057637SLuke Drummond 
1055b9c1b51eSKate Stone     if (alloc) {
1056e09c44b6SAidan Dodds       // save the allocation address
1057b9c1b51eSKate Stone       if (alloc->address.isValid()) {
1058e09c44b6SAidan Dodds         // check the allocation address we already have matches
1059e09c44b6SAidan Dodds         assert(*alloc->address.get() == alloc_addr);
1060b9c1b51eSKate Stone       } else {
1061e09c44b6SAidan Dodds         alloc->address = alloc_addr;
1062e09c44b6SAidan Dodds       }
1063e09c44b6SAidan Dodds 
1064e09c44b6SAidan Dodds       // save the context
1065b9c1b51eSKate Stone       if (log) {
1066b9c1b51eSKate Stone         if (alloc->context.isValid() &&
1067b9c1b51eSKate Stone             *alloc->context.get() != addr_t(args[eRsContext]))
1068b9c1b51eSKate Stone           log->Printf("%s - Allocation used by multiple contexts",
1069b9c1b51eSKate Stone                       __FUNCTION__);
1070e09c44b6SAidan Dodds       }
1071f4786785SAidan Dodds       alloc->context = addr_t(args[eRsContext]);
1072e09c44b6SAidan Dodds     }
1073e09c44b6SAidan Dodds   }
1074e09c44b6SAidan Dodds 
1075e09c44b6SAidan Dodds   // make sure we track this script object
1076b9c1b51eSKate Stone   if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1077b9c1b51eSKate Stone           LookUpScript(addr_t(args[eRsScript]), true)) {
1078b9c1b51eSKate Stone     if (log) {
1079b9c1b51eSKate Stone       if (script->context.isValid() &&
1080b9c1b51eSKate Stone           *script->context.get() != addr_t(args[eRsContext]))
1081b3f7f69dSAidan Dodds         log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1082e09c44b6SAidan Dodds     }
1083f4786785SAidan Dodds     script->context = addr_t(args[eRsContext]);
1084e09c44b6SAidan Dodds   }
1085e09c44b6SAidan Dodds }
1086e09c44b6SAidan Dodds 
1087*80af0b9eSLuke Drummond void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1088b9c1b51eSKate Stone                                               ExecutionContext &context) {
10894640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
10904640cde1SColin Riley 
1091b9c1b51eSKate Stone   enum {
1092f4786785SAidan Dodds     eRsContext,
1093f4786785SAidan Dodds     eRsScript,
1094f4786785SAidan Dodds     eRsId,
1095f4786785SAidan Dodds     eRsData,
1096f4786785SAidan Dodds     eRsLength,
1097f4786785SAidan Dodds   };
10984640cde1SColin Riley 
10991ee07253SSaleem Abdulrasool   std::array<ArgItem, 5> args{{
1100f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1101f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsScript
1102f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsId
1103f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsData
1104f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsLength
11051ee07253SSaleem Abdulrasool   }};
11064640cde1SColin Riley 
1107f4786785SAidan Dodds   bool success = GetArgs(context, &args[0], args.size());
1108b9c1b51eSKate Stone   if (!success) {
110982780287SAidan Dodds     if (log)
1110b3f7f69dSAidan Dodds       log->Printf("%s - error reading the function parameters.", __FUNCTION__);
111182780287SAidan Dodds     return;
111282780287SAidan Dodds   }
11134640cde1SColin Riley 
1114b9c1b51eSKate Stone   if (log) {
1115b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1116b9c1b51eSKate Stone                 ":%" PRIu64 "bytes.",
1117b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1118b9c1b51eSKate Stone                 uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1119f4786785SAidan Dodds                 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
11204640cde1SColin Riley 
1121f4786785SAidan Dodds     addr_t script_addr = addr_t(args[eRsScript]);
1122b9c1b51eSKate Stone     if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
11234640cde1SColin Riley       auto rsm = m_scriptMappings[script_addr];
1124b9c1b51eSKate Stone       if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1125f4786785SAidan Dodds         auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1126b9c1b51eSKate Stone         log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__,
1127b9c1b51eSKate Stone                     rsg.m_name.AsCString(),
1128f4786785SAidan Dodds                     rsm->m_module->GetFileSpec().GetFilename().AsCString());
11294640cde1SColin Riley       }
11304640cde1SColin Riley     }
11314640cde1SColin Riley   }
11324640cde1SColin Riley }
11334640cde1SColin Riley 
1134*80af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
1135*80af0b9eSLuke Drummond                                                 ExecutionContext &exe_ctx) {
11364640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11374640cde1SColin Riley 
1138b9c1b51eSKate Stone   enum { eRsContext, eRsAlloc, eRsForceZero };
11394640cde1SColin Riley 
11401ee07253SSaleem Abdulrasool   std::array<ArgItem, 3> args{{
1141f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1142f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1143f4786785SAidan Dodds       ArgItem{ArgItem::eBool, 0},    // eRsForceZero
11441ee07253SSaleem Abdulrasool   }};
11454640cde1SColin Riley 
1146*80af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1147*80af0b9eSLuke Drummond   if (!success) {
114882780287SAidan Dodds     if (log)
1149b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters",
1150b9c1b51eSKate Stone                   __FUNCTION__);
1151*80af0b9eSLuke Drummond     return;
115282780287SAidan Dodds   }
11534640cde1SColin Riley 
11544640cde1SColin Riley   if (log)
1155b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1156b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1157f4786785SAidan Dodds                 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
115878f339d1SEwan Crawford 
11595d057637SLuke Drummond   AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
116078f339d1SEwan Crawford   if (alloc)
1161f4786785SAidan Dodds     alloc->context = uint64_t(args[eRsContext]);
11624640cde1SColin Riley }
11634640cde1SColin Riley 
1164*80af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
1165*80af0b9eSLuke Drummond                                                    ExecutionContext &exe_ctx) {
1166e69df382SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1167e69df382SEwan Crawford 
1168b9c1b51eSKate Stone   enum {
1169f4786785SAidan Dodds     eRsContext,
1170f4786785SAidan Dodds     eRsAlloc,
1171f4786785SAidan Dodds   };
1172e69df382SEwan Crawford 
11731ee07253SSaleem Abdulrasool   std::array<ArgItem, 2> args{{
1174f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1175f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
11761ee07253SSaleem Abdulrasool   }};
1177f4786785SAidan Dodds 
1178*80af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1179b9c1b51eSKate Stone   if (!success) {
1180e69df382SEwan Crawford     if (log)
1181b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1182b9c1b51eSKate Stone                   __FUNCTION__);
1183b3f7f69dSAidan Dodds     return;
1184e69df382SEwan Crawford   }
1185e69df382SEwan Crawford 
1186e69df382SEwan Crawford   if (log)
1187b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1188b9c1b51eSKate Stone                 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1189e69df382SEwan Crawford 
1190b9c1b51eSKate Stone   for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1191e69df382SEwan Crawford     auto &allocation_ap = *iter; // get the unique pointer
1192b9c1b51eSKate Stone     if (allocation_ap->address.isValid() &&
1193b9c1b51eSKate Stone         *allocation_ap->address.get() == addr_t(args[eRsAlloc])) {
1194e69df382SEwan Crawford       m_allocations.erase(iter);
1195e69df382SEwan Crawford       if (log)
1196b3f7f69dSAidan Dodds         log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1197e69df382SEwan Crawford       return;
1198e69df382SEwan Crawford     }
1199e69df382SEwan Crawford   }
1200e69df382SEwan Crawford 
1201e69df382SEwan Crawford   if (log)
1202b3f7f69dSAidan Dodds     log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1203e69df382SEwan Crawford }
1204e69df382SEwan Crawford 
1205*80af0b9eSLuke Drummond void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
1206*80af0b9eSLuke Drummond                                             ExecutionContext &exe_ctx) {
12074640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
12084640cde1SColin Riley 
1209*80af0b9eSLuke Drummond   Error err;
1210*80af0b9eSLuke Drummond   Process *process = exe_ctx.GetProcessPtr();
12114640cde1SColin Riley 
1212b9c1b51eSKate Stone   enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
12134640cde1SColin Riley 
1214b9c1b51eSKate Stone   std::array<ArgItem, 4> args{
1215b9c1b51eSKate Stone       {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
12161ee07253SSaleem Abdulrasool        ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
1217*80af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1218b9c1b51eSKate Stone   if (!success) {
121982780287SAidan Dodds     if (log)
1220b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1221b9c1b51eSKate Stone                   __FUNCTION__);
122282780287SAidan Dodds     return;
122382780287SAidan Dodds   }
122482780287SAidan Dodds 
1225*80af0b9eSLuke Drummond   std::string res_name;
1226*80af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
1227*80af0b9eSLuke Drummond   if (err.Fail()) {
12284640cde1SColin Riley     if (log)
1229*80af0b9eSLuke Drummond       log->Printf("%s - error reading res_name: %s.", __FUNCTION__,
1230*80af0b9eSLuke Drummond                   err.AsCString());
12314640cde1SColin Riley   }
12324640cde1SColin Riley 
1233*80af0b9eSLuke Drummond   std::string cache_dir;
1234*80af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
1235*80af0b9eSLuke Drummond   if (err.Fail()) {
12364640cde1SColin Riley     if (log)
1237*80af0b9eSLuke Drummond       log->Printf("%s - error reading cache_dir: %s.", __FUNCTION__,
1238*80af0b9eSLuke Drummond                   err.AsCString());
12394640cde1SColin Riley   }
12404640cde1SColin Riley 
12414640cde1SColin Riley   if (log)
1242b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1243b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1244*80af0b9eSLuke Drummond                 uint64_t(args[eRsScript]), res_name.c_str(), cache_dir.c_str());
12454640cde1SColin Riley 
1246*80af0b9eSLuke Drummond   if (res_name.size() > 0) {
12474640cde1SColin Riley     StreamString strm;
1248*80af0b9eSLuke Drummond     strm.Printf("librs.%s.so", res_name.c_str());
12494640cde1SColin Riley 
1250f4786785SAidan Dodds     ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1251b9c1b51eSKate Stone     if (script) {
125278f339d1SEwan Crawford       script->type = ScriptDetails::eScriptC;
1253*80af0b9eSLuke Drummond       script->cache_dir = cache_dir;
1254*80af0b9eSLuke Drummond       script->res_name = res_name;
1255*80af0b9eSLuke Drummond       script->shared_lib = strm.GetData();
1256f4786785SAidan Dodds       script->context = addr_t(args[eRsContext]);
125778f339d1SEwan Crawford     }
12584640cde1SColin Riley 
12594640cde1SColin Riley     if (log)
1260b9c1b51eSKate Stone       log->Printf("%s - '%s' tagged with context 0x%" PRIx64
1261b9c1b51eSKate Stone                   " and script 0x%" PRIx64 ".",
1262b9c1b51eSKate Stone                   __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1263b9c1b51eSKate Stone                   uint64_t(args[eRsScript]));
1264b9c1b51eSKate Stone   } else if (log) {
1265b3f7f69dSAidan Dodds     log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
12664640cde1SColin Riley   }
12674640cde1SColin Riley }
12684640cde1SColin Riley 
1269b9c1b51eSKate Stone void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1270b9c1b51eSKate Stone                                            ModuleKind kind) {
12714640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
12724640cde1SColin Riley 
1273b9c1b51eSKate Stone   if (!module) {
12744640cde1SColin Riley     return;
12754640cde1SColin Riley   }
12764640cde1SColin Riley 
127782780287SAidan Dodds   Target &target = GetProcess()->GetTarget();
1278*80af0b9eSLuke Drummond   llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
127982780287SAidan Dodds 
1280*80af0b9eSLuke Drummond   if (machine != llvm::Triple::ArchType::x86 &&
1281*80af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::arm &&
1282*80af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::aarch64 &&
1283*80af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mipsel &&
1284*80af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mips64el &&
1285*80af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::x86_64) {
12864640cde1SColin Riley     if (log)
1287b3f7f69dSAidan Dodds       log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
12884640cde1SColin Riley     return;
12894640cde1SColin Riley   }
12904640cde1SColin Riley 
1291*80af0b9eSLuke Drummond   uint32_t target_ptr_size = target.GetArchitecture().GetAddressByteSize();
12924640cde1SColin Riley 
1293b9c1b51eSKate Stone   for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
12944640cde1SColin Riley     const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1295b9c1b51eSKate Stone     if (hook_defn->kind != kind) {
12964640cde1SColin Riley       continue;
12974640cde1SColin Riley     }
12984640cde1SColin Riley 
1299*80af0b9eSLuke Drummond     const char *symbol_name = (target_ptr_size == 4)
1300*80af0b9eSLuke Drummond                                   ? hook_defn->symbol_name_m32
1301b9c1b51eSKate Stone                                   : hook_defn->symbol_name_m64;
130282780287SAidan Dodds 
1303b9c1b51eSKate Stone     const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1304b9c1b51eSKate Stone         ConstString(symbol_name), eSymbolTypeCode);
1305b9c1b51eSKate Stone     if (!sym) {
1306b9c1b51eSKate Stone       if (log) {
1307b3f7f69dSAidan Dodds         log->Printf("%s - symbol '%s' related to the function %s not found",
1308b3f7f69dSAidan Dodds                     __FUNCTION__, symbol_name, hook_defn->name);
130982780287SAidan Dodds       }
131082780287SAidan Dodds       continue;
131182780287SAidan Dodds     }
13124640cde1SColin Riley 
1313358cf1eaSGreg Clayton     addr_t addr = sym->GetLoadAddress(&target);
1314b9c1b51eSKate Stone     if (addr == LLDB_INVALID_ADDRESS) {
13154640cde1SColin Riley       if (log)
1316b9c1b51eSKate Stone         log->Printf("%s - unable to resolve the address of hook function '%s' "
1317b9c1b51eSKate Stone                     "with symbol '%s'.",
1318b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, symbol_name);
13194640cde1SColin Riley       continue;
1320b9c1b51eSKate Stone     } else {
132182780287SAidan Dodds       if (log)
1322b3f7f69dSAidan Dodds         log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1323b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, addr);
132482780287SAidan Dodds     }
13254640cde1SColin Riley 
13264640cde1SColin Riley     RuntimeHookSP hook(new RuntimeHook());
13274640cde1SColin Riley     hook->address = addr;
13284640cde1SColin Riley     hook->defn = hook_defn;
13294640cde1SColin Riley     hook->bp_sp = target.CreateBreakpoint(addr, true, false);
13304640cde1SColin Riley     hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
13314640cde1SColin Riley     m_runtimeHooks[addr] = hook;
1332b9c1b51eSKate Stone     if (log) {
1333b9c1b51eSKate Stone       log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64
1334b9c1b51eSKate Stone                   " at 0x%" PRIx64 ".",
1335b9c1b51eSKate Stone                   __FUNCTION__, hook_defn->name,
1336b9c1b51eSKate Stone                   module->GetFileSpec().GetFilename().AsCString(),
1337b3f7f69dSAidan Dodds                   (uint64_t)hook_defn->version, (uint64_t)addr);
13384640cde1SColin Riley     }
13394640cde1SColin Riley   }
13404640cde1SColin Riley }
13414640cde1SColin Riley 
1342b9c1b51eSKate Stone void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
13434640cde1SColin Riley   if (!rsmodule_sp)
13444640cde1SColin Riley     return;
13454640cde1SColin Riley 
13464640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
13474640cde1SColin Riley 
13484640cde1SColin Riley   const ModuleSP module = rsmodule_sp->m_module;
13494640cde1SColin Riley   const FileSpec &file = module->GetPlatformFileSpec();
13504640cde1SColin Riley 
135178f339d1SEwan Crawford   // Iterate over all of the scripts that we currently know of.
135278f339d1SEwan Crawford   // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
1353b9c1b51eSKate Stone   for (const auto &rs_script : m_scripts) {
135478f339d1SEwan Crawford     // Extract the expected .so file path for this script.
1355*80af0b9eSLuke Drummond     std::string shared_lib;
1356*80af0b9eSLuke Drummond     if (!rs_script->shared_lib.get(shared_lib))
135778f339d1SEwan Crawford       continue;
135878f339d1SEwan Crawford 
135978f339d1SEwan Crawford     // Only proceed if the module that has loaded corresponds to this script.
1360*80af0b9eSLuke Drummond     if (file.GetFilename() != ConstString(shared_lib.c_str()))
136178f339d1SEwan Crawford       continue;
136278f339d1SEwan Crawford 
136378f339d1SEwan Crawford     // Obtain the script address which we use as a key.
136478f339d1SEwan Crawford     lldb::addr_t script;
136578f339d1SEwan Crawford     if (!rs_script->script.get(script))
136678f339d1SEwan Crawford       continue;
136778f339d1SEwan Crawford 
136878f339d1SEwan Crawford     // If we have a script mapping for the current script.
1369b9c1b51eSKate Stone     if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
137078f339d1SEwan Crawford       // if the module we have stored is different to the one we just received.
1371b9c1b51eSKate Stone       if (m_scriptMappings[script] != rsmodule_sp) {
13724640cde1SColin Riley         if (log)
1373b9c1b51eSKate Stone           log->Printf(
1374b9c1b51eSKate Stone               "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1375b9c1b51eSKate Stone               __FUNCTION__, (uint64_t)script,
1376b9c1b51eSKate Stone               rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
13774640cde1SColin Riley       }
13784640cde1SColin Riley     }
137978f339d1SEwan Crawford     // We don't have a script mapping for the current script.
1380b9c1b51eSKate Stone     else {
138178f339d1SEwan Crawford       // Obtain the script resource name.
1382*80af0b9eSLuke Drummond       std::string res_name;
1383*80af0b9eSLuke Drummond       if (rs_script->res_name.get(res_name))
138478f339d1SEwan Crawford         // Set the modules resource name.
1385*80af0b9eSLuke Drummond         rsmodule_sp->m_resname = res_name;
138678f339d1SEwan Crawford       // Add Script/Module pair to map.
138778f339d1SEwan Crawford       m_scriptMappings[script] = rsmodule_sp;
13884640cde1SColin Riley       if (log)
1389b9c1b51eSKate Stone         log->Printf(
1390b9c1b51eSKate Stone             "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1391b9c1b51eSKate Stone             __FUNCTION__, (uint64_t)script,
1392b9c1b51eSKate Stone             rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
13934640cde1SColin Riley     }
13944640cde1SColin Riley   }
13954640cde1SColin Riley }
13964640cde1SColin Riley 
1397b9c1b51eSKate Stone // Uses the Target API to evaluate the expression passed as a parameter to the
1398*80af0b9eSLuke Drummond // function The result of that expression is returned an unsigned 64 bit int,
1399*80af0b9eSLuke Drummond // via the result* parameter. Function returns true on success, and false on
1400*80af0b9eSLuke Drummond // failure
1401*80af0b9eSLuke Drummond bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1402b9c1b51eSKate Stone                                            StackFrame *frame_ptr,
1403b9c1b51eSKate Stone                                            uint64_t *result) {
140415f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
140515f2bd95SEwan Crawford   if (log)
1406*80af0b9eSLuke Drummond     log->Printf("%s(%s)", __FUNCTION__, expr);
140715f2bd95SEwan Crawford 
140815f2bd95SEwan Crawford   ValueObjectSP expr_result;
14098433fdbeSAidan Dodds   EvaluateExpressionOptions options;
14108433fdbeSAidan Dodds   options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
141115f2bd95SEwan Crawford   // Perform the actual expression evaluation
1412*80af0b9eSLuke Drummond   auto &target = GetProcess()->GetTarget();
1413*80af0b9eSLuke Drummond   target.EvaluateExpression(expr, frame_ptr, expr_result, options);
141415f2bd95SEwan Crawford 
1415b9c1b51eSKate Stone   if (!expr_result) {
141615f2bd95SEwan Crawford     if (log)
1417b3f7f69dSAidan Dodds       log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
141815f2bd95SEwan Crawford     return false;
141915f2bd95SEwan Crawford   }
142015f2bd95SEwan Crawford 
142115f2bd95SEwan Crawford   // The result of the expression is invalid
1422b9c1b51eSKate Stone   if (!expr_result->GetError().Success()) {
142315f2bd95SEwan Crawford     Error err = expr_result->GetError();
1424*80af0b9eSLuke Drummond     // Expression returned is void, so this is actually a success
1425*80af0b9eSLuke Drummond     if (err.GetError() == UserExpression::kNoResult) {
142615f2bd95SEwan Crawford       if (log)
1427b3f7f69dSAidan Dodds         log->Printf("%s - expression returned void.", __FUNCTION__);
142815f2bd95SEwan Crawford 
142915f2bd95SEwan Crawford       result = nullptr;
143015f2bd95SEwan Crawford       return true;
143115f2bd95SEwan Crawford     }
143215f2bd95SEwan Crawford 
143315f2bd95SEwan Crawford     if (log)
1434b3f7f69dSAidan Dodds       log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1435b3f7f69dSAidan Dodds                   err.AsCString());
143615f2bd95SEwan Crawford     return false;
143715f2bd95SEwan Crawford   }
143815f2bd95SEwan Crawford 
143915f2bd95SEwan Crawford   bool success = false;
1440*80af0b9eSLuke Drummond   // We only read the result as an uint32_t.
1441*80af0b9eSLuke Drummond   *result = expr_result->GetValueAsUnsigned(0, &success);
144215f2bd95SEwan Crawford 
1443b9c1b51eSKate Stone   if (!success) {
144415f2bd95SEwan Crawford     if (log)
1445b9c1b51eSKate Stone       log->Printf("%s - couldn't convert expression result to uint32_t",
1446b9c1b51eSKate Stone                   __FUNCTION__);
144715f2bd95SEwan Crawford     return false;
144815f2bd95SEwan Crawford   }
144915f2bd95SEwan Crawford 
145015f2bd95SEwan Crawford   return true;
145115f2bd95SEwan Crawford }
145215f2bd95SEwan Crawford 
1453b9c1b51eSKate Stone namespace {
1454836d9651SEwan Crawford // Used to index expression format strings
1455b9c1b51eSKate Stone enum ExpressionStrings {
1456836d9651SEwan Crawford   eExprGetOffsetPtr = 0,
1457836d9651SEwan Crawford   eExprAllocGetType,
1458836d9651SEwan Crawford   eExprTypeDimX,
1459836d9651SEwan Crawford   eExprTypeDimY,
1460836d9651SEwan Crawford   eExprTypeDimZ,
1461836d9651SEwan Crawford   eExprTypeElemPtr,
1462836d9651SEwan Crawford   eExprElementType,
1463836d9651SEwan Crawford   eExprElementKind,
1464836d9651SEwan Crawford   eExprElementVec,
1465836d9651SEwan Crawford   eExprElementFieldCount,
1466836d9651SEwan Crawford   eExprSubelementsId,
1467836d9651SEwan Crawford   eExprSubelementsName,
1468ea0636b5SEwan Crawford   eExprSubelementsArrSize,
1469ea0636b5SEwan Crawford 
1470*80af0b9eSLuke Drummond   _eExprLast // keep at the end, implicit size of the array runtime_expressions
1471836d9651SEwan Crawford };
147215f2bd95SEwan Crawford 
1473ea0636b5SEwan Crawford // max length of an expanded expression
1474ea0636b5SEwan Crawford const int jit_max_expr_size = 512;
1475ea0636b5SEwan Crawford 
1476ea0636b5SEwan Crawford // Retrieve the string to JIT for the given expression
1477b9c1b51eSKate Stone const char *JITTemplate(ExpressionStrings e) {
1478ea0636b5SEwan Crawford   // Format strings containing the expressions we may need to evaluate.
1479*80af0b9eSLuke Drummond   static std::array<const char *, _eExprLast> runtime_expressions = {
1480b9c1b51eSKate Stone       {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1481b9c1b51eSKate Stone        "(int*)_"
1482b9c1b51eSKate Stone        "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1483b9c1b51eSKate Stone        "CubemapFace"
1484577570b4SAidan Dodds        "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)",
148515f2bd95SEwan Crawford 
148615f2bd95SEwan Crawford        // Type* rsaAllocationGetType(Context*, Allocation*)
1487577570b4SAidan Dodds        "(void*)rsaAllocationGetType(0x%" PRIx64 ", 0x%" PRIx64 ")",
148815f2bd95SEwan Crawford 
1489*80af0b9eSLuke Drummond        // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
1490*80af0b9eSLuke Drummond        // data in the following way mHal.state.dimX; mHal.state.dimY;
1491*80af0b9eSLuke Drummond        // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement; into
1492*80af0b9eSLuke Drummond        // typeData Need to specify 32 or 64 bit for uint_t since this differs
1493*80af0b9eSLuke Drummond        // between devices
1494b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1495b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[0]", // X dim
1496b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1497b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[1]", // Y dim
1498b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1499b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[2]", // Z dim
1500b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1501b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[5]", // Element ptr
150215f2bd95SEwan Crawford 
150315f2bd95SEwan Crawford        // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1504b9c1b51eSKate Stone        // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1505b9c1b51eSKate Stone        // elemData
1506b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1507b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[0]", // Type
1508b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1509b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[1]", // Kind
1510b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1511b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[3]", // Vector Size
1512b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1513b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[4]", // Field Count
15148b244e21SEwan Crawford 
1515b9c1b51eSKate Stone        // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
1516*80af0b9eSLuke Drummond        // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1517b9c1b51eSKate Stone        // Needed for Allocations of structs to gather details about
1518*80af0b9eSLuke Drummond        // fields/Subelements Element* of field
1519b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1520b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1521b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1522b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]",
15238b244e21SEwan Crawford 
1524577570b4SAidan Dodds        // Name of field
1525b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1526b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1527b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1528b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]",
15298b244e21SEwan Crawford 
1530577570b4SAidan Dodds        // Array size of field
1531b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1532b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1533b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1534b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}};
1535ea0636b5SEwan Crawford 
1536*80af0b9eSLuke Drummond   return runtime_expressions[e];
1537ea0636b5SEwan Crawford }
1538ea0636b5SEwan Crawford } // end of the anonymous namespace
1539ea0636b5SEwan Crawford 
1540*80af0b9eSLuke Drummond // JITs the RS runtime for the internal data pointer of an allocation. Is passed
1541*80af0b9eSLuke Drummond // x,y,z coordinates for the pointer to a specific element. Then sets the
1542*80af0b9eSLuke Drummond // data_ptr member in Allocation with the result. Returns true on success, false
1543*80af0b9eSLuke Drummond // otherwise
1544*80af0b9eSLuke Drummond bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1545b9c1b51eSKate Stone                                          StackFrame *frame_ptr, uint32_t x,
1546b9c1b51eSKate Stone                                          uint32_t y, uint32_t z) {
154715f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
154815f2bd95SEwan Crawford 
1549*80af0b9eSLuke Drummond   if (!alloc->address.isValid()) {
155015f2bd95SEwan Crawford     if (log)
1551b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
155215f2bd95SEwan Crawford     return false;
155315f2bd95SEwan Crawford   }
155415f2bd95SEwan Crawford 
1555*80af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
1556*80af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
155715f2bd95SEwan Crawford 
1558*80af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1559*80af0b9eSLuke Drummond                          *alloc->address.get(), x, y, z);
1560*80af0b9eSLuke Drummond   if (written < 0) {
156115f2bd95SEwan Crawford     if (log)
1562b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
156315f2bd95SEwan Crawford     return false;
1564*80af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
156515f2bd95SEwan Crawford     if (log)
1566b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
156715f2bd95SEwan Crawford     return false;
156815f2bd95SEwan Crawford   }
156915f2bd95SEwan Crawford 
157015f2bd95SEwan Crawford   uint64_t result = 0;
1571*80af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
157215f2bd95SEwan Crawford     return false;
157315f2bd95SEwan Crawford 
1574*80af0b9eSLuke Drummond   addr_t data_ptr = static_cast<lldb::addr_t>(result);
1575*80af0b9eSLuke Drummond   alloc->data_ptr = data_ptr;
157615f2bd95SEwan Crawford 
157715f2bd95SEwan Crawford   return true;
157815f2bd95SEwan Crawford }
157915f2bd95SEwan Crawford 
158015f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
1581*80af0b9eSLuke Drummond // Then sets the type_ptr member in Allocation with the result. Returns true on
1582*80af0b9eSLuke Drummond // success, false otherwise
1583*80af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1584b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
158515f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
158615f2bd95SEwan Crawford 
1587*80af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->context.isValid()) {
158815f2bd95SEwan Crawford     if (log)
1589b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
159015f2bd95SEwan Crawford     return false;
159115f2bd95SEwan Crawford   }
159215f2bd95SEwan Crawford 
1593*80af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprAllocGetType);
1594*80af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
159515f2bd95SEwan Crawford 
1596*80af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1597*80af0b9eSLuke Drummond                          *alloc->context.get(), *alloc->address.get());
1598*80af0b9eSLuke Drummond   if (written < 0) {
159915f2bd95SEwan Crawford     if (log)
1600b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
160115f2bd95SEwan Crawford     return false;
1602*80af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
160315f2bd95SEwan Crawford     if (log)
1604b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
160515f2bd95SEwan Crawford     return false;
160615f2bd95SEwan Crawford   }
160715f2bd95SEwan Crawford 
160815f2bd95SEwan Crawford   uint64_t result = 0;
1609*80af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
161015f2bd95SEwan Crawford     return false;
161115f2bd95SEwan Crawford 
161215f2bd95SEwan Crawford   addr_t type_ptr = static_cast<lldb::addr_t>(result);
1613*80af0b9eSLuke Drummond   alloc->type_ptr = type_ptr;
161415f2bd95SEwan Crawford 
161515f2bd95SEwan Crawford   return true;
161615f2bd95SEwan Crawford }
161715f2bd95SEwan Crawford 
1618b9c1b51eSKate Stone // JITs the RS runtime for information about the dimensions and type of an
1619*80af0b9eSLuke Drummond // allocation Then sets dimension and element_ptr members in Allocation with the
1620*80af0b9eSLuke Drummond // result. Returns true on success, false otherwise
1621*80af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1622b9c1b51eSKate Stone                                         StackFrame *frame_ptr) {
162315f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
162415f2bd95SEwan Crawford 
1625*80af0b9eSLuke Drummond   if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
162615f2bd95SEwan Crawford     if (log)
1627b3f7f69dSAidan Dodds       log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
162815f2bd95SEwan Crawford     return false;
162915f2bd95SEwan Crawford   }
163015f2bd95SEwan Crawford 
163115f2bd95SEwan Crawford   // Expression is different depending on if device is 32 or 64 bit
1632*80af0b9eSLuke Drummond   uint32_t target_ptr_size =
1633b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
1634*80af0b9eSLuke Drummond   const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
163515f2bd95SEwan Crawford 
163615f2bd95SEwan Crawford   // We want 4 elements from packed data
1637b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
1638b9c1b51eSKate Stone   assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) &&
1639b9c1b51eSKate Stone          "Invalid number of expressions");
164015f2bd95SEwan Crawford 
1641*80af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
164215f2bd95SEwan Crawford   uint64_t results[num_exprs];
164315f2bd95SEwan Crawford 
1644b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; ++i) {
1645*80af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
1646*80af0b9eSLuke Drummond     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, bits,
1647*80af0b9eSLuke Drummond                            *alloc->context.get(), *alloc->type_ptr.get());
1648*80af0b9eSLuke Drummond     if (written < 0) {
164915f2bd95SEwan Crawford       if (log)
1650b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
165115f2bd95SEwan Crawford       return false;
1652*80af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
165315f2bd95SEwan Crawford       if (log)
1654b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
165515f2bd95SEwan Crawford       return false;
165615f2bd95SEwan Crawford     }
165715f2bd95SEwan Crawford 
165815f2bd95SEwan Crawford     // Perform expression evaluation
1659*80af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
166015f2bd95SEwan Crawford       return false;
166115f2bd95SEwan Crawford   }
166215f2bd95SEwan Crawford 
166315f2bd95SEwan Crawford   // Assign results to allocation members
166415f2bd95SEwan Crawford   AllocationDetails::Dimension dims;
166515f2bd95SEwan Crawford   dims.dim_1 = static_cast<uint32_t>(results[0]);
166615f2bd95SEwan Crawford   dims.dim_2 = static_cast<uint32_t>(results[1]);
166715f2bd95SEwan Crawford   dims.dim_3 = static_cast<uint32_t>(results[2]);
1668*80af0b9eSLuke Drummond   alloc->dimension = dims;
166915f2bd95SEwan Crawford 
1670*80af0b9eSLuke Drummond   addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
1671*80af0b9eSLuke Drummond   alloc->element.element_ptr = element_ptr;
167215f2bd95SEwan Crawford 
167315f2bd95SEwan Crawford   if (log)
1674b9c1b51eSKate Stone     log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
1675b9c1b51eSKate Stone                 ") Element*: 0x%" PRIx64 ".",
1676*80af0b9eSLuke Drummond                 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
167715f2bd95SEwan Crawford 
167815f2bd95SEwan Crawford   return true;
167915f2bd95SEwan Crawford }
168015f2bd95SEwan Crawford 
1681*80af0b9eSLuke Drummond // JITs the RS runtime for information about the Element of an allocation Then
1682*80af0b9eSLuke Drummond // sets type, type_vec_size, field_count and type_kind members in Element with
1683*80af0b9eSLuke Drummond // the result. Returns true on success, false otherwise
1684b9c1b51eSKate Stone bool RenderScriptRuntime::JITElementPacked(Element &elem,
1685b9c1b51eSKate Stone                                            const lldb::addr_t context,
1686b9c1b51eSKate Stone                                            StackFrame *frame_ptr) {
168715f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
168815f2bd95SEwan Crawford 
1689b9c1b51eSKate Stone   if (!elem.element_ptr.isValid()) {
169015f2bd95SEwan Crawford     if (log)
1691b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
169215f2bd95SEwan Crawford     return false;
169315f2bd95SEwan Crawford   }
169415f2bd95SEwan Crawford 
16958b244e21SEwan Crawford   // We want 4 elements from packed data
1696b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
1697b9c1b51eSKate Stone   assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) &&
1698b9c1b51eSKate Stone          "Invalid number of expressions");
169915f2bd95SEwan Crawford 
1700*80af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
170115f2bd95SEwan Crawford   uint64_t results[num_exprs];
170215f2bd95SEwan Crawford 
1703b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; i++) {
1704*80af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
1705*80af0b9eSLuke Drummond     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
1706*80af0b9eSLuke Drummond                            *elem.element_ptr.get());
1707*80af0b9eSLuke Drummond     if (written < 0) {
170815f2bd95SEwan Crawford       if (log)
1709b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
171015f2bd95SEwan Crawford       return false;
1711*80af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
171215f2bd95SEwan Crawford       if (log)
1713b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
171415f2bd95SEwan Crawford       return false;
171515f2bd95SEwan Crawford     }
171615f2bd95SEwan Crawford 
171715f2bd95SEwan Crawford     // Perform expression evaluation
1718*80af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
171915f2bd95SEwan Crawford       return false;
172015f2bd95SEwan Crawford   }
172115f2bd95SEwan Crawford 
172215f2bd95SEwan Crawford   // Assign results to allocation members
17238b244e21SEwan Crawford   elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
1724b9c1b51eSKate Stone   elem.type_kind =
1725b9c1b51eSKate Stone       static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
17268b244e21SEwan Crawford   elem.type_vec_size = static_cast<uint32_t>(results[2]);
17278b244e21SEwan Crawford   elem.field_count = static_cast<uint32_t>(results[3]);
172815f2bd95SEwan Crawford 
172915f2bd95SEwan Crawford   if (log)
1730b9c1b51eSKate Stone     log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32
1731b9c1b51eSKate Stone                 ", vector size %" PRIu32 ", field count %" PRIu32,
1732b9c1b51eSKate Stone                 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
1733b9c1b51eSKate Stone                 *elem.type_vec_size.get(), *elem.field_count.get());
17348b244e21SEwan Crawford 
1735b9c1b51eSKate Stone   // If this Element has subelements then JIT rsaElementGetSubElements() for
1736b9c1b51eSKate Stone   // details about its fields
17378b244e21SEwan Crawford   if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
17388b244e21SEwan Crawford     return false;
17398b244e21SEwan Crawford 
17408b244e21SEwan Crawford   return true;
17418b244e21SEwan Crawford }
17428b244e21SEwan Crawford 
1743b9c1b51eSKate Stone // JITs the RS runtime for information about the subelements/fields of a struct
1744*80af0b9eSLuke Drummond // allocation This is necessary for infering the struct type so we can pretty
1745*80af0b9eSLuke Drummond // print the allocation's contents. Returns true on success, false otherwise
1746b9c1b51eSKate Stone bool RenderScriptRuntime::JITSubelements(Element &elem,
1747b9c1b51eSKate Stone                                          const lldb::addr_t context,
1748b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
17498b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
17508b244e21SEwan Crawford 
1751b9c1b51eSKate Stone   if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
17528b244e21SEwan Crawford     if (log)
1753b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
17548b244e21SEwan Crawford     return false;
17558b244e21SEwan Crawford   }
17568b244e21SEwan Crawford 
17578b244e21SEwan Crawford   const short num_exprs = 3;
1758b9c1b51eSKate Stone   assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) &&
1759b9c1b51eSKate Stone          "Invalid number of expressions");
17608b244e21SEwan Crawford 
1761ea0636b5SEwan Crawford   char expr_buffer[jit_max_expr_size];
17628b244e21SEwan Crawford   uint64_t results;
17638b244e21SEwan Crawford 
17648b244e21SEwan Crawford   // Iterate over struct fields.
17658b244e21SEwan Crawford   const uint32_t field_count = *elem.field_count.get();
1766b9c1b51eSKate Stone   for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
17678b244e21SEwan Crawford     Element child;
1768b9c1b51eSKate Stone     for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
1769*80af0b9eSLuke Drummond       const char *fmt_str =
1770b9c1b51eSKate Stone           JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
1771*80af0b9eSLuke Drummond       int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
1772*80af0b9eSLuke Drummond                              field_count, field_count, field_count, context,
1773*80af0b9eSLuke Drummond                              *elem.element_ptr.get(), field_count, field_index);
1774*80af0b9eSLuke Drummond       if (written < 0) {
17758b244e21SEwan Crawford         if (log)
1776b3f7f69dSAidan Dodds           log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
17778b244e21SEwan Crawford         return false;
1778*80af0b9eSLuke Drummond       } else if (written >= jit_max_expr_size) {
17798b244e21SEwan Crawford         if (log)
1780b3f7f69dSAidan Dodds           log->Printf("%s - expression too long.", __FUNCTION__);
17818b244e21SEwan Crawford         return false;
17828b244e21SEwan Crawford       }
17838b244e21SEwan Crawford 
17848b244e21SEwan Crawford       // Perform expression evaluation
17858b244e21SEwan Crawford       if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
17868b244e21SEwan Crawford         return false;
17878b244e21SEwan Crawford 
17888b244e21SEwan Crawford       if (log)
1789b3f7f69dSAidan Dodds         log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
17908b244e21SEwan Crawford 
1791b9c1b51eSKate Stone       switch (expr_index) {
17928b244e21SEwan Crawford       case 0: // Element* of child
17938b244e21SEwan Crawford         child.element_ptr = static_cast<addr_t>(results);
17948b244e21SEwan Crawford         break;
17958b244e21SEwan Crawford       case 1: // Name of child
17968b244e21SEwan Crawford       {
17978b244e21SEwan Crawford         lldb::addr_t address = static_cast<addr_t>(results);
17988b244e21SEwan Crawford         Error err;
17998b244e21SEwan Crawford         std::string name;
18008b244e21SEwan Crawford         GetProcess()->ReadCStringFromMemory(address, name, err);
18018b244e21SEwan Crawford         if (!err.Fail())
18028b244e21SEwan Crawford           child.type_name = ConstString(name);
1803b9c1b51eSKate Stone         else {
18048b244e21SEwan Crawford           if (log)
1805b9c1b51eSKate Stone             log->Printf("%s - warning: Couldn't read field name.",
1806b9c1b51eSKate Stone                         __FUNCTION__);
18078b244e21SEwan Crawford         }
18088b244e21SEwan Crawford         break;
18098b244e21SEwan Crawford       }
18108b244e21SEwan Crawford       case 2: // Array size of child
18118b244e21SEwan Crawford         child.array_size = static_cast<uint32_t>(results);
18128b244e21SEwan Crawford         break;
18138b244e21SEwan Crawford       }
18148b244e21SEwan Crawford     }
18158b244e21SEwan Crawford 
18168b244e21SEwan Crawford     // We need to recursively JIT each Element field of the struct since
18178b244e21SEwan Crawford     // structs can be nested inside structs.
18188b244e21SEwan Crawford     if (!JITElementPacked(child, context, frame_ptr))
18198b244e21SEwan Crawford       return false;
18208b244e21SEwan Crawford     elem.children.push_back(child);
18218b244e21SEwan Crawford   }
18228b244e21SEwan Crawford 
1823b9c1b51eSKate Stone   // Try to infer the name of the struct type so we can pretty print the
1824b9c1b51eSKate Stone   // allocation contents.
18258b244e21SEwan Crawford   FindStructTypeName(elem, frame_ptr);
182615f2bd95SEwan Crawford 
182715f2bd95SEwan Crawford   return true;
182815f2bd95SEwan Crawford }
182915f2bd95SEwan Crawford 
1830a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
1831b9c1b51eSKate Stone // The `elem_size` parameter represents the size of a single element, including
1832*80af0b9eSLuke Drummond // padding. Which is needed as an offset from the last element pointer. Using
1833*80af0b9eSLuke Drummond // this offset minus the starting address we can calculate the size of the
1834*80af0b9eSLuke Drummond // allocation. Returns true on success, false otherwise
1835*80af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
1836b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
1837a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1838a0f08674SEwan Crawford 
1839*80af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
1840*80af0b9eSLuke Drummond       !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
1841a0f08674SEwan Crawford     if (log)
1842b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1843a0f08674SEwan Crawford     return false;
1844a0f08674SEwan Crawford   }
1845a0f08674SEwan Crawford 
1846a0f08674SEwan Crawford   // Find dimensions
1847*80af0b9eSLuke Drummond   uint32_t dim_x = alloc->dimension.get()->dim_1;
1848*80af0b9eSLuke Drummond   uint32_t dim_y = alloc->dimension.get()->dim_2;
1849*80af0b9eSLuke Drummond   uint32_t dim_z = alloc->dimension.get()->dim_3;
1850a0f08674SEwan Crawford 
1851b9c1b51eSKate Stone   // Our plan of jitting the last element address doesn't seem to work for
1852*80af0b9eSLuke Drummond   // struct Allocations` Instead try to infer the size ourselves without any
1853*80af0b9eSLuke Drummond   // inter element padding.
1854*80af0b9eSLuke Drummond   if (alloc->element.children.size() > 0) {
1855b9c1b51eSKate Stone     if (dim_x == 0)
1856b9c1b51eSKate Stone       dim_x = 1;
1857b9c1b51eSKate Stone     if (dim_y == 0)
1858b9c1b51eSKate Stone       dim_y = 1;
1859b9c1b51eSKate Stone     if (dim_z == 0)
1860b9c1b51eSKate Stone       dim_z = 1;
18618b244e21SEwan Crawford 
1862*80af0b9eSLuke Drummond     alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
18638b244e21SEwan Crawford 
18648b244e21SEwan Crawford     if (log)
1865b9c1b51eSKate Stone       log->Printf("%s - inferred size of struct allocation %" PRIu32 ".",
1866*80af0b9eSLuke Drummond                   __FUNCTION__, *alloc->size.get());
18678b244e21SEwan Crawford     return true;
18688b244e21SEwan Crawford   }
18698b244e21SEwan Crawford 
1870*80af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
1871*80af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
18728b244e21SEwan Crawford 
1873a0f08674SEwan Crawford   // Calculate last element
1874a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 0 : dim_x - 1;
1875a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 0 : dim_y - 1;
1876a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 0 : dim_z - 1;
1877a0f08674SEwan Crawford 
1878*80af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1879*80af0b9eSLuke Drummond                          *alloc->address.get(), dim_x, dim_y, dim_z);
1880*80af0b9eSLuke Drummond   if (written < 0) {
1881a0f08674SEwan Crawford     if (log)
1882b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1883a0f08674SEwan Crawford     return false;
1884*80af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
1885a0f08674SEwan Crawford     if (log)
1886b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
1887a0f08674SEwan Crawford     return false;
1888a0f08674SEwan Crawford   }
1889a0f08674SEwan Crawford 
1890a0f08674SEwan Crawford   uint64_t result = 0;
1891*80af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1892a0f08674SEwan Crawford     return false;
1893a0f08674SEwan Crawford 
1894a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1895a0f08674SEwan Crawford   // Find pointer to last element and add on size of an element
1896*80af0b9eSLuke Drummond   alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
1897*80af0b9eSLuke Drummond                 *alloc->element.datum_size.get();
1898a0f08674SEwan Crawford 
1899a0f08674SEwan Crawford   return true;
1900a0f08674SEwan Crawford }
1901a0f08674SEwan Crawford 
1902b9c1b51eSKate Stone // JITs the RS runtime for information about the stride between rows in the
1903*80af0b9eSLuke Drummond // allocation. This is done to detect padding, since allocated memory is 16-byte
1904*80af0b9eSLuke Drummond // aligned.
1905a0f08674SEwan Crawford // Returns true on success, false otherwise
1906*80af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
1907b9c1b51eSKate Stone                                               StackFrame *frame_ptr) {
1908a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1909a0f08674SEwan Crawford 
1910*80af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
1911a0f08674SEwan Crawford     if (log)
1912b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1913a0f08674SEwan Crawford     return false;
1914a0f08674SEwan Crawford   }
1915a0f08674SEwan Crawford 
1916*80af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
1917*80af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
1918a0f08674SEwan Crawford 
1919*80af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1920*80af0b9eSLuke Drummond                          *alloc->address.get(), 0, 1, 0);
1921*80af0b9eSLuke Drummond   if (written < 0) {
1922a0f08674SEwan Crawford     if (log)
1923b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1924a0f08674SEwan Crawford     return false;
1925*80af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
1926a0f08674SEwan Crawford     if (log)
1927b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
1928a0f08674SEwan Crawford     return false;
1929a0f08674SEwan Crawford   }
1930a0f08674SEwan Crawford 
1931a0f08674SEwan Crawford   uint64_t result = 0;
1932*80af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1933a0f08674SEwan Crawford     return false;
1934a0f08674SEwan Crawford 
1935a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1936*80af0b9eSLuke Drummond   alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
1937a0f08674SEwan Crawford 
1938a0f08674SEwan Crawford   return true;
1939a0f08674SEwan Crawford }
1940a0f08674SEwan Crawford 
194115f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
1942*80af0b9eSLuke Drummond bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
1943b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
194415f2bd95SEwan Crawford   // GetOffsetPointer()
1945*80af0b9eSLuke Drummond   if (!JITDataPointer(alloc, frame_ptr))
194615f2bd95SEwan Crawford     return false;
194715f2bd95SEwan Crawford 
194815f2bd95SEwan Crawford   // rsaAllocationGetType()
1949*80af0b9eSLuke Drummond   if (!JITTypePointer(alloc, frame_ptr))
195015f2bd95SEwan Crawford     return false;
195115f2bd95SEwan Crawford 
195215f2bd95SEwan Crawford   // rsaTypeGetNativeData()
1953*80af0b9eSLuke Drummond   if (!JITTypePacked(alloc, frame_ptr))
195415f2bd95SEwan Crawford     return false;
195515f2bd95SEwan Crawford 
195615f2bd95SEwan Crawford   // rsaElementGetNativeData()
1957*80af0b9eSLuke Drummond   if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
195815f2bd95SEwan Crawford     return false;
195915f2bd95SEwan Crawford 
19608b244e21SEwan Crawford   // Sets the datum_size member in Element
1961*80af0b9eSLuke Drummond   SetElementSize(alloc->element);
19628b244e21SEwan Crawford 
196355232f09SEwan Crawford   // Use GetOffsetPointer() to infer size of the allocation
1964*80af0b9eSLuke Drummond   if (!JITAllocationSize(alloc, frame_ptr))
196555232f09SEwan Crawford     return false;
196655232f09SEwan Crawford 
196755232f09SEwan Crawford   return true;
196855232f09SEwan Crawford }
196955232f09SEwan Crawford 
1970b9c1b51eSKate Stone // Function attempts to set the type_name member of the paramaterised Element
1971b9c1b51eSKate Stone // object.
19728b244e21SEwan Crawford // This string should be the name of the struct type the Element represents.
19738b244e21SEwan Crawford // We need this string for pretty printing the Element to users.
1974b9c1b51eSKate Stone void RenderScriptRuntime::FindStructTypeName(Element &elem,
1975b9c1b51eSKate Stone                                              StackFrame *frame_ptr) {
19768b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
19778b244e21SEwan Crawford 
19788b244e21SEwan Crawford   if (!elem.type_name.IsEmpty()) // Name already set
19798b244e21SEwan Crawford     return;
19808b244e21SEwan Crawford   else
1981b9c1b51eSKate Stone     elem.type_name = Element::GetFallbackStructName(); // Default type name if
1982b9c1b51eSKate Stone                                                        // we don't succeed
19838b244e21SEwan Crawford 
19848b244e21SEwan Crawford   // Find all the global variables from the script rs modules
1985*80af0b9eSLuke Drummond   VariableList var_list;
19868b244e21SEwan Crawford   for (auto module_sp : m_rsmodules)
198795eae423SZachary Turner     module_sp->m_module->FindGlobalVariables(
1988*80af0b9eSLuke Drummond         RegularExpression(llvm::StringRef(".")), true, UINT32_MAX, var_list);
19898b244e21SEwan Crawford 
1990b9c1b51eSKate Stone   // Iterate over all the global variables looking for one with a matching type
1991b9c1b51eSKate Stone   // to the Element.
1992b9c1b51eSKate Stone   // We make the assumption a match exists since there needs to be a global
1993*80af0b9eSLuke Drummond   // variable to reflect the struct type back into java host code.
1994*80af0b9eSLuke Drummond   for (uint32_t i = 0; i < var_list.GetSize(); ++i) {
1995*80af0b9eSLuke Drummond     const VariableSP var_sp(var_list.GetVariableAtIndex(i));
19968b244e21SEwan Crawford     if (!var_sp)
19978b244e21SEwan Crawford       continue;
19988b244e21SEwan Crawford 
19998b244e21SEwan Crawford     ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
20008b244e21SEwan Crawford     if (!valobj_sp)
20018b244e21SEwan Crawford       continue;
20028b244e21SEwan Crawford 
20038b244e21SEwan Crawford     // Find the number of variable fields.
2004b9c1b51eSKate Stone     // If it has no fields, or more fields than our Element, then it can't be
2005b9c1b51eSKate Stone     // the struct we're looking for.
2006b9c1b51eSKate Stone     // Don't check for equality since RS can add extra struct members for
2007b9c1b51eSKate Stone     // padding.
20088b244e21SEwan Crawford     size_t num_children = valobj_sp->GetNumChildren();
20098b244e21SEwan Crawford     if (num_children > elem.children.size() || num_children == 0)
20108b244e21SEwan Crawford       continue;
20118b244e21SEwan Crawford 
20128b244e21SEwan Crawford     // Iterate over children looking for members with matching field names.
20138b244e21SEwan Crawford     // If all the field names match, this is likely the struct we want.
2014b9c1b51eSKate Stone     //   TODO: This could be made more robust by also checking children data
2015b9c1b51eSKate Stone     //   sizes, or array size
20168b244e21SEwan Crawford     bool found = true;
2017*80af0b9eSLuke Drummond     for (size_t i = 0; i < num_children; ++i) {
2018*80af0b9eSLuke Drummond       ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
2019*80af0b9eSLuke Drummond       if (!child || (child->GetName() != elem.children[i].type_name)) {
20208b244e21SEwan Crawford         found = false;
20218b244e21SEwan Crawford         break;
20228b244e21SEwan Crawford       }
20238b244e21SEwan Crawford     }
20248b244e21SEwan Crawford 
2025b9c1b51eSKate Stone     // RS can add extra struct members for padding in the format
2026b9c1b51eSKate Stone     // '#rs_padding_[0-9]+'
2027b9c1b51eSKate Stone     if (found && num_children < elem.children.size()) {
2028b3f7f69dSAidan Dodds       const uint32_t size_diff = elem.children.size() - num_children;
20298b244e21SEwan Crawford       if (log)
2030b9c1b51eSKate Stone         log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2031b9c1b51eSKate Stone                     size_diff);
20328b244e21SEwan Crawford 
2033*80af0b9eSLuke Drummond       for (uint32_t i = 0; i < size_diff; ++i) {
2034*80af0b9eSLuke Drummond         const ConstString &name = elem.children[num_children + i].type_name;
20358b244e21SEwan Crawford         if (strcmp(name.AsCString(), "#rs_padding") < 0)
20368b244e21SEwan Crawford           found = false;
20378b244e21SEwan Crawford       }
20388b244e21SEwan Crawford     }
20398b244e21SEwan Crawford 
2040*80af0b9eSLuke Drummond     // We've found a global variable with matching type
2041b9c1b51eSKate Stone     if (found) {
20428b244e21SEwan Crawford       // Dereference since our Element type isn't a pointer.
2043b9c1b51eSKate Stone       if (valobj_sp->IsPointerType()) {
20448b244e21SEwan Crawford         Error err;
20458b244e21SEwan Crawford         ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
20468b244e21SEwan Crawford         if (!err.Fail())
20478b244e21SEwan Crawford           valobj_sp = deref_valobj;
20488b244e21SEwan Crawford       }
20498b244e21SEwan Crawford 
20508b244e21SEwan Crawford       // Save name of variable in Element.
20518b244e21SEwan Crawford       elem.type_name = valobj_sp->GetTypeName();
20528b244e21SEwan Crawford       if (log)
2053b9c1b51eSKate Stone         log->Printf("%s - element name set to %s", __FUNCTION__,
2054b9c1b51eSKate Stone                     elem.type_name.AsCString());
20558b244e21SEwan Crawford 
20568b244e21SEwan Crawford       return;
20578b244e21SEwan Crawford     }
20588b244e21SEwan Crawford   }
20598b244e21SEwan Crawford }
20608b244e21SEwan Crawford 
2061b9c1b51eSKate Stone // Function sets the datum_size member of Element. Representing the size of a
2062b9c1b51eSKate Stone // single instance including padding.
20638b244e21SEwan Crawford // Assumes the relevant allocation information has already been jitted.
2064b9c1b51eSKate Stone void RenderScriptRuntime::SetElementSize(Element &elem) {
20658b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
20668b244e21SEwan Crawford   const Element::DataType type = *elem.type.get();
2067b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2068b9c1b51eSKate Stone          "Invalid allocation type");
206955232f09SEwan Crawford 
2070b3f7f69dSAidan Dodds   const uint32_t vec_size = *elem.type_vec_size.get();
2071b3f7f69dSAidan Dodds   uint32_t data_size = 0;
2072b3f7f69dSAidan Dodds   uint32_t padding = 0;
207355232f09SEwan Crawford 
20748b244e21SEwan Crawford   // Element is of a struct type, calculate size recursively.
2075b9c1b51eSKate Stone   if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2076b9c1b51eSKate Stone     for (Element &child : elem.children) {
20778b244e21SEwan Crawford       SetElementSize(child);
2078b9c1b51eSKate Stone       const uint32_t array_size =
2079b9c1b51eSKate Stone           child.array_size.isValid() ? *child.array_size.get() : 1;
20808b244e21SEwan Crawford       data_size += *child.datum_size.get() * array_size;
20818b244e21SEwan Crawford     }
20828b244e21SEwan Crawford   }
2083b3f7f69dSAidan Dodds   // These have been packed already
2084b3f7f69dSAidan Dodds   else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2085b3f7f69dSAidan Dodds            type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2086b9c1b51eSKate Stone            type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
20872e920715SEwan Crawford     data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2088b9c1b51eSKate Stone   } else if (type < Element::RS_TYPE_ELEMENT) {
2089b9c1b51eSKate Stone     data_size =
2090b9c1b51eSKate Stone         vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
20912e920715SEwan Crawford     if (vec_size == 3)
20922e920715SEwan Crawford       padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2093b9c1b51eSKate Stone   } else
2094b9c1b51eSKate Stone     data_size =
2095b9c1b51eSKate Stone         GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
20968b244e21SEwan Crawford 
20978b244e21SEwan Crawford   elem.padding = padding;
20988b244e21SEwan Crawford   elem.datum_size = data_size + padding;
20998b244e21SEwan Crawford   if (log)
2100b9c1b51eSKate Stone     log->Printf("%s - element size set to %" PRIu32, __FUNCTION__,
2101b9c1b51eSKate Stone                 data_size + padding);
210255232f09SEwan Crawford }
210355232f09SEwan Crawford 
2104b9c1b51eSKate Stone // Given an allocation, this function copies the allocation contents from device
2105b9c1b51eSKate Stone // into a buffer on the heap.
210655232f09SEwan Crawford // Returning a shared pointer to the buffer containing the data.
210755232f09SEwan Crawford std::shared_ptr<uint8_t>
2108*80af0b9eSLuke Drummond RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2109b9c1b51eSKate Stone                                        StackFrame *frame_ptr) {
211055232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
211155232f09SEwan Crawford 
211255232f09SEwan Crawford   // JIT all the allocation details
2113*80af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
211455232f09SEwan Crawford     if (log)
2115b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info",
2116b9c1b51eSKate Stone                   __FUNCTION__);
211755232f09SEwan Crawford 
2118*80af0b9eSLuke Drummond     if (!RefreshAllocation(alloc, frame_ptr)) {
211955232f09SEwan Crawford       if (log)
2120b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
212155232f09SEwan Crawford       return nullptr;
212255232f09SEwan Crawford     }
212355232f09SEwan Crawford   }
212455232f09SEwan Crawford 
2125*80af0b9eSLuke Drummond   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2126*80af0b9eSLuke Drummond          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2127*80af0b9eSLuke Drummond          "Allocation information not available");
212855232f09SEwan Crawford 
212955232f09SEwan Crawford   // Allocate a buffer to copy data into
2130*80af0b9eSLuke Drummond   const uint32_t size = *alloc->size.get();
213155232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2132b9c1b51eSKate Stone   if (!buffer) {
213355232f09SEwan Crawford     if (log)
2134b9c1b51eSKate Stone       log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer",
2135b9c1b51eSKate Stone                   __FUNCTION__, size);
213655232f09SEwan Crawford     return nullptr;
213755232f09SEwan Crawford   }
213855232f09SEwan Crawford 
213955232f09SEwan Crawford   // Read the inferior memory
2140*80af0b9eSLuke Drummond   Error err;
2141*80af0b9eSLuke Drummond   lldb::addr_t data_ptr = *alloc->data_ptr.get();
2142*80af0b9eSLuke Drummond   GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
2143*80af0b9eSLuke Drummond   if (err.Fail()) {
214455232f09SEwan Crawford     if (log)
2145b9c1b51eSKate Stone       log->Printf("%s - '%s' Couldn't read %" PRIu32
2146b9c1b51eSKate Stone                   " bytes of allocation data from 0x%" PRIx64,
2147*80af0b9eSLuke Drummond                   __FUNCTION__, err.AsCString(), size, data_ptr);
214855232f09SEwan Crawford     return nullptr;
214955232f09SEwan Crawford   }
215055232f09SEwan Crawford 
215155232f09SEwan Crawford   return buffer;
215255232f09SEwan Crawford }
215355232f09SEwan Crawford 
215455232f09SEwan Crawford // Function copies data from a binary file into an allocation.
2155b9c1b51eSKate Stone // There is a header at the start of the file, FileHeader, before the data
2156b9c1b51eSKate Stone // content itself.
2157b9c1b51eSKate Stone // Information from this header is used to display warnings to the user about
2158b9c1b51eSKate Stone // incompatibilities
2159b9c1b51eSKate Stone bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
2160*80af0b9eSLuke Drummond                                          const char *path,
2161b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
216255232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
216355232f09SEwan Crawford 
216455232f09SEwan Crawford   // Find allocation with the given id
216555232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
216655232f09SEwan Crawford   if (!alloc)
216755232f09SEwan Crawford     return false;
216855232f09SEwan Crawford 
216955232f09SEwan Crawford   if (log)
2170b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2171b9c1b51eSKate Stone                 *alloc->address.get());
217255232f09SEwan Crawford 
217355232f09SEwan Crawford   // JIT all the allocation details
2174*80af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
217555232f09SEwan Crawford     if (log)
2176b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2177b9c1b51eSKate Stone                   __FUNCTION__);
217855232f09SEwan Crawford 
2179b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
218055232f09SEwan Crawford       if (log)
2181b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
21824cfc9198SSylvestre Ledru       return false;
218355232f09SEwan Crawford     }
218455232f09SEwan Crawford   }
218555232f09SEwan Crawford 
2186b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2187b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2188b9c1b51eSKate Stone          alloc->element.datum_size.isValid() &&
2189b9c1b51eSKate Stone          "Allocation information not available");
219055232f09SEwan Crawford 
219155232f09SEwan Crawford   // Check we can read from file
2192*80af0b9eSLuke Drummond   FileSpec file(path, true);
2193b9c1b51eSKate Stone   if (!file.Exists()) {
2194*80af0b9eSLuke Drummond     strm.Printf("Error: File %s does not exist", path);
219555232f09SEwan Crawford     strm.EOL();
219655232f09SEwan Crawford     return false;
219755232f09SEwan Crawford   }
219855232f09SEwan Crawford 
2199b9c1b51eSKate Stone   if (!file.Readable()) {
2200*80af0b9eSLuke Drummond     strm.Printf("Error: File %s does not have readable permissions", path);
220155232f09SEwan Crawford     strm.EOL();
220255232f09SEwan Crawford     return false;
220355232f09SEwan Crawford   }
220455232f09SEwan Crawford 
220555232f09SEwan Crawford   // Read file into data buffer
220655232f09SEwan Crawford   DataBufferSP data_sp(file.ReadFileContents());
220755232f09SEwan Crawford 
220855232f09SEwan Crawford   // Cast start of buffer to FileHeader and use pointer to read metadata
2209*80af0b9eSLuke Drummond   void *file_buf = data_sp->GetBytes();
2210*80af0b9eSLuke Drummond   if (file_buf == nullptr ||
2211b9c1b51eSKate Stone       data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2212b9c1b51eSKate Stone                                 sizeof(AllocationDetails::ElementHeader))) {
2213*80af0b9eSLuke Drummond     strm.Printf("Error: File %s does not contain enough data for header", path);
221426e52a70SEwan Crawford     strm.EOL();
221526e52a70SEwan Crawford     return false;
221626e52a70SEwan Crawford   }
2217b9c1b51eSKate Stone   const AllocationDetails::FileHeader *file_header =
2218*80af0b9eSLuke Drummond       static_cast<AllocationDetails::FileHeader *>(file_buf);
221955232f09SEwan Crawford 
222026e52a70SEwan Crawford   // Check file starts with ascii characters "RSAD"
2221b9c1b51eSKate Stone   if (memcmp(file_header->ident, "RSAD", 4)) {
2222b9c1b51eSKate Stone     strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2223b9c1b51eSKate Stone                 "dump. Are you sure this is the correct file?");
222426e52a70SEwan Crawford     strm.EOL();
222526e52a70SEwan Crawford     return false;
222626e52a70SEwan Crawford   }
222726e52a70SEwan Crawford 
222826e52a70SEwan Crawford   // Look at the type of the root element in the header
2229*80af0b9eSLuke Drummond   AllocationDetails::ElementHeader root_el_hdr;
2230*80af0b9eSLuke Drummond   memcpy(&root_el_hdr, static_cast<uint8_t *>(file_buf) +
2231b9c1b51eSKate Stone                            sizeof(AllocationDetails::FileHeader),
223226e52a70SEwan Crawford          sizeof(AllocationDetails::ElementHeader));
223355232f09SEwan Crawford 
223455232f09SEwan Crawford   if (log)
2235b9c1b51eSKate Stone     log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32,
2236*80af0b9eSLuke Drummond                 __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
223755232f09SEwan Crawford 
2238b9c1b51eSKate Stone   // Check if the target allocation and file both have the same number of bytes
2239b9c1b51eSKate Stone   // for an Element
2240*80af0b9eSLuke Drummond   if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2241b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2242b9c1b51eSKate Stone                 " bytes, allocation %" PRIu32 " bytes",
2243*80af0b9eSLuke Drummond                 root_el_hdr.element_size, *alloc->element.datum_size.get());
224455232f09SEwan Crawford     strm.EOL();
224555232f09SEwan Crawford   }
224655232f09SEwan Crawford 
224726e52a70SEwan Crawford   // Check if the target allocation and file both have the same type
2248b3f7f69dSAidan Dodds   const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
2249*80af0b9eSLuke Drummond   const uint32_t file_type = root_el_hdr.type;
225026e52a70SEwan Crawford 
2251b9c1b51eSKate Stone   if (file_type > Element::RS_TYPE_FONT) {
225226e52a70SEwan Crawford     strm.Printf("Warning: File has unknown allocation type");
225326e52a70SEwan Crawford     strm.EOL();
2254b9c1b51eSKate Stone   } else if (alloc_type != file_type) {
2255b9c1b51eSKate Stone     // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2256b9c1b51eSKate Stone     // array
2257*80af0b9eSLuke Drummond     uint32_t target_type_name_idx = alloc_type;
2258*80af0b9eSLuke Drummond     uint32_t head_type_name_idx = file_type;
2259b9c1b51eSKate Stone     if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2260b9c1b51eSKate Stone         alloc_type <= Element::RS_TYPE_FONT)
2261*80af0b9eSLuke Drummond       target_type_name_idx = static_cast<Element::DataType>(
2262b9c1b51eSKate Stone           (alloc_type - Element::RS_TYPE_ELEMENT) +
2263b3f7f69dSAidan Dodds           Element::RS_TYPE_MATRIX_2X2 + 1);
22642e920715SEwan Crawford 
2265b9c1b51eSKate Stone     if (file_type >= Element::RS_TYPE_ELEMENT &&
2266b9c1b51eSKate Stone         file_type <= Element::RS_TYPE_FONT)
2267*80af0b9eSLuke Drummond       head_type_name_idx = static_cast<Element::DataType>(
2268b9c1b51eSKate Stone           (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2269b9c1b51eSKate Stone           1);
22702e920715SEwan Crawford 
2271*80af0b9eSLuke Drummond     const char *head_type_name =
2272*80af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
2273*80af0b9eSLuke Drummond     const char *target_type_name =
2274*80af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
227555232f09SEwan Crawford 
2276b9c1b51eSKate Stone     strm.Printf(
2277b9c1b51eSKate Stone         "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
2278*80af0b9eSLuke Drummond         head_type_name, target_type_name);
227955232f09SEwan Crawford     strm.EOL();
228055232f09SEwan Crawford   }
228155232f09SEwan Crawford 
228226e52a70SEwan Crawford   // Advance buffer past header
2283*80af0b9eSLuke Drummond   file_buf = static_cast<uint8_t *>(file_buf) + file_header->hdr_size;
228426e52a70SEwan Crawford 
228555232f09SEwan Crawford   // Calculate size of allocation data in file
2286*80af0b9eSLuke Drummond   size_t size = data_sp->GetByteSize() - file_header->hdr_size;
228755232f09SEwan Crawford 
228855232f09SEwan Crawford   // Check if the target allocation and file both have the same total data size.
2289b3f7f69dSAidan Dodds   const uint32_t alloc_size = *alloc->size.get();
2290*80af0b9eSLuke Drummond   if (alloc_size != size) {
2291b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2292b9c1b51eSKate Stone                 " bytes, allocation 0x%" PRIx32 " bytes",
2293*80af0b9eSLuke Drummond                 (uint64_t)size, alloc_size);
229455232f09SEwan Crawford     strm.EOL();
2295*80af0b9eSLuke Drummond     // Set length to copy to minimum
2296*80af0b9eSLuke Drummond     size = alloc_size < size ? alloc_size : size;
229755232f09SEwan Crawford   }
229855232f09SEwan Crawford 
229955232f09SEwan Crawford   // Copy file data from our buffer into the target allocation.
230055232f09SEwan Crawford   lldb::addr_t alloc_data = *alloc->data_ptr.get();
2301*80af0b9eSLuke Drummond   Error err;
2302*80af0b9eSLuke Drummond   size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
2303*80af0b9eSLuke Drummond   if (!err.Success() || written != size) {
2304*80af0b9eSLuke Drummond     strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
230555232f09SEwan Crawford     strm.EOL();
230655232f09SEwan Crawford     return false;
230755232f09SEwan Crawford   }
230855232f09SEwan Crawford 
2309*80af0b9eSLuke Drummond   strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2310b9c1b51eSKate Stone               alloc->id);
231155232f09SEwan Crawford   strm.EOL();
231255232f09SEwan Crawford 
231355232f09SEwan Crawford   return true;
231455232f09SEwan Crawford }
231555232f09SEwan Crawford 
2316b9c1b51eSKate Stone // Function takes as parameters a byte buffer, which will eventually be written
2317*80af0b9eSLuke Drummond // to file as the element header, an offset into that buffer, and an Element
2318*80af0b9eSLuke Drummond // that will be saved into the buffer at the parametrised offset.
231926e52a70SEwan Crawford // Return value is the new offset after writing the element into the buffer.
2320b9c1b51eSKate Stone // Elements are saved to the file as the ElementHeader struct followed by
2321*80af0b9eSLuke Drummond // offsets to the structs of all the element's children.
2322b9c1b51eSKate Stone size_t RenderScriptRuntime::PopulateElementHeaders(
2323b9c1b51eSKate Stone     const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2324b9c1b51eSKate Stone     const Element &elem) {
2325b9c1b51eSKate Stone   // File struct for an element header with all the relevant details copied from
2326*80af0b9eSLuke Drummond   // elem. We assume members are valid already.
232726e52a70SEwan Crawford   AllocationDetails::ElementHeader elem_header;
232826e52a70SEwan Crawford   elem_header.type = *elem.type.get();
232926e52a70SEwan Crawford   elem_header.kind = *elem.type_kind.get();
233026e52a70SEwan Crawford   elem_header.element_size = *elem.datum_size.get();
233126e52a70SEwan Crawford   elem_header.vector_size = *elem.type_vec_size.get();
2332b9c1b51eSKate Stone   elem_header.array_size =
2333b9c1b51eSKate Stone       elem.array_size.isValid() ? *elem.array_size.get() : 0;
233426e52a70SEwan Crawford   const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
233526e52a70SEwan Crawford 
233626e52a70SEwan Crawford   // Copy struct into buffer and advance offset
2337b9c1b51eSKate Stone   // We assume that header_buffer has been checked for nullptr before this
2338b9c1b51eSKate Stone   // method is called
233926e52a70SEwan Crawford   memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
234026e52a70SEwan Crawford   offset += elem_header_size;
234126e52a70SEwan Crawford 
234226e52a70SEwan Crawford   // Starting offset of child ElementHeader struct
2343b9c1b51eSKate Stone   size_t child_offset =
2344b9c1b51eSKate Stone       offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2345b9c1b51eSKate Stone   for (const RenderScriptRuntime::Element &child : elem.children) {
2346b9c1b51eSKate Stone     // Recursively populate the buffer with the element header structs of
2347*80af0b9eSLuke Drummond     // children. Then save the offsets where they were set after the parent
2348*80af0b9eSLuke Drummond     // element header.
234926e52a70SEwan Crawford     memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
235026e52a70SEwan Crawford     offset += sizeof(uint32_t);
235126e52a70SEwan Crawford 
235226e52a70SEwan Crawford     child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
235326e52a70SEwan Crawford   }
235426e52a70SEwan Crawford 
235526e52a70SEwan Crawford   // Zero indicates no more children
235626e52a70SEwan Crawford   memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
235726e52a70SEwan Crawford 
235826e52a70SEwan Crawford   return child_offset;
235926e52a70SEwan Crawford }
236026e52a70SEwan Crawford 
2361b9c1b51eSKate Stone // Given an Element object this function returns the total size needed in the
2362*80af0b9eSLuke Drummond // file header to store the element's details. Taking into account the size of
2363*80af0b9eSLuke Drummond // the element header struct, plus the offsets to all the element's children.
2364b9c1b51eSKate Stone // Function is recursive so that the size of all ancestors is taken into
2365b9c1b51eSKate Stone // account.
2366b9c1b51eSKate Stone size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
2367*80af0b9eSLuke Drummond   // Offsets to children plus zero terminator
2368*80af0b9eSLuke Drummond   size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
2369*80af0b9eSLuke Drummond   // Size of header struct with type details
2370*80af0b9eSLuke Drummond   size += sizeof(AllocationDetails::ElementHeader);
237126e52a70SEwan Crawford 
237226e52a70SEwan Crawford   // Calculate recursively for all descendants
237326e52a70SEwan Crawford   for (const Element &child : elem.children)
237426e52a70SEwan Crawford     size += CalculateElementHeaderSize(child);
237526e52a70SEwan Crawford 
237626e52a70SEwan Crawford   return size;
237726e52a70SEwan Crawford }
237826e52a70SEwan Crawford 
2379*80af0b9eSLuke Drummond // Function copies allocation contents into a binary file. This file can then be
2380*80af0b9eSLuke Drummond // loaded later into a different allocation. There is a header, FileHeader,
2381*80af0b9eSLuke Drummond // before the allocation data containing meta-data.
2382b9c1b51eSKate Stone bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
2383*80af0b9eSLuke Drummond                                          const char *path,
2384b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
238555232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
238655232f09SEwan Crawford 
238755232f09SEwan Crawford   // Find allocation with the given id
238855232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
238955232f09SEwan Crawford   if (!alloc)
239055232f09SEwan Crawford     return false;
239155232f09SEwan Crawford 
239255232f09SEwan Crawford   if (log)
2393b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2394b9c1b51eSKate Stone                 *alloc->address.get());
239555232f09SEwan Crawford 
239655232f09SEwan Crawford   // JIT all the allocation details
2397*80af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
239855232f09SEwan Crawford     if (log)
2399b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2400b9c1b51eSKate Stone                   __FUNCTION__);
240155232f09SEwan Crawford 
2402b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
240355232f09SEwan Crawford       if (log)
2404b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
24054cfc9198SSylvestre Ledru       return false;
240655232f09SEwan Crawford     }
240755232f09SEwan Crawford   }
240855232f09SEwan Crawford 
2409b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2410b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() &&
2411b9c1b51eSKate Stone          alloc->element.datum_size.get() &&
2412b9c1b51eSKate Stone          alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2413b3f7f69dSAidan Dodds          "Allocation information not available");
241455232f09SEwan Crawford 
241555232f09SEwan Crawford   // Check we can create writable file
2416*80af0b9eSLuke Drummond   FileSpec file_spec(path, true);
2417b9c1b51eSKate Stone   File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate |
2418b9c1b51eSKate Stone                            File::eOpenOptionTruncate);
2419b9c1b51eSKate Stone   if (!file) {
2420*80af0b9eSLuke Drummond     strm.Printf("Error: Failed to open '%s' for writing", path);
242155232f09SEwan Crawford     strm.EOL();
242255232f09SEwan Crawford     return false;
242355232f09SEwan Crawford   }
242455232f09SEwan Crawford 
242555232f09SEwan Crawford   // Read allocation into buffer of heap memory
242655232f09SEwan Crawford   const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2427b9c1b51eSKate Stone   if (!buffer) {
242855232f09SEwan Crawford     strm.Printf("Error: Couldn't read allocation data into buffer");
242955232f09SEwan Crawford     strm.EOL();
243055232f09SEwan Crawford     return false;
243155232f09SEwan Crawford   }
243255232f09SEwan Crawford 
243355232f09SEwan Crawford   // Create the file header
243455232f09SEwan Crawford   AllocationDetails::FileHeader head;
2435b3f7f69dSAidan Dodds   memcpy(head.ident, "RSAD", 4);
24362d62328aSEwan Crawford   head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
24372d62328aSEwan Crawford   head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
24382d62328aSEwan Crawford   head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
243926e52a70SEwan Crawford 
244026e52a70SEwan Crawford   const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2441b9c1b51eSKate Stone   assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2442b9c1b51eSKate Stone              UINT16_MAX &&
2443b9c1b51eSKate Stone          "Element header too large");
2444b9c1b51eSKate Stone   head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2445b9c1b51eSKate Stone                                         element_header_size);
244655232f09SEwan Crawford 
244755232f09SEwan Crawford   // Write the file header
244855232f09SEwan Crawford   size_t num_bytes = sizeof(AllocationDetails::FileHeader);
244926e52a70SEwan Crawford   if (log)
2450b9c1b51eSKate Stone     log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2451b9c1b51eSKate Stone                 (uint64_t)num_bytes);
245226e52a70SEwan Crawford 
245326e52a70SEwan Crawford   Error err = file.Write(&head, num_bytes);
2454b9c1b51eSKate Stone   if (!err.Success()) {
2455*80af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
245626e52a70SEwan Crawford     strm.EOL();
245726e52a70SEwan Crawford     return false;
245826e52a70SEwan Crawford   }
245926e52a70SEwan Crawford 
246026e52a70SEwan Crawford   // Create the headers describing the element type of the allocation.
2461b9c1b51eSKate Stone   std::shared_ptr<uint8_t> element_header_buffer(
2462b9c1b51eSKate Stone       new uint8_t[element_header_size]);
2463b9c1b51eSKate Stone   if (element_header_buffer == nullptr) {
2464b9c1b51eSKate Stone     strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2465b9c1b51eSKate Stone                 " bytes on the heap",
2466b9c1b51eSKate Stone                 (uint64_t)element_header_size);
246726e52a70SEwan Crawford     strm.EOL();
246826e52a70SEwan Crawford     return false;
246926e52a70SEwan Crawford   }
247026e52a70SEwan Crawford 
247126e52a70SEwan Crawford   PopulateElementHeaders(element_header_buffer, 0, alloc->element);
247226e52a70SEwan Crawford 
247326e52a70SEwan Crawford   // Write headers for allocation element type to file
247426e52a70SEwan Crawford   num_bytes = element_header_size;
247526e52a70SEwan Crawford   if (log)
2476b9c1b51eSKate Stone     log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.",
2477b9c1b51eSKate Stone                 __FUNCTION__, (uint64_t)num_bytes);
247826e52a70SEwan Crawford 
247926e52a70SEwan Crawford   err = file.Write(element_header_buffer.get(), num_bytes);
2480b9c1b51eSKate Stone   if (!err.Success()) {
2481*80af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
248255232f09SEwan Crawford     strm.EOL();
248355232f09SEwan Crawford     return false;
248455232f09SEwan Crawford   }
248555232f09SEwan Crawford 
248655232f09SEwan Crawford   // Write allocation data to file
248755232f09SEwan Crawford   num_bytes = static_cast<size_t>(*alloc->size.get());
248855232f09SEwan Crawford   if (log)
2489b9c1b51eSKate Stone     log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2490b9c1b51eSKate Stone                 (uint64_t)num_bytes);
249155232f09SEwan Crawford 
249255232f09SEwan Crawford   err = file.Write(buffer.get(), num_bytes);
2493b9c1b51eSKate Stone   if (!err.Success()) {
2494*80af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
249555232f09SEwan Crawford     strm.EOL();
249655232f09SEwan Crawford     return false;
249755232f09SEwan Crawford   }
249855232f09SEwan Crawford 
2499*80af0b9eSLuke Drummond   strm.Printf("Allocation written to file '%s'", path);
250055232f09SEwan Crawford   strm.EOL();
250115f2bd95SEwan Crawford   return true;
250215f2bd95SEwan Crawford }
250315f2bd95SEwan Crawford 
2504b9c1b51eSKate Stone bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
25054640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
25064640cde1SColin Riley 
2507b9c1b51eSKate Stone   if (module_sp) {
2508b9c1b51eSKate Stone     for (const auto &rs_module : m_rsmodules) {
2509b9c1b51eSKate Stone       if (rs_module->m_module == module_sp) {
25107dc7771cSEwan Crawford         // Check if the user has enabled automatically breaking on
25117dc7771cSEwan Crawford         // all RS kernels.
25127dc7771cSEwan Crawford         if (m_breakAllKernels)
25137dc7771cSEwan Crawford           BreakOnModuleKernels(rs_module);
25147dc7771cSEwan Crawford 
25155ec532a9SColin Riley         return false;
25165ec532a9SColin Riley       }
25177dc7771cSEwan Crawford     }
2518ef20b08fSColin Riley     bool module_loaded = false;
2519b9c1b51eSKate Stone     switch (GetModuleKind(module_sp)) {
2520b9c1b51eSKate Stone     case eModuleKindKernelObj: {
25214640cde1SColin Riley       RSModuleDescriptorSP module_desc;
25224640cde1SColin Riley       module_desc.reset(new RSModuleDescriptor(module_sp));
2523b9c1b51eSKate Stone       if (module_desc->ParseRSInfo()) {
25245ec532a9SColin Riley         m_rsmodules.push_back(module_desc);
2525ef20b08fSColin Riley         module_loaded = true;
25265ec532a9SColin Riley       }
2527b9c1b51eSKate Stone       if (module_loaded) {
25284640cde1SColin Riley         FixupScriptDetails(module_desc);
25294640cde1SColin Riley       }
2530ef20b08fSColin Riley       break;
2531ef20b08fSColin Riley     }
2532b9c1b51eSKate Stone     case eModuleKindDriver: {
2533b9c1b51eSKate Stone       if (!m_libRSDriver) {
25344640cde1SColin Riley         m_libRSDriver = module_sp;
25354640cde1SColin Riley         LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
25364640cde1SColin Riley       }
25374640cde1SColin Riley       break;
25384640cde1SColin Riley     }
2539b9c1b51eSKate Stone     case eModuleKindImpl: {
25404640cde1SColin Riley       m_libRSCpuRef = module_sp;
25414640cde1SColin Riley       break;
25424640cde1SColin Riley     }
2543b9c1b51eSKate Stone     case eModuleKindLibRS: {
2544b9c1b51eSKate Stone       if (!m_libRS) {
25454640cde1SColin Riley         m_libRS = module_sp;
25464640cde1SColin Riley         static ConstString gDbgPresentStr("gDebuggerPresent");
2547b9c1b51eSKate Stone         const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2548b9c1b51eSKate Stone             gDbgPresentStr, eSymbolTypeData);
2549b9c1b51eSKate Stone         if (debug_present) {
2550*80af0b9eSLuke Drummond           Error err;
25514640cde1SColin Riley           uint32_t flag = 0x00000001U;
25524640cde1SColin Riley           Target &target = GetProcess()->GetTarget();
2553358cf1eaSGreg Clayton           addr_t addr = debug_present->GetLoadAddress(&target);
2554*80af0b9eSLuke Drummond           GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
2555*80af0b9eSLuke Drummond           if (err.Success()) {
25564640cde1SColin Riley             if (log)
2557b9c1b51eSKate Stone               log->Printf("%s - debugger present flag set on debugee.",
2558b9c1b51eSKate Stone                           __FUNCTION__);
25594640cde1SColin Riley 
25604640cde1SColin Riley             m_debuggerPresentFlagged = true;
2561b9c1b51eSKate Stone           } else if (log) {
2562b9c1b51eSKate Stone             log->Printf("%s - error writing debugger present flags '%s' ",
2563*80af0b9eSLuke Drummond                         __FUNCTION__, err.AsCString());
25644640cde1SColin Riley           }
2565b9c1b51eSKate Stone         } else if (log) {
2566b9c1b51eSKate Stone           log->Printf(
2567b9c1b51eSKate Stone               "%s - error writing debugger present flags - symbol not found",
2568b9c1b51eSKate Stone               __FUNCTION__);
25694640cde1SColin Riley         }
25704640cde1SColin Riley       }
25714640cde1SColin Riley       break;
25724640cde1SColin Riley     }
2573ef20b08fSColin Riley     default:
2574ef20b08fSColin Riley       break;
2575ef20b08fSColin Riley     }
2576ef20b08fSColin Riley     if (module_loaded)
2577ef20b08fSColin Riley       Update();
2578ef20b08fSColin Riley     return module_loaded;
25795ec532a9SColin Riley   }
25805ec532a9SColin Riley   return false;
25815ec532a9SColin Riley }
25825ec532a9SColin Riley 
2583b9c1b51eSKate Stone void RenderScriptRuntime::Update() {
2584b9c1b51eSKate Stone   if (m_rsmodules.size() > 0) {
2585b9c1b51eSKate Stone     if (!m_initiated) {
2586ef20b08fSColin Riley       Initiate();
2587ef20b08fSColin Riley     }
2588ef20b08fSColin Riley   }
2589ef20b08fSColin Riley }
2590ef20b08fSColin Riley 
25917f193d69SLuke Drummond bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
25927f193d69SLuke Drummond                                           size_t n_lines) {
25937f193d69SLuke Drummond   // Skip the pragma prototype line
25947f193d69SLuke Drummond   ++lines;
25957f193d69SLuke Drummond   for (; n_lines--; ++lines) {
25967f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
25977f193d69SLuke Drummond     m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
25987f193d69SLuke Drummond   }
25997f193d69SLuke Drummond   return true;
26007f193d69SLuke Drummond }
26017f193d69SLuke Drummond 
26027f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
26037f193d69SLuke Drummond                                                 size_t n_lines) {
26047f193d69SLuke Drummond   // The list of reduction kernels in the `.rs.info` symbol is of the form
26057f193d69SLuke Drummond   // "signature - accumulatordatasize - reduction_name - initializer_name -
26067f193d69SLuke Drummond   // accumulator_name - combiner_name -
26077f193d69SLuke Drummond   // outconverter_name - halter_name"
26087f193d69SLuke Drummond   // Where a function is not explicitly named by the user, or is not generated
26097f193d69SLuke Drummond   // by the compiler, it is named "." so the
26107f193d69SLuke Drummond   // dash separated list should always be 8 items long
26117f193d69SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
26127f193d69SLuke Drummond   // Skip the exportReduceCount line
26137f193d69SLuke Drummond   ++lines;
26147f193d69SLuke Drummond   for (; n_lines--; ++lines) {
26157f193d69SLuke Drummond     llvm::SmallVector<llvm::StringRef, 8> spec;
26167f193d69SLuke Drummond     lines->split(spec, " - ");
26177f193d69SLuke Drummond     if (spec.size() != 8) {
26187f193d69SLuke Drummond       if (spec.size() < 8) {
26197f193d69SLuke Drummond         if (log)
26207f193d69SLuke Drummond           log->Error("Error parsing RenderScript reduction spec. wrong number "
26217f193d69SLuke Drummond                      "of fields");
26227f193d69SLuke Drummond         return false;
26237f193d69SLuke Drummond       } else if (log)
26247f193d69SLuke Drummond         log->Warning("Extraneous members in reduction spec: '%s'",
26257f193d69SLuke Drummond                      lines->str().c_str());
26267f193d69SLuke Drummond     }
26277f193d69SLuke Drummond 
26287f193d69SLuke Drummond     const auto sig_s = spec[0];
26297f193d69SLuke Drummond     uint32_t sig;
26307f193d69SLuke Drummond     if (sig_s.getAsInteger(10, sig)) {
26317f193d69SLuke Drummond       if (log)
26327f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid kernel "
26337f193d69SLuke Drummond                    "signature: '%s'",
26347f193d69SLuke Drummond                    sig_s.str().c_str());
26357f193d69SLuke Drummond       return false;
26367f193d69SLuke Drummond     }
26377f193d69SLuke Drummond 
26387f193d69SLuke Drummond     const auto accum_data_size_s = spec[1];
26397f193d69SLuke Drummond     uint32_t accum_data_size;
26407f193d69SLuke Drummond     if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
26417f193d69SLuke Drummond       if (log)
26427f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid "
26437f193d69SLuke Drummond                    "accumulator data size %s",
26447f193d69SLuke Drummond                    accum_data_size_s.str().c_str());
26457f193d69SLuke Drummond       return false;
26467f193d69SLuke Drummond     }
26477f193d69SLuke Drummond 
26487f193d69SLuke Drummond     if (log)
26497f193d69SLuke Drummond       log->Printf("Found RenderScript reduction '%s'", spec[2].str().c_str());
26507f193d69SLuke Drummond 
26517f193d69SLuke Drummond     m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
26527f193d69SLuke Drummond                                                  spec[2], spec[3], spec[4],
26537f193d69SLuke Drummond                                                  spec[5], spec[6], spec[7]));
26547f193d69SLuke Drummond   }
26557f193d69SLuke Drummond   return true;
26567f193d69SLuke Drummond }
26577f193d69SLuke Drummond 
26587f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
26597f193d69SLuke Drummond                                                  size_t n_lines) {
26607f193d69SLuke Drummond   // Skip the exportForeachCount line
26617f193d69SLuke Drummond   ++lines;
26627f193d69SLuke Drummond   for (; n_lines--; ++lines) {
26637f193d69SLuke Drummond     uint32_t slot;
26647f193d69SLuke Drummond     // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
26657f193d69SLuke Drummond     // pair per line
26667f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
26677f193d69SLuke Drummond     if (kv_pair.first.getAsInteger(10, slot))
26687f193d69SLuke Drummond       return false;
26697f193d69SLuke Drummond     m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
26707f193d69SLuke Drummond   }
26717f193d69SLuke Drummond   return true;
26727f193d69SLuke Drummond }
26737f193d69SLuke Drummond 
26747f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
26757f193d69SLuke Drummond                                              size_t n_lines) {
26767f193d69SLuke Drummond   // Skip the ExportVarCount line
26777f193d69SLuke Drummond   ++lines;
26787f193d69SLuke Drummond   for (; n_lines--; ++lines)
26797f193d69SLuke Drummond     m_globals.push_back(RSGlobalDescriptor(this, *lines));
26807f193d69SLuke Drummond   return true;
26817f193d69SLuke Drummond }
26825ec532a9SColin Riley 
2683b9c1b51eSKate Stone // The .rs.info symbol in renderscript modules contains a string which needs to
2684b9c1b51eSKate Stone // be parsed.
26855ec532a9SColin Riley // The string is basic and is parsed on a line by line basis.
2686b9c1b51eSKate Stone bool RSModuleDescriptor::ParseRSInfo() {
2687b0be30f7SAidan Dodds   assert(m_module);
26887f193d69SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2689b9c1b51eSKate Stone   const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
2690b9c1b51eSKate Stone       ConstString(".rs.info"), eSymbolTypeData);
2691b0be30f7SAidan Dodds   if (!info_sym)
2692b0be30f7SAidan Dodds     return false;
2693b0be30f7SAidan Dodds 
2694358cf1eaSGreg Clayton   const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
2695b0be30f7SAidan Dodds   if (addr == LLDB_INVALID_ADDRESS)
2696b0be30f7SAidan Dodds     return false;
2697b0be30f7SAidan Dodds 
26985ec532a9SColin Riley   const addr_t size = info_sym->GetByteSize();
26995ec532a9SColin Riley   const FileSpec fs = m_module->GetFileSpec();
27005ec532a9SColin Riley 
2701b0be30f7SAidan Dodds   const DataBufferSP buffer = fs.ReadFileContents(addr, size);
27025ec532a9SColin Riley   if (!buffer)
27035ec532a9SColin Riley     return false;
27045ec532a9SColin Riley 
2705b0be30f7SAidan Dodds   // split rs.info. contents into lines
27067f193d69SLuke Drummond   llvm::SmallVector<llvm::StringRef, 128> info_lines;
27075ec532a9SColin Riley   {
27087f193d69SLuke Drummond     const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
27097f193d69SLuke Drummond     raw_rs_info.split(info_lines, '\n');
27107f193d69SLuke Drummond     if (log)
27117f193d69SLuke Drummond       log->Printf("'.rs.info symbol for '%s':\n%s",
27127f193d69SLuke Drummond                   m_module->GetFileSpec().GetCString(),
27137f193d69SLuke Drummond                   raw_rs_info.str().c_str());
2714b0be30f7SAidan Dodds   }
2715b0be30f7SAidan Dodds 
27167f193d69SLuke Drummond   enum {
27177f193d69SLuke Drummond     eExportVar,
27187f193d69SLuke Drummond     eExportForEach,
27197f193d69SLuke Drummond     eExportReduce,
27207f193d69SLuke Drummond     ePragma,
27217f193d69SLuke Drummond     eBuildChecksum,
27227f193d69SLuke Drummond     eObjectSlot
27237f193d69SLuke Drummond   };
27247f193d69SLuke Drummond 
27257f193d69SLuke Drummond   static const llvm::StringMap<int> rs_info_handlers{
27267f193d69SLuke Drummond       {// The number of visible global variables in the script
27277f193d69SLuke Drummond        {"exportVarCount", eExportVar},
27287f193d69SLuke Drummond        // The number of RenderScrip `forEach` kernels __attribute__((kernel))
27297f193d69SLuke Drummond        {"exportForEachCount", eExportForEach},
27307f193d69SLuke Drummond        // The number of generalreductions: This marked in the script by `#pragma
27317f193d69SLuke Drummond        // reduce()`
27327f193d69SLuke Drummond        {"exportReduceCount", eExportReduce},
27337f193d69SLuke Drummond        // Total count of all RenderScript specific `#pragmas` used in the script
27347f193d69SLuke Drummond        {"pragmaCount", ePragma},
27357f193d69SLuke Drummond        {"objectSlotCount", eObjectSlot}}};
2736b0be30f7SAidan Dodds 
2737b0be30f7SAidan Dodds   // parse all text lines of .rs.info
2738b9c1b51eSKate Stone   for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
27397f193d69SLuke Drummond     const auto kv_pair = line->split(": ");
27407f193d69SLuke Drummond     const auto key = kv_pair.first;
27417f193d69SLuke Drummond     const auto val = kv_pair.second.trim();
27425ec532a9SColin Riley 
27437f193d69SLuke Drummond     const auto handler = rs_info_handlers.find(key);
27447f193d69SLuke Drummond     if (handler == rs_info_handlers.end())
27457f193d69SLuke Drummond       continue;
27467f193d69SLuke Drummond     // getAsInteger returns `true` on an error condition - we're only interested
27477f193d69SLuke Drummond     // in
27487f193d69SLuke Drummond     // numeric fields at the moment
27497f193d69SLuke Drummond     uint64_t n_lines;
27507f193d69SLuke Drummond     if (val.getAsInteger(10, n_lines)) {
27517f193d69SLuke Drummond       if (log)
27527f193d69SLuke Drummond         log->Debug("Failed to parse non-numeric '.rs.info' section %s",
27537f193d69SLuke Drummond                    line->str().c_str());
27547f193d69SLuke Drummond       continue;
27557f193d69SLuke Drummond     }
27567f193d69SLuke Drummond     if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
27577f193d69SLuke Drummond       return false;
27587f193d69SLuke Drummond 
27597f193d69SLuke Drummond     bool success = false;
27607f193d69SLuke Drummond     switch (handler->getValue()) {
27617f193d69SLuke Drummond     case eExportVar:
27627f193d69SLuke Drummond       success = ParseExportVarCount(line, n_lines);
27637f193d69SLuke Drummond       break;
27647f193d69SLuke Drummond     case eExportForEach:
27657f193d69SLuke Drummond       success = ParseExportForeachCount(line, n_lines);
27667f193d69SLuke Drummond       break;
27677f193d69SLuke Drummond     case eExportReduce:
27687f193d69SLuke Drummond       success = ParseExportReduceCount(line, n_lines);
27697f193d69SLuke Drummond       break;
27707f193d69SLuke Drummond     case ePragma:
27717f193d69SLuke Drummond       success = ParsePragmaCount(line, n_lines);
27727f193d69SLuke Drummond       break;
27737f193d69SLuke Drummond     default: {
27747f193d69SLuke Drummond       if (log)
27757f193d69SLuke Drummond         log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__,
27767f193d69SLuke Drummond                     line->str().c_str());
27777f193d69SLuke Drummond       continue;
27787f193d69SLuke Drummond     }
27797f193d69SLuke Drummond     }
27807f193d69SLuke Drummond     if (!success)
27817f193d69SLuke Drummond       return false;
27827f193d69SLuke Drummond     line += n_lines;
27837f193d69SLuke Drummond   }
27847f193d69SLuke Drummond   return info_lines.size() > 0;
27855ec532a9SColin Riley }
27865ec532a9SColin Riley 
2787b9c1b51eSKate Stone void RenderScriptRuntime::Status(Stream &strm) const {
2788b9c1b51eSKate Stone   if (m_libRS) {
27894640cde1SColin Riley     strm.Printf("Runtime Library discovered.");
27904640cde1SColin Riley     strm.EOL();
27914640cde1SColin Riley   }
2792b9c1b51eSKate Stone   if (m_libRSDriver) {
27934640cde1SColin Riley     strm.Printf("Runtime Driver discovered.");
27944640cde1SColin Riley     strm.EOL();
27954640cde1SColin Riley   }
2796b9c1b51eSKate Stone   if (m_libRSCpuRef) {
27974640cde1SColin Riley     strm.Printf("CPU Reference Implementation discovered.");
27984640cde1SColin Riley     strm.EOL();
27994640cde1SColin Riley   }
28004640cde1SColin Riley 
2801b9c1b51eSKate Stone   if (m_runtimeHooks.size()) {
28024640cde1SColin Riley     strm.Printf("Runtime functions hooked:");
28034640cde1SColin Riley     strm.EOL();
2804b9c1b51eSKate Stone     for (auto b : m_runtimeHooks) {
28054640cde1SColin Riley       strm.Indent(b.second->defn->name);
28064640cde1SColin Riley       strm.EOL();
28074640cde1SColin Riley     }
2808b9c1b51eSKate Stone   } else {
28094640cde1SColin Riley     strm.Printf("Runtime is not hooked.");
28104640cde1SColin Riley     strm.EOL();
28114640cde1SColin Riley   }
28124640cde1SColin Riley }
28134640cde1SColin Riley 
2814b9c1b51eSKate Stone void RenderScriptRuntime::DumpContexts(Stream &strm) const {
28154640cde1SColin Riley   strm.Printf("Inferred RenderScript Contexts:");
28164640cde1SColin Riley   strm.EOL();
28174640cde1SColin Riley   strm.IndentMore();
28184640cde1SColin Riley 
28194640cde1SColin Riley   std::map<addr_t, uint64_t> contextReferences;
28204640cde1SColin Riley 
282178f339d1SEwan Crawford   // Iterate over all of the currently discovered scripts.
2822b9c1b51eSKate Stone   // Note: We cant push or pop from m_scripts inside this loop or it may
2823b9c1b51eSKate Stone   // invalidate script.
2824b9c1b51eSKate Stone   for (const auto &script : m_scripts) {
282578f339d1SEwan Crawford     if (!script->context.isValid())
282678f339d1SEwan Crawford       continue;
282778f339d1SEwan Crawford     lldb::addr_t context = *script->context;
282878f339d1SEwan Crawford 
2829b9c1b51eSKate Stone     if (contextReferences.find(context) != contextReferences.end()) {
283078f339d1SEwan Crawford       contextReferences[context]++;
2831b9c1b51eSKate Stone     } else {
283278f339d1SEwan Crawford       contextReferences[context] = 1;
28334640cde1SColin Riley     }
28344640cde1SColin Riley   }
28354640cde1SColin Riley 
2836b9c1b51eSKate Stone   for (const auto &cRef : contextReferences) {
2837b9c1b51eSKate Stone     strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
2838b9c1b51eSKate Stone                 cRef.first, cRef.second);
28394640cde1SColin Riley     strm.EOL();
28404640cde1SColin Riley   }
28414640cde1SColin Riley   strm.IndentLess();
28424640cde1SColin Riley }
28434640cde1SColin Riley 
2844b9c1b51eSKate Stone void RenderScriptRuntime::DumpKernels(Stream &strm) const {
28454640cde1SColin Riley   strm.Printf("RenderScript Kernels:");
28464640cde1SColin Riley   strm.EOL();
28474640cde1SColin Riley   strm.IndentMore();
2848b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
28494640cde1SColin Riley     strm.Printf("Resource '%s':", module->m_resname.c_str());
28504640cde1SColin Riley     strm.EOL();
2851b9c1b51eSKate Stone     for (const auto &kernel : module->m_kernels) {
28524640cde1SColin Riley       strm.Indent(kernel.m_name.AsCString());
28534640cde1SColin Riley       strm.EOL();
28544640cde1SColin Riley     }
28554640cde1SColin Riley   }
28564640cde1SColin Riley   strm.IndentLess();
28574640cde1SColin Riley }
28584640cde1SColin Riley 
2859a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails *
2860b9c1b51eSKate Stone RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
2861a0f08674SEwan Crawford   AllocationDetails *alloc = nullptr;
2862a0f08674SEwan Crawford 
2863a0f08674SEwan Crawford   // See if we can find allocation using id as an index;
2864b9c1b51eSKate Stone   if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
2865b9c1b51eSKate Stone       m_allocations[alloc_id - 1]->id == alloc_id) {
2866a0f08674SEwan Crawford     alloc = m_allocations[alloc_id - 1].get();
2867a0f08674SEwan Crawford     return alloc;
2868a0f08674SEwan Crawford   }
2869a0f08674SEwan Crawford 
2870a0f08674SEwan Crawford   // Fallback to searching
2871b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
2872b9c1b51eSKate Stone     if (a->id == alloc_id) {
2873a0f08674SEwan Crawford       alloc = a.get();
2874a0f08674SEwan Crawford       break;
2875a0f08674SEwan Crawford     }
2876a0f08674SEwan Crawford   }
2877a0f08674SEwan Crawford 
2878b9c1b51eSKate Stone   if (alloc == nullptr) {
2879b9c1b51eSKate Stone     strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
2880b9c1b51eSKate Stone                 alloc_id);
2881a0f08674SEwan Crawford     strm.EOL();
2882a0f08674SEwan Crawford   }
2883a0f08674SEwan Crawford 
2884a0f08674SEwan Crawford   return alloc;
2885a0f08674SEwan Crawford }
2886a0f08674SEwan Crawford 
2887b9c1b51eSKate Stone // Prints the contents of an allocation to the output stream, which may be a
2888b9c1b51eSKate Stone // file
2889b9c1b51eSKate Stone bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
2890b9c1b51eSKate Stone                                          const uint32_t id) {
2891a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2892a0f08674SEwan Crawford 
2893a0f08674SEwan Crawford   // Check we can find the desired allocation
2894a0f08674SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, id);
2895a0f08674SEwan Crawford   if (!alloc)
2896a0f08674SEwan Crawford     return false; // FindAllocByID() will print error message for us here
2897a0f08674SEwan Crawford 
2898a0f08674SEwan Crawford   if (log)
2899b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2900b9c1b51eSKate Stone                 *alloc->address.get());
2901a0f08674SEwan Crawford 
2902a0f08674SEwan Crawford   // Check we have information about the allocation, if not calculate it
2903*80af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
2904a0f08674SEwan Crawford     if (log)
2905b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2906b9c1b51eSKate Stone                   __FUNCTION__);
2907a0f08674SEwan Crawford 
2908a0f08674SEwan Crawford     // JIT all the allocation information
2909b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
2910a0f08674SEwan Crawford       strm.Printf("Error: Couldn't JIT allocation details");
2911a0f08674SEwan Crawford       strm.EOL();
2912a0f08674SEwan Crawford       return false;
2913a0f08674SEwan Crawford     }
2914a0f08674SEwan Crawford   }
2915a0f08674SEwan Crawford 
2916a0f08674SEwan Crawford   // Establish format and size of each data element
2917b3f7f69dSAidan Dodds   const uint32_t vec_size = *alloc->element.type_vec_size.get();
29188b244e21SEwan Crawford   const Element::DataType type = *alloc->element.type.get();
2919a0f08674SEwan Crawford 
2920b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2921b9c1b51eSKate Stone          "Invalid allocation type");
2922a0f08674SEwan Crawford 
29232e920715SEwan Crawford   lldb::Format format;
29242e920715SEwan Crawford   if (type >= Element::RS_TYPE_ELEMENT)
29252e920715SEwan Crawford     format = eFormatHex;
29262e920715SEwan Crawford   else
2927b9c1b51eSKate Stone     format = vec_size == 1
2928b9c1b51eSKate Stone                  ? static_cast<lldb::Format>(
2929b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatSingle])
2930b9c1b51eSKate Stone                  : static_cast<lldb::Format>(
2931b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatVector]);
2932a0f08674SEwan Crawford 
2933b3f7f69dSAidan Dodds   const uint32_t data_size = *alloc->element.datum_size.get();
2934a0f08674SEwan Crawford 
2935a0f08674SEwan Crawford   if (log)
2936b9c1b51eSKate Stone     log->Printf("%s - element size %" PRIu32 " bytes, including padding",
2937b9c1b51eSKate Stone                 __FUNCTION__, data_size);
2938a0f08674SEwan Crawford 
293955232f09SEwan Crawford   // Allocate a buffer to copy data into
294055232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2941b9c1b51eSKate Stone   if (!buffer) {
29422e920715SEwan Crawford     strm.Printf("Error: Couldn't read allocation data");
294355232f09SEwan Crawford     strm.EOL();
294455232f09SEwan Crawford     return false;
294555232f09SEwan Crawford   }
294655232f09SEwan Crawford 
2947a0f08674SEwan Crawford   // Calculate stride between rows as there may be padding at end of rows since
2948a0f08674SEwan Crawford   // allocated memory is 16-byte aligned
2949b9c1b51eSKate Stone   if (!alloc->stride.isValid()) {
2950a0f08674SEwan Crawford     if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
2951a0f08674SEwan Crawford       alloc->stride = 0;
2952b9c1b51eSKate Stone     else if (!JITAllocationStride(alloc, frame_ptr)) {
2953a0f08674SEwan Crawford       strm.Printf("Error: Couldn't calculate allocation row stride");
2954a0f08674SEwan Crawford       strm.EOL();
2955a0f08674SEwan Crawford       return false;
2956a0f08674SEwan Crawford     }
2957a0f08674SEwan Crawford   }
2958b3f7f69dSAidan Dodds   const uint32_t stride = *alloc->stride.get();
2959b3f7f69dSAidan Dodds   const uint32_t size = *alloc->size.get(); // Size of whole allocation
2960b9c1b51eSKate Stone   const uint32_t padding =
2961b9c1b51eSKate Stone       alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
2962a0f08674SEwan Crawford   if (log)
2963b9c1b51eSKate Stone     log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32
2964b9c1b51eSKate Stone                 " bytes, padding %" PRIu32,
2965b3f7f69dSAidan Dodds                 __FUNCTION__, stride, size, padding);
2966a0f08674SEwan Crawford 
2967a0f08674SEwan Crawford   // Find dimensions used to index loops, so need to be non-zero
2968b3f7f69dSAidan Dodds   uint32_t dim_x = alloc->dimension.get()->dim_1;
2969a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 1 : dim_x;
2970a0f08674SEwan Crawford 
2971b3f7f69dSAidan Dodds   uint32_t dim_y = alloc->dimension.get()->dim_2;
2972a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 1 : dim_y;
2973a0f08674SEwan Crawford 
2974b3f7f69dSAidan Dodds   uint32_t dim_z = alloc->dimension.get()->dim_3;
2975a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 1 : dim_z;
2976a0f08674SEwan Crawford 
297755232f09SEwan Crawford   // Use data extractor to format output
2978*80af0b9eSLuke Drummond   const uint32_t target_ptr_size =
2979b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
2980b9c1b51eSKate Stone   DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
2981*80af0b9eSLuke Drummond                            target_ptr_size);
298255232f09SEwan Crawford 
2983b3f7f69dSAidan Dodds   uint32_t offset = 0;   // Offset in buffer to next element to be printed
2984b3f7f69dSAidan Dodds   uint32_t prev_row = 0; // Offset to the start of the previous row
2985a0f08674SEwan Crawford 
2986a0f08674SEwan Crawford   // Iterate over allocation dimensions, printing results to user
2987a0f08674SEwan Crawford   strm.Printf("Data (X, Y, Z):");
2988b9c1b51eSKate Stone   for (uint32_t z = 0; z < dim_z; ++z) {
2989b9c1b51eSKate Stone     for (uint32_t y = 0; y < dim_y; ++y) {
2990a0f08674SEwan Crawford       // Use stride to index start of next row.
2991a0f08674SEwan Crawford       if (!(y == 0 && z == 0))
2992a0f08674SEwan Crawford         offset = prev_row + stride;
2993a0f08674SEwan Crawford       prev_row = offset;
2994a0f08674SEwan Crawford 
2995a0f08674SEwan Crawford       // Print each element in the row individually
2996b9c1b51eSKate Stone       for (uint32_t x = 0; x < dim_x; ++x) {
2997b3f7f69dSAidan Dodds         strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
2998b9c1b51eSKate Stone         if ((type == Element::RS_TYPE_NONE) &&
2999b9c1b51eSKate Stone             (alloc->element.children.size() > 0) &&
3000b9c1b51eSKate Stone             (alloc->element.type_name != Element::GetFallbackStructName())) {
30018b244e21SEwan Crawford           // Here we are dumping an Element of struct type.
3002b9c1b51eSKate Stone           // This is done using expression evaluation with the name of the
3003b9c1b51eSKate Stone           // struct type and pointer to element.
3004b9c1b51eSKate Stone           // Don't print the name of the resulting expression, since this will
3005b9c1b51eSKate Stone           // be '$[0-9]+'
30068b244e21SEwan Crawford           DumpValueObjectOptions expr_options;
30078b244e21SEwan Crawford           expr_options.SetHideName(true);
30088b244e21SEwan Crawford 
30098b244e21SEwan Crawford           // Setup expression as derefrencing a pointer cast to element address.
3010ea0636b5SEwan Crawford           char expr_char_buffer[jit_max_expr_size];
3011*80af0b9eSLuke Drummond           int written =
3012b9c1b51eSKate Stone               snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3013b9c1b51eSKate Stone                        alloc->element.type_name.AsCString(),
3014b9c1b51eSKate Stone                        *alloc->data_ptr.get() + offset);
30158b244e21SEwan Crawford 
3016*80af0b9eSLuke Drummond           if (written < 0 || written >= jit_max_expr_size) {
30178b244e21SEwan Crawford             if (log)
3018b3f7f69dSAidan Dodds               log->Printf("%s - error in snprintf().", __FUNCTION__);
30198b244e21SEwan Crawford             continue;
30208b244e21SEwan Crawford           }
30218b244e21SEwan Crawford 
30228b244e21SEwan Crawford           // Evaluate expression
30238b244e21SEwan Crawford           ValueObjectSP expr_result;
3024b9c1b51eSKate Stone           GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3025b9c1b51eSKate Stone                                                        frame_ptr, expr_result);
30268b244e21SEwan Crawford 
30278b244e21SEwan Crawford           // Print the results to our stream.
30288b244e21SEwan Crawford           expr_result->Dump(strm, expr_options);
3029b9c1b51eSKate Stone         } else {
3030b9c1b51eSKate Stone           alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1,
3031b9c1b51eSKate Stone                           LLDB_INVALID_ADDRESS, 0, 0);
30328b244e21SEwan Crawford         }
30338b244e21SEwan Crawford         offset += data_size;
3034a0f08674SEwan Crawford       }
3035a0f08674SEwan Crawford     }
3036a0f08674SEwan Crawford   }
3037a0f08674SEwan Crawford   strm.EOL();
3038a0f08674SEwan Crawford 
3039a0f08674SEwan Crawford   return true;
3040a0f08674SEwan Crawford }
3041a0f08674SEwan Crawford 
3042b9c1b51eSKate Stone // Function recalculates all our cached information about allocations by jitting
3043*80af0b9eSLuke Drummond // the RS runtime regarding each allocation we know about. Returns true if all
3044*80af0b9eSLuke Drummond // allocations could be recomputed, false otherwise.
3045b9c1b51eSKate Stone bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3046b9c1b51eSKate Stone                                                   StackFrame *frame_ptr) {
30470d2bfcfbSEwan Crawford   bool success = true;
3048b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
30490d2bfcfbSEwan Crawford     // JIT current allocation information
3050b9c1b51eSKate Stone     if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3051b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3052b9c1b51eSKate Stone                   "\n",
3053b9c1b51eSKate Stone                   alloc->id);
30540d2bfcfbSEwan Crawford       success = false;
30550d2bfcfbSEwan Crawford     }
30560d2bfcfbSEwan Crawford   }
30570d2bfcfbSEwan Crawford 
30580d2bfcfbSEwan Crawford   if (success)
30590d2bfcfbSEwan Crawford     strm.Printf("All allocations successfully recomputed");
30600d2bfcfbSEwan Crawford   strm.EOL();
30610d2bfcfbSEwan Crawford 
30620d2bfcfbSEwan Crawford   return success;
30630d2bfcfbSEwan Crawford }
30640d2bfcfbSEwan Crawford 
3065*80af0b9eSLuke Drummond // Prints information regarding currently loaded allocations. These details are
3066*80af0b9eSLuke Drummond // gathered by jitting the runtime, which has as latency. Index parameter
3067*80af0b9eSLuke Drummond // specifies a single allocation ID to print, or a zero value to print them all
3068b9c1b51eSKate Stone void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3069b9c1b51eSKate Stone                                           const uint32_t index) {
307015f2bd95SEwan Crawford   strm.Printf("RenderScript Allocations:");
307115f2bd95SEwan Crawford   strm.EOL();
307215f2bd95SEwan Crawford   strm.IndentMore();
307315f2bd95SEwan Crawford 
3074b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
3075b649b005SEwan Crawford     // index will only be zero if we want to print all allocations
3076b649b005SEwan Crawford     if (index != 0 && index != alloc->id)
3077b649b005SEwan Crawford       continue;
307815f2bd95SEwan Crawford 
307915f2bd95SEwan Crawford     // JIT current allocation information
3080*80af0b9eSLuke Drummond     if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3081b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3082b9c1b51eSKate Stone                   alloc->id);
3083b3f7f69dSAidan Dodds       strm.EOL();
308415f2bd95SEwan Crawford       continue;
308515f2bd95SEwan Crawford     }
308615f2bd95SEwan Crawford 
3087b3f7f69dSAidan Dodds     strm.Printf("%" PRIu32 ":", alloc->id);
3088b3f7f69dSAidan Dodds     strm.EOL();
308915f2bd95SEwan Crawford     strm.IndentMore();
309015f2bd95SEwan Crawford 
309115f2bd95SEwan Crawford     strm.Indent("Context: ");
309215f2bd95SEwan Crawford     if (!alloc->context.isValid())
309315f2bd95SEwan Crawford       strm.Printf("unknown\n");
309415f2bd95SEwan Crawford     else
309515f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
309615f2bd95SEwan Crawford 
309715f2bd95SEwan Crawford     strm.Indent("Address: ");
309815f2bd95SEwan Crawford     if (!alloc->address.isValid())
309915f2bd95SEwan Crawford       strm.Printf("unknown\n");
310015f2bd95SEwan Crawford     else
310115f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
310215f2bd95SEwan Crawford 
310315f2bd95SEwan Crawford     strm.Indent("Data pointer: ");
310415f2bd95SEwan Crawford     if (!alloc->data_ptr.isValid())
310515f2bd95SEwan Crawford       strm.Printf("unknown\n");
310615f2bd95SEwan Crawford     else
310715f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
310815f2bd95SEwan Crawford 
310915f2bd95SEwan Crawford     strm.Indent("Dimensions: ");
311015f2bd95SEwan Crawford     if (!alloc->dimension.isValid())
311115f2bd95SEwan Crawford       strm.Printf("unknown\n");
311215f2bd95SEwan Crawford     else
3113b3f7f69dSAidan Dodds       strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3114b9c1b51eSKate Stone                   alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3115b9c1b51eSKate Stone                   alloc->dimension.get()->dim_3);
311615f2bd95SEwan Crawford 
311715f2bd95SEwan Crawford     strm.Indent("Data Type: ");
3118b9c1b51eSKate Stone     if (!alloc->element.type.isValid() ||
3119b9c1b51eSKate Stone         !alloc->element.type_vec_size.isValid())
312015f2bd95SEwan Crawford       strm.Printf("unknown\n");
3121b9c1b51eSKate Stone     else {
31228b244e21SEwan Crawford       const int vector_size = *alloc->element.type_vec_size.get();
31232e920715SEwan Crawford       Element::DataType type = *alloc->element.type.get();
312415f2bd95SEwan Crawford 
31258b244e21SEwan Crawford       if (!alloc->element.type_name.IsEmpty())
31268b244e21SEwan Crawford         strm.Printf("%s\n", alloc->element.type_name.AsCString());
3127b9c1b51eSKate Stone       else {
3128b9c1b51eSKate Stone         // Enum value isn't monotonous, so doesn't always index
3129b9c1b51eSKate Stone         // RsDataTypeToString array
31302e920715SEwan Crawford         if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3131b9c1b51eSKate Stone           type =
3132b9c1b51eSKate Stone               static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3133b3f7f69dSAidan Dodds                                              Element::RS_TYPE_MATRIX_2X2 + 1);
31342e920715SEwan Crawford 
3135b3f7f69dSAidan Dodds         if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3136b3f7f69dSAidan Dodds                      sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3137b3f7f69dSAidan Dodds             vector_size > 4 || vector_size < 1)
313815f2bd95SEwan Crawford           strm.Printf("invalid type\n");
313915f2bd95SEwan Crawford         else
3140b9c1b51eSKate Stone           strm.Printf(
3141b9c1b51eSKate Stone               "%s\n",
3142b9c1b51eSKate Stone               AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3143b3f7f69dSAidan Dodds                                                    [vector_size - 1]);
314415f2bd95SEwan Crawford       }
31452e920715SEwan Crawford     }
314615f2bd95SEwan Crawford 
314715f2bd95SEwan Crawford     strm.Indent("Data Kind: ");
31488b244e21SEwan Crawford     if (!alloc->element.type_kind.isValid())
314915f2bd95SEwan Crawford       strm.Printf("unknown\n");
3150b9c1b51eSKate Stone     else {
31518b244e21SEwan Crawford       const Element::DataKind kind = *alloc->element.type_kind.get();
31528b244e21SEwan Crawford       if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
315315f2bd95SEwan Crawford         strm.Printf("invalid kind\n");
315415f2bd95SEwan Crawford       else
3155b9c1b51eSKate Stone         strm.Printf(
3156b9c1b51eSKate Stone             "%s\n",
3157b9c1b51eSKate Stone             AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
315815f2bd95SEwan Crawford     }
315915f2bd95SEwan Crawford 
316015f2bd95SEwan Crawford     strm.EOL();
316115f2bd95SEwan Crawford     strm.IndentLess();
316215f2bd95SEwan Crawford   }
316315f2bd95SEwan Crawford   strm.IndentLess();
316415f2bd95SEwan Crawford }
316515f2bd95SEwan Crawford 
31667dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
3167b9c1b51eSKate Stone void RenderScriptRuntime::BreakOnModuleKernels(
3168b9c1b51eSKate Stone     const RSModuleDescriptorSP rsmodule_sp) {
3169b9c1b51eSKate Stone   for (const auto &kernel : rsmodule_sp->m_kernels) {
31707dc7771cSEwan Crawford     // Don't set breakpoint on 'root' kernel
31717dc7771cSEwan Crawford     if (strcmp(kernel.m_name.AsCString(), "root") == 0)
31727dc7771cSEwan Crawford       continue;
31737dc7771cSEwan Crawford 
31747dc7771cSEwan Crawford     CreateKernelBreakpoint(kernel.m_name);
31757dc7771cSEwan Crawford   }
31767dc7771cSEwan Crawford }
31777dc7771cSEwan Crawford 
3178*80af0b9eSLuke Drummond // Method is internally called by the 'kernel breakpoint all' command to enable
3179*80af0b9eSLuke Drummond // or disable breaking on all kernels. When do_break is true we want to enable
3180*80af0b9eSLuke Drummond // this functionality. When do_break is false we want to disable it.
3181b9c1b51eSKate Stone void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3182b9c1b51eSKate Stone   Log *log(
3183b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
31847dc7771cSEwan Crawford 
31857dc7771cSEwan Crawford   InitSearchFilter(target);
31867dc7771cSEwan Crawford 
31877dc7771cSEwan Crawford   // Set breakpoints on all the kernels
3188b9c1b51eSKate Stone   if (do_break && !m_breakAllKernels) {
31897dc7771cSEwan Crawford     m_breakAllKernels = true;
31907dc7771cSEwan Crawford 
31917dc7771cSEwan Crawford     for (const auto &module : m_rsmodules)
31927dc7771cSEwan Crawford       BreakOnModuleKernels(module);
31937dc7771cSEwan Crawford 
31947dc7771cSEwan Crawford     if (log)
3195b9c1b51eSKate Stone       log->Printf("%s(True) - breakpoints set on all currently loaded kernels.",
3196b9c1b51eSKate Stone                   __FUNCTION__);
3197b9c1b51eSKate Stone   } else if (!do_break &&
3198b9c1b51eSKate Stone              m_breakAllKernels) // Breakpoints won't be set on any new kernels.
31997dc7771cSEwan Crawford   {
32007dc7771cSEwan Crawford     m_breakAllKernels = false;
32017dc7771cSEwan Crawford 
32027dc7771cSEwan Crawford     if (log)
3203b9c1b51eSKate Stone       log->Printf("%s(False) - breakpoints no longer automatically set.",
3204b9c1b51eSKate Stone                   __FUNCTION__);
32057dc7771cSEwan Crawford   }
32067dc7771cSEwan Crawford }
32077dc7771cSEwan Crawford 
32087dc7771cSEwan Crawford // Given the name of a kernel this function creates a breakpoint using our
32097dc7771cSEwan Crawford // own breakpoint resolver, and returns the Breakpoint shared pointer.
32107dc7771cSEwan Crawford BreakpointSP
3211b9c1b51eSKate Stone RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) {
3212b9c1b51eSKate Stone   Log *log(
3213b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
32147dc7771cSEwan Crawford 
3215b9c1b51eSKate Stone   if (!m_filtersp) {
32167dc7771cSEwan Crawford     if (log)
3217b3f7f69dSAidan Dodds       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
32187dc7771cSEwan Crawford     return nullptr;
32197dc7771cSEwan Crawford   }
32207dc7771cSEwan Crawford 
32217dc7771cSEwan Crawford   BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3222b9c1b51eSKate Stone   BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
3223b9c1b51eSKate Stone       m_filtersp, resolver_sp, false, false, false);
32247dc7771cSEwan Crawford 
3225b9c1b51eSKate Stone   // Give RS breakpoints a specific name, so the user can manipulate them as a
3226b9c1b51eSKate Stone   // group.
322754782db7SEwan Crawford   Error err;
322854782db7SEwan Crawford   if (!bp->AddName("RenderScriptKernel", err) && log)
3229b9c1b51eSKate Stone     log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3230b9c1b51eSKate Stone                 err.AsCString());
323154782db7SEwan Crawford 
32327dc7771cSEwan Crawford   return bp;
32337dc7771cSEwan Crawford }
32347dc7771cSEwan Crawford 
3235b9c1b51eSKate Stone // Given an expression for a variable this function tries to calculate the
3236*80af0b9eSLuke Drummond // variable's value. If this is possible it returns true and sets the uint64_t
3237*80af0b9eSLuke Drummond // parameter to the variables unsigned value. Otherwise function returns false.
3238b9c1b51eSKate Stone bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3239b9c1b51eSKate Stone                                                 const char *var_name,
3240b9c1b51eSKate Stone                                                 uint64_t &val) {
3241018f5a7eSEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3242*80af0b9eSLuke Drummond   Error err;
3243018f5a7eSEwan Crawford   VariableSP var_sp;
3244018f5a7eSEwan Crawford 
3245018f5a7eSEwan Crawford   // Find variable in stack frame
3246b3f7f69dSAidan Dodds   ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3247b3f7f69dSAidan Dodds       var_name, eNoDynamicValues,
3248b9c1b51eSKate Stone       StackFrame::eExpressionPathOptionCheckPtrVsMember |
3249b9c1b51eSKate Stone           StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3250*80af0b9eSLuke Drummond       var_sp, err));
3251*80af0b9eSLuke Drummond   if (!err.Success()) {
3252018f5a7eSEwan Crawford     if (log)
3253b9c1b51eSKate Stone       log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__,
3254b9c1b51eSKate Stone                   var_name);
3255018f5a7eSEwan Crawford     return false;
3256018f5a7eSEwan Crawford   }
3257018f5a7eSEwan Crawford 
3258b3f7f69dSAidan Dodds   // Find the uint32_t value for the variable
3259018f5a7eSEwan Crawford   bool success = false;
3260018f5a7eSEwan Crawford   val = value_sp->GetValueAsUnsigned(0, &success);
3261b9c1b51eSKate Stone   if (!success) {
3262018f5a7eSEwan Crawford     if (log)
3263b9c1b51eSKate Stone       log->Printf("%s - error, couldn't parse '%s' as an uint32_t.",
3264b9c1b51eSKate Stone                   __FUNCTION__, var_name);
3265018f5a7eSEwan Crawford     return false;
3266018f5a7eSEwan Crawford   }
3267018f5a7eSEwan Crawford 
3268018f5a7eSEwan Crawford   return true;
3269018f5a7eSEwan Crawford }
3270018f5a7eSEwan Crawford 
3271b9c1b51eSKate Stone // Function attempts to find the current coordinate of a kernel invocation by
3272*80af0b9eSLuke Drummond // investigating the values of frame variables in the .expand function. These
3273*80af0b9eSLuke Drummond // coordinates are returned via the coord array reference parameter. Returns
3274*80af0b9eSLuke Drummond // true if the coordinates could be found, and false otherwise.
3275b9c1b51eSKate Stone bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3276b9c1b51eSKate Stone                                               Thread *thread_ptr) {
327700f56eebSLuke Drummond   static const char *const x_expr = "rsIndex";
327800f56eebSLuke Drummond   static const char *const y_expr = "p->current.y";
327900f56eebSLuke Drummond   static const char *const z_expr = "p->current.z";
32801e05c3bcSGreg Clayton 
32814f8817c2SEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
32824f8817c2SEwan Crawford 
3283b9c1b51eSKate Stone   if (!thread_ptr) {
32844f8817c2SEwan Crawford     if (log)
32854f8817c2SEwan Crawford       log->Printf("%s - Error, No thread pointer", __FUNCTION__);
32864f8817c2SEwan Crawford 
32874f8817c2SEwan Crawford     return false;
32884f8817c2SEwan Crawford   }
32894f8817c2SEwan Crawford 
3290b9c1b51eSKate Stone   // Walk the call stack looking for a function whose name has the suffix
3291*80af0b9eSLuke Drummond   // '.expand' and contains the variables we're looking for.
3292b9c1b51eSKate Stone   for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
32934f8817c2SEwan Crawford     if (!thread_ptr->SetSelectedFrameByIndex(i))
32944f8817c2SEwan Crawford       continue;
32954f8817c2SEwan Crawford 
32964f8817c2SEwan Crawford     StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
32974f8817c2SEwan Crawford     if (!frame_sp)
32984f8817c2SEwan Crawford       continue;
32994f8817c2SEwan Crawford 
33004f8817c2SEwan Crawford     // Find the function name
33014f8817c2SEwan Crawford     const SymbolContext sym_ctx = frame_sp->GetSymbolContext(false);
330200f56eebSLuke Drummond     const ConstString func_name = sym_ctx.GetFunctionName();
330300f56eebSLuke Drummond     if (!func_name)
33044f8817c2SEwan Crawford       continue;
33054f8817c2SEwan Crawford 
33064f8817c2SEwan Crawford     if (log)
3307b9c1b51eSKate Stone       log->Printf("%s - Inspecting function '%s'", __FUNCTION__,
330800f56eebSLuke Drummond                   func_name.GetCString());
33094f8817c2SEwan Crawford 
33104f8817c2SEwan Crawford     // Check if function name has .expand suffix
331100f56eebSLuke Drummond     if (!func_name.GetStringRef().endswith(".expand"))
33124f8817c2SEwan Crawford       continue;
33134f8817c2SEwan Crawford 
33144f8817c2SEwan Crawford     if (log)
3315b9c1b51eSKate Stone       log->Printf("%s - Found .expand function '%s'", __FUNCTION__,
331600f56eebSLuke Drummond                   func_name.GetCString());
33174f8817c2SEwan Crawford 
3318b9c1b51eSKate Stone     // Get values for variables in .expand frame that tell us the current kernel
3319b9c1b51eSKate Stone     // invocation
332000f56eebSLuke Drummond     uint64_t x, y, z;
332100f56eebSLuke Drummond     bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
332200f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
332300f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, z_expr, z);
33244f8817c2SEwan Crawford 
332500f56eebSLuke Drummond     if (found) {
332600f56eebSLuke Drummond       // The RenderScript runtime uses uint32_t for these vars. If they're not
332700f56eebSLuke Drummond       // within bounds, our frame parsing is garbage
332800f56eebSLuke Drummond       assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
332900f56eebSLuke Drummond       coord.x = (uint32_t)x;
333000f56eebSLuke Drummond       coord.y = (uint32_t)y;
333100f56eebSLuke Drummond       coord.z = (uint32_t)z;
33324f8817c2SEwan Crawford       return true;
33334f8817c2SEwan Crawford     }
333400f56eebSLuke Drummond   }
33354f8817c2SEwan Crawford   return false;
33364f8817c2SEwan Crawford }
33374f8817c2SEwan Crawford 
3338b9c1b51eSKate Stone // Callback when a kernel breakpoint hits and we're looking for a specific
3339*80af0b9eSLuke Drummond // coordinate. Baton parameter contains a pointer to the target coordinate we
3340*80af0b9eSLuke Drummond // want to break on.
3341b9c1b51eSKate Stone // Function then checks the .expand frame for the current coordinate and breaks
3342b9c1b51eSKate Stone // to user if it matches.
3343018f5a7eSEwan Crawford // Parameter 'break_id' is the id of the Breakpoint which made the callback.
3344018f5a7eSEwan Crawford // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
3345018f5a7eSEwan Crawford // a single logical breakpoint can have multiple addresses.
3346b9c1b51eSKate Stone bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3347b9c1b51eSKate Stone                                               StoppointCallbackContext *ctx,
3348b9c1b51eSKate Stone                                               user_id_t break_id,
3349b9c1b51eSKate Stone                                               user_id_t break_loc_id) {
3350b9c1b51eSKate Stone   Log *log(
3351b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3352018f5a7eSEwan Crawford 
3353b9c1b51eSKate Stone   assert(baton &&
3354b9c1b51eSKate Stone          "Error: null baton in conditional kernel breakpoint callback");
3355018f5a7eSEwan Crawford 
3356018f5a7eSEwan Crawford   // Coordinate we want to stop on
335700f56eebSLuke Drummond   RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3358018f5a7eSEwan Crawford 
3359018f5a7eSEwan Crawford   if (log)
336000f56eebSLuke Drummond     log->Printf("%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__, break_id,
336100f56eebSLuke Drummond                 target_coord.x, target_coord.y, target_coord.z);
3362018f5a7eSEwan Crawford 
33634f8817c2SEwan Crawford   // Select current thread
3364018f5a7eSEwan Crawford   ExecutionContext context(ctx->exe_ctx_ref);
33654f8817c2SEwan Crawford   Thread *thread_ptr = context.GetThreadPtr();
33664f8817c2SEwan Crawford   assert(thread_ptr && "Null thread pointer");
33674f8817c2SEwan Crawford 
33684f8817c2SEwan Crawford   // Find current kernel invocation from .expand frame variables
336900f56eebSLuke Drummond   RSCoordinate current_coord{};
3370b9c1b51eSKate Stone   if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3371018f5a7eSEwan Crawford     if (log)
3372b9c1b51eSKate Stone       log->Printf("%s - Error, couldn't select .expand stack frame",
3373b9c1b51eSKate Stone                   __FUNCTION__);
3374018f5a7eSEwan Crawford     return false;
3375018f5a7eSEwan Crawford   }
3376018f5a7eSEwan Crawford 
3377018f5a7eSEwan Crawford   if (log)
337800f56eebSLuke Drummond     log->Printf("%s - " FMT_COORD, __FUNCTION__, current_coord.x,
337900f56eebSLuke Drummond                 current_coord.y, current_coord.z);
3380018f5a7eSEwan Crawford 
3381b9c1b51eSKate Stone   // Check if the current kernel invocation coordinate matches our target
3382b9c1b51eSKate Stone   // coordinate
338300f56eebSLuke Drummond   if (target_coord == current_coord) {
3384018f5a7eSEwan Crawford     if (log)
338500f56eebSLuke Drummond       log->Printf("%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
338600f56eebSLuke Drummond                   current_coord.y, current_coord.z);
3387018f5a7eSEwan Crawford 
3388b9c1b51eSKate Stone     BreakpointSP breakpoint_sp =
3389b9c1b51eSKate Stone         context.GetTargetPtr()->GetBreakpointByID(break_id);
3390b9c1b51eSKate Stone     assert(breakpoint_sp != nullptr &&
3391b9c1b51eSKate Stone            "Error: Couldn't find breakpoint matching break id for callback");
3392b9c1b51eSKate Stone     breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3393b9c1b51eSKate Stone                                       // should only be hit once.
3394018f5a7eSEwan Crawford     return true;
3395018f5a7eSEwan Crawford   }
3396018f5a7eSEwan Crawford 
3397018f5a7eSEwan Crawford   // No match on coordinate
3398018f5a7eSEwan Crawford   return false;
3399018f5a7eSEwan Crawford }
3400018f5a7eSEwan Crawford 
340100f56eebSLuke Drummond void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
340200f56eebSLuke Drummond                                          const RSCoordinate &coord) {
340300f56eebSLuke Drummond   messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
340400f56eebSLuke Drummond                   coord.x, coord.y, coord.z);
340500f56eebSLuke Drummond   messages.EOL();
340600f56eebSLuke Drummond 
340700f56eebSLuke Drummond   // Allocate memory for the baton, and copy over coordinate
340800f56eebSLuke Drummond   RSCoordinate *baton = new RSCoordinate(coord);
340900f56eebSLuke Drummond 
341000f56eebSLuke Drummond   // Create a callback that will be invoked every time the breakpoint is hit.
341100f56eebSLuke Drummond   // The baton object passed to the handler is the target coordinate we want to
341200f56eebSLuke Drummond   // break on.
341300f56eebSLuke Drummond   bp->SetCallback(KernelBreakpointHit, baton, true);
341400f56eebSLuke Drummond 
341500f56eebSLuke Drummond   // Store a shared pointer to the baton, so the memory will eventually be
341600f56eebSLuke Drummond   // cleaned up after destruction
341700f56eebSLuke Drummond   m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
341800f56eebSLuke Drummond }
341900f56eebSLuke Drummond 
3420b9c1b51eSKate Stone // Tries to set a breakpoint on the start of a kernel, resolved using the kernel
3421*80af0b9eSLuke Drummond // name. Argument 'coords', represents a three dimensional coordinate which can
3422*80af0b9eSLuke Drummond // be
3423*80af0b9eSLuke Drummond // used to specify a single kernel instance to break on. If this is set then we
3424*80af0b9eSLuke Drummond // add a callback
3425b9c1b51eSKate Stone // to the breakpoint.
342600f56eebSLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
342700f56eebSLuke Drummond                                                   Stream &messages,
342800f56eebSLuke Drummond                                                   const char *name,
342900f56eebSLuke Drummond                                                   const RSCoordinate *coord) {
343000f56eebSLuke Drummond   if (!name)
343100f56eebSLuke Drummond     return false;
34324640cde1SColin Riley 
34337dc7771cSEwan Crawford   InitSearchFilter(target);
343498156583SEwan Crawford 
34354640cde1SColin Riley   ConstString kernel_name(name);
34367dc7771cSEwan Crawford   BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
343700f56eebSLuke Drummond   if (!bp)
343800f56eebSLuke Drummond     return false;
3439018f5a7eSEwan Crawford 
3440018f5a7eSEwan Crawford   // We have a conditional breakpoint on a specific coordinate
344100f56eebSLuke Drummond   if (coord)
344200f56eebSLuke Drummond     SetConditional(bp, messages, *coord);
3443018f5a7eSEwan Crawford 
344400f56eebSLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3445018f5a7eSEwan Crawford 
344600f56eebSLuke Drummond   return true;
34474640cde1SColin Riley }
34484640cde1SColin Riley 
3449b9c1b51eSKate Stone void RenderScriptRuntime::DumpModules(Stream &strm) const {
34505ec532a9SColin Riley   strm.Printf("RenderScript Modules:");
34515ec532a9SColin Riley   strm.EOL();
34525ec532a9SColin Riley   strm.IndentMore();
3453b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
34544640cde1SColin Riley     module->Dump(strm);
34555ec532a9SColin Riley   }
34565ec532a9SColin Riley   strm.IndentLess();
34575ec532a9SColin Riley }
34585ec532a9SColin Riley 
345978f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails *
3460b9c1b51eSKate Stone RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3461b9c1b51eSKate Stone   for (const auto &s : m_scripts) {
346278f339d1SEwan Crawford     if (s->script.isValid())
346378f339d1SEwan Crawford       if (*s->script == address)
346478f339d1SEwan Crawford         return s.get();
346578f339d1SEwan Crawford   }
3466b9c1b51eSKate Stone   if (create) {
346778f339d1SEwan Crawford     std::unique_ptr<ScriptDetails> s(new ScriptDetails);
346878f339d1SEwan Crawford     s->script = address;
346978f339d1SEwan Crawford     m_scripts.push_back(std::move(s));
3470d10ca9deSEwan Crawford     return m_scripts.back().get();
347178f339d1SEwan Crawford   }
347278f339d1SEwan Crawford   return nullptr;
347378f339d1SEwan Crawford }
347478f339d1SEwan Crawford 
347578f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails *
3476b9c1b51eSKate Stone RenderScriptRuntime::LookUpAllocation(addr_t address) {
3477b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
347878f339d1SEwan Crawford     if (a->address.isValid())
347978f339d1SEwan Crawford       if (*a->address == address)
348078f339d1SEwan Crawford         return a.get();
348178f339d1SEwan Crawford   }
34825d057637SLuke Drummond   return nullptr;
34835d057637SLuke Drummond }
34845d057637SLuke Drummond 
34855d057637SLuke Drummond RenderScriptRuntime::AllocationDetails *
3486b9c1b51eSKate Stone RenderScriptRuntime::CreateAllocation(addr_t address) {
34875d057637SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
34885d057637SLuke Drummond 
34895d057637SLuke Drummond   // Remove any previous allocation which contains the same address
34905d057637SLuke Drummond   auto it = m_allocations.begin();
3491b9c1b51eSKate Stone   while (it != m_allocations.end()) {
3492b9c1b51eSKate Stone     if (*((*it)->address) == address) {
34935d057637SLuke Drummond       if (log)
3494b9c1b51eSKate Stone         log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64,
3495b9c1b51eSKate Stone                     __FUNCTION__, (*it)->id, address);
34965d057637SLuke Drummond 
34975d057637SLuke Drummond       it = m_allocations.erase(it);
3498b9c1b51eSKate Stone     } else {
34995d057637SLuke Drummond       it++;
35005d057637SLuke Drummond     }
35015d057637SLuke Drummond   }
35025d057637SLuke Drummond 
350378f339d1SEwan Crawford   std::unique_ptr<AllocationDetails> a(new AllocationDetails);
350478f339d1SEwan Crawford   a->address = address;
350578f339d1SEwan Crawford   m_allocations.push_back(std::move(a));
3506d10ca9deSEwan Crawford   return m_allocations.back().get();
350778f339d1SEwan Crawford }
350878f339d1SEwan Crawford 
3509b9c1b51eSKate Stone void RSModuleDescriptor::Dump(Stream &strm) const {
35107f193d69SLuke Drummond   int indent = strm.GetIndentLevel();
35117f193d69SLuke Drummond 
35125ec532a9SColin Riley   strm.Indent();
35135ec532a9SColin Riley   m_module->GetFileSpec().Dump(&strm);
35147f193d69SLuke Drummond   strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
35157f193d69SLuke Drummond                                              : "Debug info does not exist.");
35165ec532a9SColin Riley   strm.EOL();
35175ec532a9SColin Riley   strm.IndentMore();
35187f193d69SLuke Drummond 
35195ec532a9SColin Riley   strm.Indent();
3520189598edSColin Riley   strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
35215ec532a9SColin Riley   strm.EOL();
35225ec532a9SColin Riley   strm.IndentMore();
3523b9c1b51eSKate Stone   for (const auto &global : m_globals) {
35245ec532a9SColin Riley     global.Dump(strm);
35255ec532a9SColin Riley   }
35265ec532a9SColin Riley   strm.IndentLess();
35277f193d69SLuke Drummond 
35285ec532a9SColin Riley   strm.Indent();
3529189598edSColin Riley   strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
35305ec532a9SColin Riley   strm.EOL();
35315ec532a9SColin Riley   strm.IndentMore();
3532b9c1b51eSKate Stone   for (const auto &kernel : m_kernels) {
35335ec532a9SColin Riley     kernel.Dump(strm);
35345ec532a9SColin Riley   }
35357f193d69SLuke Drummond   strm.IndentLess();
35367f193d69SLuke Drummond 
35377f193d69SLuke Drummond   strm.Indent();
35384640cde1SColin Riley   strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
35394640cde1SColin Riley   strm.EOL();
35404640cde1SColin Riley   strm.IndentMore();
3541b9c1b51eSKate Stone   for (const auto &key_val : m_pragmas) {
35427f193d69SLuke Drummond     strm.Indent();
35434640cde1SColin Riley     strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
35444640cde1SColin Riley     strm.EOL();
35454640cde1SColin Riley   }
35467f193d69SLuke Drummond   strm.IndentLess();
35477f193d69SLuke Drummond 
35487f193d69SLuke Drummond   strm.Indent();
35497f193d69SLuke Drummond   strm.Printf("Reductions: %" PRIu64,
35507f193d69SLuke Drummond               static_cast<uint64_t>(m_reductions.size()));
35517f193d69SLuke Drummond   strm.EOL();
35527f193d69SLuke Drummond   strm.IndentMore();
35537f193d69SLuke Drummond   for (const auto &reduction : m_reductions) {
35547f193d69SLuke Drummond     reduction.Dump(strm);
35557f193d69SLuke Drummond   }
35567f193d69SLuke Drummond 
35577f193d69SLuke Drummond   strm.SetIndentLevel(indent);
35585ec532a9SColin Riley }
35595ec532a9SColin Riley 
3560b9c1b51eSKate Stone void RSGlobalDescriptor::Dump(Stream &strm) const {
35615ec532a9SColin Riley   strm.Indent(m_name.AsCString());
35624640cde1SColin Riley   VariableList var_list;
35634640cde1SColin Riley   m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
3564b9c1b51eSKate Stone   if (var_list.GetSize() == 1) {
35654640cde1SColin Riley     auto var = var_list.GetVariableAtIndex(0);
35664640cde1SColin Riley     auto type = var->GetType();
3567b9c1b51eSKate Stone     if (type) {
35684640cde1SColin Riley       strm.Printf(" - ");
35694640cde1SColin Riley       type->DumpTypeName(&strm);
3570b9c1b51eSKate Stone     } else {
35714640cde1SColin Riley       strm.Printf(" - Unknown Type");
35724640cde1SColin Riley     }
3573b9c1b51eSKate Stone   } else {
35744640cde1SColin Riley     strm.Printf(" - variable identified, but not found in binary");
3575b9c1b51eSKate Stone     const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
3576b9c1b51eSKate Stone         m_name, eSymbolTypeData);
3577b9c1b51eSKate Stone     if (s) {
35784640cde1SColin Riley       strm.Printf(" (symbol exists) ");
35794640cde1SColin Riley     }
35804640cde1SColin Riley   }
35814640cde1SColin Riley 
35825ec532a9SColin Riley   strm.EOL();
35835ec532a9SColin Riley }
35845ec532a9SColin Riley 
3585b9c1b51eSKate Stone void RSKernelDescriptor::Dump(Stream &strm) const {
35865ec532a9SColin Riley   strm.Indent(m_name.AsCString());
35875ec532a9SColin Riley   strm.EOL();
35885ec532a9SColin Riley }
35895ec532a9SColin Riley 
35907f193d69SLuke Drummond void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
35917f193d69SLuke Drummond   stream.Indent(m_reduce_name.AsCString());
35927f193d69SLuke Drummond   stream.IndentMore();
35937f193d69SLuke Drummond   stream.EOL();
35947f193d69SLuke Drummond   stream.Indent();
35957f193d69SLuke Drummond   stream.Printf("accumulator: %s", m_accum_name.AsCString());
35967f193d69SLuke Drummond   stream.EOL();
35977f193d69SLuke Drummond   stream.Indent();
35987f193d69SLuke Drummond   stream.Printf("initializer: %s", m_init_name.AsCString());
35997f193d69SLuke Drummond   stream.EOL();
36007f193d69SLuke Drummond   stream.Indent();
36017f193d69SLuke Drummond   stream.Printf("combiner: %s", m_comb_name.AsCString());
36027f193d69SLuke Drummond   stream.EOL();
36037f193d69SLuke Drummond   stream.Indent();
36047f193d69SLuke Drummond   stream.Printf("outconverter: %s", m_outc_name.AsCString());
36057f193d69SLuke Drummond   stream.EOL();
36067f193d69SLuke Drummond   // XXX This is currently unspecified by RenderScript, and unused
36077f193d69SLuke Drummond   // stream.Indent();
36087f193d69SLuke Drummond   // stream.Printf("halter: '%s'", m_init_name.AsCString());
36097f193d69SLuke Drummond   // stream.EOL();
36107f193d69SLuke Drummond   stream.IndentLess();
36117f193d69SLuke Drummond }
36127f193d69SLuke Drummond 
3613b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
36145ec532a9SColin Riley public:
36155ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
3616b9c1b51eSKate Stone       : CommandObjectParsed(
3617b9c1b51eSKate Stone             interpreter, "renderscript module dump",
3618b9c1b51eSKate Stone             "Dumps renderscript specific information for all modules.",
3619b9c1b51eSKate Stone             "renderscript module dump",
3620b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
36215ec532a9SColin Riley 
3622222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
36235ec532a9SColin Riley 
3624b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
36255ec532a9SColin Riley     RenderScriptRuntime *runtime =
3626b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
3627b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
36285ec532a9SColin Riley     runtime->DumpModules(result.GetOutputStream());
36295ec532a9SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
36305ec532a9SColin Riley     return true;
36315ec532a9SColin Riley   }
36325ec532a9SColin Riley };
36335ec532a9SColin Riley 
3634b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
36355ec532a9SColin Riley public:
36365ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
3637b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript module",
3638b9c1b51eSKate Stone                                "Commands that deal with RenderScript modules.",
3639b9c1b51eSKate Stone                                nullptr) {
3640b9c1b51eSKate Stone     LoadSubCommand(
3641b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
3642b9c1b51eSKate Stone                     interpreter)));
36435ec532a9SColin Riley   }
36445ec532a9SColin Riley 
3645222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModule() override = default;
36465ec532a9SColin Riley };
36475ec532a9SColin Riley 
3648b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
36494640cde1SColin Riley public:
36504640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
3651b9c1b51eSKate Stone       : CommandObjectParsed(
3652b9c1b51eSKate Stone             interpreter, "renderscript kernel list",
3653b3f7f69dSAidan Dodds             "Lists renderscript kernel names and associated script resources.",
3654b9c1b51eSKate Stone             "renderscript kernel list",
3655b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
36564640cde1SColin Riley 
3657222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelList() override = default;
36584640cde1SColin Riley 
3659b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
36604640cde1SColin Riley     RenderScriptRuntime *runtime =
3661b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
3662b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
36634640cde1SColin Riley     runtime->DumpKernels(result.GetOutputStream());
36644640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
36654640cde1SColin Riley     return true;
36664640cde1SColin Riley   }
36674640cde1SColin Riley };
36684640cde1SColin Riley 
36691f0f5b5bSZachary Turner static OptionDefinition g_renderscript_kernel_bp_set_options[] = {
36701f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
36711f0f5b5bSZachary Turner      nullptr, nullptr, 0, eArgTypeValue,
36721f0f5b5bSZachary Turner      "Set a breakpoint on a single invocation of the kernel with specified "
36731f0f5b5bSZachary Turner      "coordinate.\n"
36741f0f5b5bSZachary Turner      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
36751f0f5b5bSZachary Turner      "integers representing kernel dimensions. "
36761f0f5b5bSZachary Turner      "Any unset dimensions will be defaulted to zero."}};
36771f0f5b5bSZachary Turner 
3678b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointSet
3679b9c1b51eSKate Stone     : public CommandObjectParsed {
36804640cde1SColin Riley public:
3681b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointSet(
3682b9c1b51eSKate Stone       CommandInterpreter &interpreter)
3683b9c1b51eSKate Stone       : CommandObjectParsed(
3684b9c1b51eSKate Stone             interpreter, "renderscript kernel breakpoint set",
3685b3f7f69dSAidan Dodds             "Sets a breakpoint on a renderscript kernel.",
3686b3f7f69dSAidan Dodds             "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
3687b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
3688b9c1b51eSKate Stone                 eCommandProcessMustBePaused),
3689b9c1b51eSKate Stone         m_options() {}
36904640cde1SColin Riley 
3691222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
3692222b937cSEugene Zelenko 
3693b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
3694018f5a7eSEwan Crawford 
3695b9c1b51eSKate Stone   class CommandOptions : public Options {
3696018f5a7eSEwan Crawford   public:
3697e1cfbc79STodd Fiala     CommandOptions() : Options() {}
3698018f5a7eSEwan Crawford 
3699222b937cSEugene Zelenko     ~CommandOptions() override = default;
3700018f5a7eSEwan Crawford 
3701b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
3702b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
3703*80af0b9eSLuke Drummond       Error err;
3704018f5a7eSEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
3705018f5a7eSEwan Crawford 
3706b9c1b51eSKate Stone       switch (short_option) {
370700f56eebSLuke Drummond       case 'c': {
370800f56eebSLuke Drummond         auto coord = RSCoordinate{};
370900f56eebSLuke Drummond         if (!ParseCoordinate(option_arg, coord))
3710*80af0b9eSLuke Drummond           err.SetErrorStringWithFormat(
3711b9c1b51eSKate Stone               "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
3712b3f7f69dSAidan Dodds               option_arg);
371300f56eebSLuke Drummond         else {
371400f56eebSLuke Drummond           m_have_coord = true;
371500f56eebSLuke Drummond           m_coord = coord;
371600f56eebSLuke Drummond         }
3717018f5a7eSEwan Crawford         break;
371800f56eebSLuke Drummond       }
3719018f5a7eSEwan Crawford       default:
3720*80af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3721018f5a7eSEwan Crawford         break;
3722018f5a7eSEwan Crawford       }
3723*80af0b9eSLuke Drummond       return err;
3724018f5a7eSEwan Crawford     }
3725018f5a7eSEwan Crawford 
3726b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
372700f56eebSLuke Drummond       m_have_coord = false;
3728018f5a7eSEwan Crawford     }
3729018f5a7eSEwan Crawford 
37301f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
373170602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
37321f0f5b5bSZachary Turner     }
3733018f5a7eSEwan Crawford 
373400f56eebSLuke Drummond     RSCoordinate m_coord;
373500f56eebSLuke Drummond     bool m_have_coord;
3736018f5a7eSEwan Crawford   };
3737018f5a7eSEwan Crawford 
3738b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
37394640cde1SColin Riley     const size_t argc = command.GetArgumentCount();
3740b9c1b51eSKate Stone     if (argc < 1) {
3741b9c1b51eSKate Stone       result.AppendErrorWithFormat(
3742b9c1b51eSKate Stone           "'%s' takes 1 argument of kernel name, and an optional coordinate.",
3743b3f7f69dSAidan Dodds           m_cmd_name.c_str());
3744018f5a7eSEwan Crawford       result.SetStatus(eReturnStatusFailed);
3745018f5a7eSEwan Crawford       return false;
3746018f5a7eSEwan Crawford     }
3747018f5a7eSEwan Crawford 
37484640cde1SColin Riley     RenderScriptRuntime *runtime =
3749b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
3750b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
37514640cde1SColin Riley 
375200f56eebSLuke Drummond     auto &outstream = result.GetOutputStream();
375300f56eebSLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
375400f56eebSLuke Drummond     auto name = command.GetArgumentAtIndex(0);
375500f56eebSLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
375600f56eebSLuke Drummond     if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
375700f56eebSLuke Drummond       result.SetStatus(eReturnStatusFailed);
375800f56eebSLuke Drummond       result.AppendErrorWithFormat(
375900f56eebSLuke Drummond           "Error: unable to set breakpoint on kernel '%s'", name);
376000f56eebSLuke Drummond       return false;
376100f56eebSLuke Drummond     }
37624640cde1SColin Riley 
37634640cde1SColin Riley     result.AppendMessage("Breakpoint(s) created");
37644640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
37654640cde1SColin Riley     return true;
37664640cde1SColin Riley   }
37674640cde1SColin Riley 
3768018f5a7eSEwan Crawford private:
3769018f5a7eSEwan Crawford   CommandOptions m_options;
37704640cde1SColin Riley };
37714640cde1SColin Riley 
3772b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointAll
3773b9c1b51eSKate Stone     : public CommandObjectParsed {
37747dc7771cSEwan Crawford public:
3775b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointAll(
3776b9c1b51eSKate Stone       CommandInterpreter &interpreter)
3777b3f7f69dSAidan Dodds       : CommandObjectParsed(
3778b3f7f69dSAidan Dodds             interpreter, "renderscript kernel breakpoint all",
3779b9c1b51eSKate Stone             "Automatically sets a breakpoint on all renderscript kernels that "
3780b9c1b51eSKate Stone             "are or will be loaded.\n"
3781b9c1b51eSKate Stone             "Disabling option means breakpoints will no longer be set on any "
3782b9c1b51eSKate Stone             "kernels loaded in the future, "
37837dc7771cSEwan Crawford             "but does not remove currently set breakpoints.",
37847dc7771cSEwan Crawford             "renderscript kernel breakpoint all <enable/disable>",
3785b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
3786b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
37877dc7771cSEwan Crawford 
3788222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
37897dc7771cSEwan Crawford 
3790b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
37917dc7771cSEwan Crawford     const size_t argc = command.GetArgumentCount();
3792b9c1b51eSKate Stone     if (argc != 1) {
3793b9c1b51eSKate Stone       result.AppendErrorWithFormat(
3794b9c1b51eSKate Stone           "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
37957dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
37967dc7771cSEwan Crawford       return false;
37977dc7771cSEwan Crawford     }
37987dc7771cSEwan Crawford 
3799b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
3800b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
3801b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
38027dc7771cSEwan Crawford 
38037dc7771cSEwan Crawford     bool do_break = false;
38047dc7771cSEwan Crawford     const char *argument = command.GetArgumentAtIndex(0);
3805b9c1b51eSKate Stone     if (strcmp(argument, "enable") == 0) {
38067dc7771cSEwan Crawford       do_break = true;
38077dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will be set on all kernels.");
3808b9c1b51eSKate Stone     } else if (strcmp(argument, "disable") == 0) {
38097dc7771cSEwan Crawford       do_break = false;
38107dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will not be set on any new kernels.");
3811b9c1b51eSKate Stone     } else {
3812b9c1b51eSKate Stone       result.AppendErrorWithFormat(
3813b9c1b51eSKate Stone           "Argument must be either 'enable' or 'disable'");
38147dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
38157dc7771cSEwan Crawford       return false;
38167dc7771cSEwan Crawford     }
38177dc7771cSEwan Crawford 
38187dc7771cSEwan Crawford     runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
38197dc7771cSEwan Crawford 
38207dc7771cSEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
38217dc7771cSEwan Crawford     return true;
38227dc7771cSEwan Crawford   }
38237dc7771cSEwan Crawford };
38247dc7771cSEwan Crawford 
3825b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelCoordinate
3826b9c1b51eSKate Stone     : public CommandObjectParsed {
38274f8817c2SEwan Crawford public:
3828b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelCoordinate(
3829b9c1b51eSKate Stone       CommandInterpreter &interpreter)
3830b9c1b51eSKate Stone       : CommandObjectParsed(
3831b9c1b51eSKate Stone             interpreter, "renderscript kernel coordinate",
38324f8817c2SEwan Crawford             "Shows the (x,y,z) coordinate of the current kernel invocation.",
38334f8817c2SEwan Crawford             "renderscript kernel coordinate",
3834b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
3835b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
38364f8817c2SEwan Crawford 
38374f8817c2SEwan Crawford   ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
38384f8817c2SEwan Crawford 
3839b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
384000f56eebSLuke Drummond     RSCoordinate coord{};
3841b9c1b51eSKate Stone     bool success = RenderScriptRuntime::GetKernelCoordinate(
3842b9c1b51eSKate Stone         coord, m_exe_ctx.GetThreadPtr());
38434f8817c2SEwan Crawford     Stream &stream = result.GetOutputStream();
38444f8817c2SEwan Crawford 
3845b9c1b51eSKate Stone     if (success) {
384600f56eebSLuke Drummond       stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
38474f8817c2SEwan Crawford       stream.EOL();
38484f8817c2SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
3849b9c1b51eSKate Stone     } else {
38504f8817c2SEwan Crawford       stream.Printf("Error: Coordinate could not be found.");
38514f8817c2SEwan Crawford       stream.EOL();
38524f8817c2SEwan Crawford       result.SetStatus(eReturnStatusFailed);
38534f8817c2SEwan Crawford     }
38544f8817c2SEwan Crawford     return true;
38554f8817c2SEwan Crawford   }
38564f8817c2SEwan Crawford };
38574f8817c2SEwan Crawford 
3858b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpoint
3859b9c1b51eSKate Stone     : public CommandObjectMultiword {
38607dc7771cSEwan Crawford public:
3861b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpoint(
3862b9c1b51eSKate Stone       CommandInterpreter &interpreter)
3863b9c1b51eSKate Stone       : CommandObjectMultiword(
3864b9c1b51eSKate Stone             interpreter, "renderscript kernel",
3865b9c1b51eSKate Stone             "Commands that generate breakpoints on renderscript kernels.",
3866b9c1b51eSKate Stone             nullptr) {
3867b9c1b51eSKate Stone     LoadSubCommand(
3868b9c1b51eSKate Stone         "set",
3869b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
3870b9c1b51eSKate Stone             interpreter)));
3871b9c1b51eSKate Stone     LoadSubCommand(
3872b9c1b51eSKate Stone         "all",
3873b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
3874b9c1b51eSKate Stone             interpreter)));
38757dc7771cSEwan Crawford   }
38767dc7771cSEwan Crawford 
3877222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
38787dc7771cSEwan Crawford };
38797dc7771cSEwan Crawford 
3880b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
38814640cde1SColin Riley public:
38824640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
3883b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript kernel",
3884b9c1b51eSKate Stone                                "Commands that deal with RenderScript kernels.",
3885b9c1b51eSKate Stone                                nullptr) {
3886b9c1b51eSKate Stone     LoadSubCommand(
3887b9c1b51eSKate Stone         "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
3888b9c1b51eSKate Stone                     interpreter)));
3889b9c1b51eSKate Stone     LoadSubCommand(
3890b9c1b51eSKate Stone         "coordinate",
3891b9c1b51eSKate Stone         CommandObjectSP(
3892b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
3893b9c1b51eSKate Stone     LoadSubCommand(
3894b9c1b51eSKate Stone         "breakpoint",
3895b9c1b51eSKate Stone         CommandObjectSP(
3896b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
38974640cde1SColin Riley   }
38984640cde1SColin Riley 
3899222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernel() override = default;
39004640cde1SColin Riley };
39014640cde1SColin Riley 
3902b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
39034640cde1SColin Riley public:
39044640cde1SColin Riley   CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
3905b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript context dump",
3906b9c1b51eSKate Stone                             "Dumps renderscript context information.",
3907b9c1b51eSKate Stone                             "renderscript context dump",
3908b9c1b51eSKate Stone                             eCommandRequiresProcess |
3909b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
39104640cde1SColin Riley 
3911222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContextDump() override = default;
39124640cde1SColin Riley 
3913b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
39144640cde1SColin Riley     RenderScriptRuntime *runtime =
3915b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
3916b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
39174640cde1SColin Riley     runtime->DumpContexts(result.GetOutputStream());
39184640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
39194640cde1SColin Riley     return true;
39204640cde1SColin Riley   }
39214640cde1SColin Riley };
39224640cde1SColin Riley 
39231f0f5b5bSZachary Turner static OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
39241f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
39251f0f5b5bSZachary Turner      nullptr, nullptr, 0, eArgTypeFilename,
39261f0f5b5bSZachary Turner      "Print results to specified file instead of command line."}};
39271f0f5b5bSZachary Turner 
3928b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
39294640cde1SColin Riley public:
39304640cde1SColin Riley   CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
3931b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript context",
3932b9c1b51eSKate Stone                                "Commands that deal with RenderScript contexts.",
3933b9c1b51eSKate Stone                                nullptr) {
3934b9c1b51eSKate Stone     LoadSubCommand(
3935b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
3936b9c1b51eSKate Stone                     interpreter)));
39374640cde1SColin Riley   }
39384640cde1SColin Riley 
3939222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContext() override = default;
39404640cde1SColin Riley };
39414640cde1SColin Riley 
3942b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationDump
3943b9c1b51eSKate Stone     : public CommandObjectParsed {
3944a0f08674SEwan Crawford public:
3945b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationDump(
3946b9c1b51eSKate Stone       CommandInterpreter &interpreter)
3947a0f08674SEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation dump",
3948b9c1b51eSKate Stone                             "Displays the contents of a particular allocation",
3949b9c1b51eSKate Stone                             "renderscript allocation dump <ID>",
3950b9c1b51eSKate Stone                             eCommandRequiresProcess |
3951b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched),
3952b9c1b51eSKate Stone         m_options() {}
3953a0f08674SEwan Crawford 
3954222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
3955222b937cSEugene Zelenko 
3956b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
3957a0f08674SEwan Crawford 
3958b9c1b51eSKate Stone   class CommandOptions : public Options {
3959a0f08674SEwan Crawford   public:
3960e1cfbc79STodd Fiala     CommandOptions() : Options() {}
3961a0f08674SEwan Crawford 
3962222b937cSEugene Zelenko     ~CommandOptions() override = default;
3963a0f08674SEwan Crawford 
3964b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
3965b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
3966*80af0b9eSLuke Drummond       Error err;
3967a0f08674SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
3968a0f08674SEwan Crawford 
3969b9c1b51eSKate Stone       switch (short_option) {
3970a0f08674SEwan Crawford       case 'f':
3971a0f08674SEwan Crawford         m_outfile.SetFile(option_arg, true);
3972b9c1b51eSKate Stone         if (m_outfile.Exists()) {
3973a0f08674SEwan Crawford           m_outfile.Clear();
3974*80af0b9eSLuke Drummond           err.SetErrorStringWithFormat("file already exists: '%s'", option_arg);
3975a0f08674SEwan Crawford         }
3976a0f08674SEwan Crawford         break;
3977a0f08674SEwan Crawford       default:
3978*80af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3979a0f08674SEwan Crawford         break;
3980a0f08674SEwan Crawford       }
3981*80af0b9eSLuke Drummond       return err;
3982a0f08674SEwan Crawford     }
3983a0f08674SEwan Crawford 
3984b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
3985a0f08674SEwan Crawford       m_outfile.Clear();
3986a0f08674SEwan Crawford     }
3987a0f08674SEwan Crawford 
39881f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
398970602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
39901f0f5b5bSZachary Turner     }
3991a0f08674SEwan Crawford 
3992a0f08674SEwan Crawford     FileSpec m_outfile;
3993a0f08674SEwan Crawford   };
3994a0f08674SEwan Crawford 
3995b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
3996a0f08674SEwan Crawford     const size_t argc = command.GetArgumentCount();
3997b9c1b51eSKate Stone     if (argc < 1) {
3998b9c1b51eSKate Stone       result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
3999b9c1b51eSKate Stone                                    "As well as an optional -f argument",
4000a0f08674SEwan Crawford                                    m_cmd_name.c_str());
4001a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4002a0f08674SEwan Crawford       return false;
4003a0f08674SEwan Crawford     }
4004a0f08674SEwan Crawford 
4005b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4006b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4007b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4008a0f08674SEwan Crawford 
4009a0f08674SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
4010*80af0b9eSLuke Drummond     bool success = false;
4011b9c1b51eSKate Stone     const uint32_t id =
4012*80af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4013*80af0b9eSLuke Drummond     if (!success) {
4014b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4015b9c1b51eSKate Stone                                    id_cstr);
4016a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4017a0f08674SEwan Crawford       return false;
4018a0f08674SEwan Crawford     }
4019a0f08674SEwan Crawford 
4020a0f08674SEwan Crawford     Stream *output_strm = nullptr;
4021a0f08674SEwan Crawford     StreamFile outfile_stream;
4022b9c1b51eSKate Stone     const FileSpec &outfile_spec =
4023b9c1b51eSKate Stone         m_options.m_outfile; // Dump allocation to file instead
4024b9c1b51eSKate Stone     if (outfile_spec) {
4025a0f08674SEwan Crawford       // Open output file
4026a0f08674SEwan Crawford       char path[256];
4027a0f08674SEwan Crawford       outfile_spec.GetPath(path, sizeof(path));
4028b9c1b51eSKate Stone       if (outfile_stream.GetFile()
4029b9c1b51eSKate Stone               .Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate)
4030b9c1b51eSKate Stone               .Success()) {
4031a0f08674SEwan Crawford         output_strm = &outfile_stream;
4032a0f08674SEwan Crawford         result.GetOutputStream().Printf("Results written to '%s'", path);
4033a0f08674SEwan Crawford         result.GetOutputStream().EOL();
4034b9c1b51eSKate Stone       } else {
4035a0f08674SEwan Crawford         result.AppendErrorWithFormat("Couldn't open file '%s'", path);
4036a0f08674SEwan Crawford         result.SetStatus(eReturnStatusFailed);
4037a0f08674SEwan Crawford         return false;
4038a0f08674SEwan Crawford       }
4039b9c1b51eSKate Stone     } else
4040a0f08674SEwan Crawford       output_strm = &result.GetOutputStream();
4041a0f08674SEwan Crawford 
4042a0f08674SEwan Crawford     assert(output_strm != nullptr);
4043*80af0b9eSLuke Drummond     bool dumped =
4044b9c1b51eSKate Stone         runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4045a0f08674SEwan Crawford 
4046*80af0b9eSLuke Drummond     if (dumped)
4047a0f08674SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4048a0f08674SEwan Crawford     else
4049a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4050a0f08674SEwan Crawford 
4051a0f08674SEwan Crawford     return true;
4052a0f08674SEwan Crawford   }
4053a0f08674SEwan Crawford 
4054a0f08674SEwan Crawford private:
4055a0f08674SEwan Crawford   CommandOptions m_options;
4056a0f08674SEwan Crawford };
4057a0f08674SEwan Crawford 
40581f0f5b5bSZachary Turner static OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
40591f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
40601f0f5b5bSZachary Turner      nullptr, 0, eArgTypeIndex,
40611f0f5b5bSZachary Turner      "Only show details of a single allocation with specified id."}};
4062a0f08674SEwan Crawford 
4063b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationList
4064b9c1b51eSKate Stone     : public CommandObjectParsed {
406515f2bd95SEwan Crawford public:
4066b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationList(
4067b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4068b9c1b51eSKate Stone       : CommandObjectParsed(
4069b9c1b51eSKate Stone             interpreter, "renderscript allocation list",
4070b9c1b51eSKate Stone             "List renderscript allocations and their information.",
4071b9c1b51eSKate Stone             "renderscript allocation list",
4072b3f7f69dSAidan Dodds             eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4073b9c1b51eSKate Stone         m_options() {}
407415f2bd95SEwan Crawford 
4075222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4076222b937cSEugene Zelenko 
4077b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
407815f2bd95SEwan Crawford 
4079b9c1b51eSKate Stone   class CommandOptions : public Options {
408015f2bd95SEwan Crawford   public:
4081e1cfbc79STodd Fiala     CommandOptions() : Options(), m_id(0) {}
408215f2bd95SEwan Crawford 
4083222b937cSEugene Zelenko     ~CommandOptions() override = default;
408415f2bd95SEwan Crawford 
4085b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
4086b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
4087*80af0b9eSLuke Drummond       Error err;
408815f2bd95SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
408915f2bd95SEwan Crawford 
4090b9c1b51eSKate Stone       switch (short_option) {
4091b649b005SEwan Crawford       case 'i':
4092b649b005SEwan Crawford         bool success;
4093b649b005SEwan Crawford         m_id = StringConvert::ToUInt32(option_arg, 0, 0, &success);
4094b649b005SEwan Crawford         if (!success)
4095*80af0b9eSLuke Drummond           err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4096b9c1b51eSKate Stone                                        short_option);
409715f2bd95SEwan Crawford         break;
4098*80af0b9eSLuke Drummond       default:
4099*80af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4100*80af0b9eSLuke Drummond         break;
410115f2bd95SEwan Crawford       }
4102*80af0b9eSLuke Drummond       return err;
410315f2bd95SEwan Crawford     }
410415f2bd95SEwan Crawford 
4105b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
4106b649b005SEwan Crawford       m_id = 0;
410715f2bd95SEwan Crawford     }
410815f2bd95SEwan Crawford 
41091f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
411070602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
41111f0f5b5bSZachary Turner     }
411215f2bd95SEwan Crawford 
4113b649b005SEwan Crawford     uint32_t m_id;
411415f2bd95SEwan Crawford   };
411515f2bd95SEwan Crawford 
4116b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4117b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4118b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4119b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4120b9c1b51eSKate Stone     runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4121b9c1b51eSKate Stone                              m_options.m_id);
412215f2bd95SEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
412315f2bd95SEwan Crawford     return true;
412415f2bd95SEwan Crawford   }
412515f2bd95SEwan Crawford 
412615f2bd95SEwan Crawford private:
412715f2bd95SEwan Crawford   CommandOptions m_options;
412815f2bd95SEwan Crawford };
412915f2bd95SEwan Crawford 
4130b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationLoad
4131b9c1b51eSKate Stone     : public CommandObjectParsed {
413255232f09SEwan Crawford public:
4133b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationLoad(
4134b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4135b3f7f69dSAidan Dodds       : CommandObjectParsed(
4136b9c1b51eSKate Stone             interpreter, "renderscript allocation load",
4137b9c1b51eSKate Stone             "Loads renderscript allocation contents from a file.",
4138b9c1b51eSKate Stone             "renderscript allocation load <ID> <filename>",
4139b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
414055232f09SEwan Crawford 
4141222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
414255232f09SEwan Crawford 
4143b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
414455232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4145b9c1b51eSKate Stone     if (argc != 2) {
4146b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4147b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4148b3f7f69dSAidan Dodds           m_cmd_name.c_str());
414955232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
415055232f09SEwan Crawford       return false;
415155232f09SEwan Crawford     }
415255232f09SEwan Crawford 
4153b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4154b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4155b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
415655232f09SEwan Crawford 
415755232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
4158*80af0b9eSLuke Drummond     bool success = false;
4159b9c1b51eSKate Stone     const uint32_t id =
4160*80af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4161*80af0b9eSLuke Drummond     if (!success) {
4162b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4163b9c1b51eSKate Stone                                    id_cstr);
416455232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
416555232f09SEwan Crawford       return false;
416655232f09SEwan Crawford     }
416755232f09SEwan Crawford 
4168*80af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
4169*80af0b9eSLuke Drummond     bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
4170*80af0b9eSLuke Drummond                                           m_exe_ctx.GetFramePtr());
417155232f09SEwan Crawford 
4172*80af0b9eSLuke Drummond     if (loaded)
417355232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
417455232f09SEwan Crawford     else
417555232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
417655232f09SEwan Crawford 
417755232f09SEwan Crawford     return true;
417855232f09SEwan Crawford   }
417955232f09SEwan Crawford };
418055232f09SEwan Crawford 
4181b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationSave
4182b9c1b51eSKate Stone     : public CommandObjectParsed {
418355232f09SEwan Crawford public:
4184b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationSave(
4185b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4186b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript allocation save",
4187b9c1b51eSKate Stone                             "Write renderscript allocation contents to a file.",
4188b9c1b51eSKate Stone                             "renderscript allocation save <ID> <filename>",
4189b9c1b51eSKate Stone                             eCommandRequiresProcess |
4190b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
419155232f09SEwan Crawford 
4192222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
419355232f09SEwan Crawford 
4194b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
419555232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4196b9c1b51eSKate Stone     if (argc != 2) {
4197b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4198b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4199b3f7f69dSAidan Dodds           m_cmd_name.c_str());
420055232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
420155232f09SEwan Crawford       return false;
420255232f09SEwan Crawford     }
420355232f09SEwan Crawford 
4204b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4205b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4206b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
420755232f09SEwan Crawford 
420855232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
4209*80af0b9eSLuke Drummond     bool success = false;
4210b9c1b51eSKate Stone     const uint32_t id =
4211*80af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4212*80af0b9eSLuke Drummond     if (!success) {
4213b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4214b9c1b51eSKate Stone                                    id_cstr);
421555232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
421655232f09SEwan Crawford       return false;
421755232f09SEwan Crawford     }
421855232f09SEwan Crawford 
4219*80af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
4220*80af0b9eSLuke Drummond     bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
4221*80af0b9eSLuke Drummond                                          m_exe_ctx.GetFramePtr());
422255232f09SEwan Crawford 
4223*80af0b9eSLuke Drummond     if (saved)
422455232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
422555232f09SEwan Crawford     else
422655232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
422755232f09SEwan Crawford 
422855232f09SEwan Crawford     return true;
422955232f09SEwan Crawford   }
423055232f09SEwan Crawford };
423155232f09SEwan Crawford 
4232b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationRefresh
4233b9c1b51eSKate Stone     : public CommandObjectParsed {
42340d2bfcfbSEwan Crawford public:
4235b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationRefresh(
4236b9c1b51eSKate Stone       CommandInterpreter &interpreter)
42370d2bfcfbSEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4238b9c1b51eSKate Stone                             "Recomputes the details of all allocations.",
4239b9c1b51eSKate Stone                             "renderscript allocation refresh",
4240b9c1b51eSKate Stone                             eCommandRequiresProcess |
4241b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
42420d2bfcfbSEwan Crawford 
42430d2bfcfbSEwan Crawford   ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
42440d2bfcfbSEwan Crawford 
4245b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
42460d2bfcfbSEwan Crawford     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4247b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4248b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
42490d2bfcfbSEwan Crawford 
4250b9c1b51eSKate Stone     bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4251b9c1b51eSKate Stone                                                     m_exe_ctx.GetFramePtr());
42520d2bfcfbSEwan Crawford 
4253b9c1b51eSKate Stone     if (success) {
42540d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
42550d2bfcfbSEwan Crawford       return true;
4256b9c1b51eSKate Stone     } else {
42570d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusFailed);
42580d2bfcfbSEwan Crawford       return false;
42590d2bfcfbSEwan Crawford     }
42600d2bfcfbSEwan Crawford   }
42610d2bfcfbSEwan Crawford };
42620d2bfcfbSEwan Crawford 
4263b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocation
4264b9c1b51eSKate Stone     : public CommandObjectMultiword {
426515f2bd95SEwan Crawford public:
426615f2bd95SEwan Crawford   CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4267b9c1b51eSKate Stone       : CommandObjectMultiword(
4268b9c1b51eSKate Stone             interpreter, "renderscript allocation",
4269b9c1b51eSKate Stone             "Commands that deal with RenderScript allocations.", nullptr) {
4270b9c1b51eSKate Stone     LoadSubCommand(
4271b9c1b51eSKate Stone         "list",
4272b9c1b51eSKate Stone         CommandObjectSP(
4273b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4274b9c1b51eSKate Stone     LoadSubCommand(
4275b9c1b51eSKate Stone         "dump",
4276b9c1b51eSKate Stone         CommandObjectSP(
4277b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4278b9c1b51eSKate Stone     LoadSubCommand(
4279b9c1b51eSKate Stone         "save",
4280b9c1b51eSKate Stone         CommandObjectSP(
4281b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4282b9c1b51eSKate Stone     LoadSubCommand(
4283b9c1b51eSKate Stone         "load",
4284b9c1b51eSKate Stone         CommandObjectSP(
4285b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4286b9c1b51eSKate Stone     LoadSubCommand(
4287b9c1b51eSKate Stone         "refresh",
4288b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4289b9c1b51eSKate Stone             interpreter)));
429015f2bd95SEwan Crawford   }
429115f2bd95SEwan Crawford 
4292222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocation() override = default;
429315f2bd95SEwan Crawford };
429415f2bd95SEwan Crawford 
4295b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
42964640cde1SColin Riley public:
42974640cde1SColin Riley   CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4298b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript status",
4299b9c1b51eSKate Stone                             "Displays current RenderScript runtime status.",
4300b9c1b51eSKate Stone                             "renderscript status",
4301b9c1b51eSKate Stone                             eCommandRequiresProcess |
4302b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
43034640cde1SColin Riley 
4304222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeStatus() override = default;
43054640cde1SColin Riley 
4306b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
43074640cde1SColin Riley     RenderScriptRuntime *runtime =
4308b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4309b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
43104640cde1SColin Riley     runtime->Status(result.GetOutputStream());
43114640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
43124640cde1SColin Riley     return true;
43134640cde1SColin Riley   }
43144640cde1SColin Riley };
43154640cde1SColin Riley 
4316b9c1b51eSKate Stone class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
43175ec532a9SColin Riley public:
43185ec532a9SColin Riley   CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
4319b9c1b51eSKate Stone       : CommandObjectMultiword(
4320b9c1b51eSKate Stone             interpreter, "renderscript",
4321b9c1b51eSKate Stone             "Commands for operating on the RenderScript runtime.",
4322b9c1b51eSKate Stone             "renderscript <subcommand> [<subcommand-options>]") {
4323b9c1b51eSKate Stone     LoadSubCommand(
4324b9c1b51eSKate Stone         "module", CommandObjectSP(
4325b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeModule(interpreter)));
4326b9c1b51eSKate Stone     LoadSubCommand(
4327b9c1b51eSKate Stone         "status", CommandObjectSP(
4328b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeStatus(interpreter)));
4329b9c1b51eSKate Stone     LoadSubCommand(
4330b9c1b51eSKate Stone         "kernel", CommandObjectSP(
4331b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeKernel(interpreter)));
4332b9c1b51eSKate Stone     LoadSubCommand("context",
4333b9c1b51eSKate Stone                    CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
4334b9c1b51eSKate Stone                        interpreter)));
4335b9c1b51eSKate Stone     LoadSubCommand(
4336b9c1b51eSKate Stone         "allocation",
4337b9c1b51eSKate Stone         CommandObjectSP(
4338b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
43395ec532a9SColin Riley   }
43405ec532a9SColin Riley 
4341222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntime() override = default;
43425ec532a9SColin Riley };
4343ef20b08fSColin Riley 
4344b9c1b51eSKate Stone void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
4345ef20b08fSColin Riley 
4346ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
4347b9c1b51eSKate Stone     : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
4348b9c1b51eSKate Stone       m_debuggerPresentFlagged(false), m_breakAllKernels(false),
4349b9c1b51eSKate Stone       m_ir_passes(nullptr) {
43504640cde1SColin Riley   ModulesDidLoad(process->GetTarget().GetImages());
4351ef20b08fSColin Riley }
43524640cde1SColin Riley 
4353b9c1b51eSKate Stone lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
4354b9c1b51eSKate Stone     lldb_private::CommandInterpreter &interpreter) {
43550a66e2f1SEnrico Granata   return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
43564640cde1SColin Riley }
43574640cde1SColin Riley 
435878f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
4359