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 
46*00f56eebSLuke Drummond #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")"
47*00f56eebSLuke Drummond 
48b9c1b51eSKate Stone namespace {
4978f339d1SEwan Crawford 
5078f339d1SEwan Crawford // The empirical_type adds a basic level of validation to arbitrary data
5178f339d1SEwan Crawford // allowing us to track if data has been discovered and stored or not.
52b9c1b51eSKate Stone // An 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 
11967dc3e15SAidan Dodds   Error error;
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;
132f4786785SAidan Dodds     Error error;
133b9c1b51eSKate Stone     size_t read =
134b9c1b51eSKate Stone         ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), error);
135b9c1b51eSKate Stone     if (read != arg_size || !error.Success()) {
136f4786785SAidan Dodds       if (log)
137b9c1b51eSKate Stone         log->Printf("%s - error reading argument: %" PRIu64 " '%s'",
138b9c1b51eSKate Stone                     __FUNCTION__, uint64_t(i), error.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
149f4786785SAidan Dodds   static const uint32_t c_args_in_reg = 6;
150f4786785SAidan Dodds   // register passing order
151b9c1b51eSKate Stone   static const std::array<const char *, c_args_in_reg> c_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 
16217e07c0aSAidan Dodds   Error error;
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;
178b9c1b51eSKate Stone   for (uint32_t i = c_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
189b9c1b51eSKate Stone     if (i < c_args_in_reg) {
190b9c1b51eSKate Stone       const RegisterInfo *rArg =
191b9c1b51eSKate Stone           ctx.reg_ctx->GetRegisterInfoByName(c_reg_names[i]);
192f4786785SAidan Dodds       RegisterValue rVal;
193f4786785SAidan Dodds       if (ctx.reg_ctx->ReadRegister(rArg, rVal))
194f4786785SAidan Dodds         arg.value = rVal.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.
204f4786785SAidan Dodds       size_t read = ctx.process->ReadMemory(sp, &arg.value, size, error);
205f4786785SAidan Dodds       success = (error.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",
21317e07c0aSAidan Dodds                     __FUNCTION__, uint64_t(i), error.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
222f4786785SAidan Dodds   static const uint32_t c_args_in_reg = 4;
223f4786785SAidan Dodds 
224f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
225f4786785SAidan Dodds 
22617e07c0aSAidan Dodds   Error error;
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
235b9c1b51eSKate Stone     if (i < c_args_in_reg) {
236f4786785SAidan Dodds       const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
237f4786785SAidan Dodds       RegisterValue rVal;
238f4786785SAidan Dodds       if (ctx.reg_ctx->ReadRegister(rArg, rVal))
239f4786785SAidan Dodds         arg.value = rVal.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 =
249b9c1b51eSKate Stone           ctx.process->ReadMemory(sp, &arg.value, arg_size, error);
250f4786785SAidan Dodds       success = (error.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",
25817e07c0aSAidan Dodds                     __FUNCTION__, uint64_t(i), error.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
267f4786785SAidan Dodds   static const uint32_t c_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
275b9c1b51eSKate Stone     if (i < c_args_in_reg) {
276f4786785SAidan Dodds       const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
277f4786785SAidan Dodds       RegisterValue rVal;
278f4786785SAidan Dodds       if (ctx.reg_ctx->ReadRegister(rArg, rVal))
279f4786785SAidan Dodds         arg.value = rVal.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
300f4786785SAidan Dodds   static const uint32_t c_args_in_reg = 4;
301f4786785SAidan Dodds   // register file offset to first argument
302f4786785SAidan Dodds   static const uint32_t c_reg_offset = 4;
303f4786785SAidan Dodds 
304f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
305f4786785SAidan Dodds 
30617e07c0aSAidan Dodds   Error error;
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
315b9c1b51eSKate Stone     if (i < c_args_in_reg) {
316b9c1b51eSKate Stone       const RegisterInfo *rArg =
317b9c1b51eSKate Stone           ctx.reg_ctx->GetRegisterInfoAtIndex(i + c_reg_offset);
318f4786785SAidan Dodds       RegisterValue rVal;
319f4786785SAidan Dodds       if (ctx.reg_ctx->ReadRegister(rArg, rVal))
320f4786785SAidan Dodds         arg.value = rVal.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 =
327b9c1b51eSKate Stone           ctx.process->ReadMemory(sp, &arg.value, arg_size, error);
3286dd4b579SAidan Dodds       success = (error.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",
33667dc3e15SAidan Dodds                     __FUNCTION__, uint64_t(i), error.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
345f4786785SAidan Dodds   static const uint32_t c_args_in_reg = 8;
346f4786785SAidan Dodds   // register file offset to first argument
347f4786785SAidan Dodds   static const uint32_t c_reg_offset = 4;
348f4786785SAidan Dodds 
349f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
350f4786785SAidan Dodds 
35117e07c0aSAidan Dodds   Error error;
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
360b9c1b51eSKate Stone     if (i < c_args_in_reg) {
361b9c1b51eSKate Stone       const RegisterInfo *rArg =
362b9c1b51eSKate Stone           ctx.reg_ctx->GetRegisterInfoAtIndex(i + c_reg_offset);
363f4786785SAidan Dodds       RegisterValue rVal;
364f4786785SAidan Dodds       if (ctx.reg_ctx->ReadRegister(rArg, rVal))
36572f77525SAidan Dodds         arg.value = rVal.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 =
375b9c1b51eSKate Stone           ctx.process->ReadMemory(sp, &arg.value, arg_size, error);
376f4786785SAidan Dodds       success = (error.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",
38417e07c0aSAidan Dodds                     __FUNCTION__, uint64_t(i), error.AsCString("n/a"));
385f4786785SAidan Dodds       return false;
386f4786785SAidan Dodds     }
387f4786785SAidan Dodds   }
388f4786785SAidan Dodds   return true;
389f4786785SAidan Dodds }
390f4786785SAidan Dodds 
391b9c1b51eSKate Stone bool GetArgs(ExecutionContext &context, 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
395b9c1b51eSKate Stone   if (!context.GetTargetPtr()) {
396f4786785SAidan Dodds     if (log)
397f4786785SAidan Dodds       log->Printf("%s - invalid target", __FUNCTION__);
398f4786785SAidan Dodds     return false;
399f4786785SAidan Dodds   }
400f4786785SAidan Dodds 
401f4786785SAidan Dodds   GetArgsCtx ctx = {context.GetRegisterContext(), context.GetProcessPtr()};
402f4786785SAidan Dodds   assert(ctx.reg_ctx && ctx.process);
403f4786785SAidan Dodds 
404f4786785SAidan Dodds   // dispatch based on architecture
405b9c1b51eSKate Stone   switch (context.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__,
429f4786785SAidan Dodds           context.GetTargetRef().GetArchitecture().GetArchitectureName());
430f4786785SAidan Dodds     }
431f4786785SAidan Dodds     return false;
432f4786785SAidan Dodds   }
433f4786785SAidan Dodds }
434*00f56eebSLuke Drummond 
435*00f56eebSLuke Drummond bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
436*00f56eebSLuke Drummond   // takes an argument of the form 'num[,num][,num]'.
437*00f56eebSLuke Drummond   // Where 'coord_s' is a comma separated 1,2 or 3-dimensional coordinate
438*00f56eebSLuke Drummond   // with the whitespace trimmed.
439*00f56eebSLuke Drummond   // Missing coordinates are defaulted to zero.
440*00f56eebSLuke Drummond   // If parsing of any elements fails the contents of &coord are undefined
441*00f56eebSLuke Drummond   // and `false` is returned, `true` otherwise
442*00f56eebSLuke Drummond 
443*00f56eebSLuke Drummond   RegularExpression regex;
444*00f56eebSLuke Drummond   RegularExpression::Match regex_match(3);
445*00f56eebSLuke Drummond 
446*00f56eebSLuke Drummond   bool matched = false;
447*00f56eebSLuke Drummond   if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+),([0-9]+)$")) &&
448*00f56eebSLuke Drummond       regex.Execute(coord_s, &regex_match))
449*00f56eebSLuke Drummond     matched = true;
450*00f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+)$")) &&
451*00f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
452*00f56eebSLuke Drummond     matched = true;
453*00f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([0-9]+)$")) &&
454*00f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
455*00f56eebSLuke Drummond     matched = true;
456*00f56eebSLuke Drummond 
457*00f56eebSLuke Drummond   if (!matched)
458*00f56eebSLuke Drummond     return false;
459*00f56eebSLuke Drummond 
460*00f56eebSLuke Drummond   auto get_index = [&](int idx, uint32_t &i) -> bool {
461*00f56eebSLuke Drummond     std::string group;
462*00f56eebSLuke Drummond     errno = 0;
463*00f56eebSLuke Drummond     if (regex_match.GetMatchAtIndex(coord_s.str().c_str(), idx + 1, group))
464*00f56eebSLuke Drummond       return !llvm::StringRef(group).getAsInteger<uint32_t>(10, i);
465*00f56eebSLuke Drummond     return true;
466*00f56eebSLuke Drummond   };
467*00f56eebSLuke Drummond 
468*00f56eebSLuke Drummond   return get_index(0, coord.x) && get_index(1, coord.y) &&
469*00f56eebSLuke Drummond          get_index(2, coord.z);
470*00f56eebSLuke 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.
48378f339d1SEwan Crawford   empirical_type<std::string> resName;
48478f339d1SEwan Crawford   // Path to script .so file on the device.
48578f339d1SEwan Crawford   empirical_type<std::string> scriptDyLib;
48678f339d1SEwan Crawford   // Directory where kernel objects are cached on device.
48778f339d1SEwan Crawford   empirical_type<std::string> cacheDir;
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 
4948b244e21SEwan Crawford // This Element class represents the Element object in RS,
4958b244e21SEwan Crawford // defining the type 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 
569b9c1b51eSKate Stone   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;
58415f2bd95SEwan Crawford     uint32_t cubeMap;
58515f2bd95SEwan Crawford 
586b9c1b51eSKate Stone     Dimension() {
58715f2bd95SEwan Crawford       dim_1 = 0;
58815f2bd95SEwan Crawford       dim_2 = 0;
58915f2bd95SEwan Crawford       dim_3 = 0;
59015f2bd95SEwan Crawford       cubeMap = 0;
59115f2bd95SEwan Crawford     }
59278f339d1SEwan Crawford   };
59378f339d1SEwan Crawford 
594b9c1b51eSKate Stone   // The FileHeader struct specifies the header we use for writing allocations
595b9c1b51eSKate Stone   // to a binary file.
596b9c1b51eSKate Stone   // Our format begins with the ASCII characters "RSAD", identifying the file as
597b9c1b51eSKate Stone   // an allocation dump.
598b9c1b51eSKate Stone   // Member variables dims and hdr_size are then written consecutively,
599b9c1b51eSKate Stone   // immediately followed by an instance of
600b9c1b51eSKate Stone   // the ElementHeader struct. Because Elements can contain subelements, there
601b9c1b51eSKate Stone   // may be more than one instance
602b9c1b51eSKate Stone   // of the ElementHeader struct. With this first instance being the root
603b9c1b51eSKate Stone   // element, and the other instances being
604b9c1b51eSKate Stone   // the root's descendants. To identify which instances are an ElementHeader's
605b9c1b51eSKate Stone   // children, each struct
606b9c1b51eSKate Stone   // is immediately followed by a sequence of consecutive offsets to the start
607b9c1b51eSKate Stone   // of its child structs.
608b9c1b51eSKate Stone   // These offsets are 4 bytes in size, and the 0 offset signifies no more
609b9c1b51eSKate Stone   // children.
610b9c1b51eSKate Stone   struct FileHeader {
61155232f09SEwan Crawford     uint8_t ident[4];  // ASCII 'RSAD' identifying the file
61226e52a70SEwan Crawford     uint32_t dims[3];  // Dimensions
61326e52a70SEwan Crawford     uint16_t hdr_size; // Header size in bytes, including all element headers
61426e52a70SEwan Crawford   };
61526e52a70SEwan Crawford 
616b9c1b51eSKate Stone   struct ElementHeader {
61755232f09SEwan Crawford     uint16_t type;         // DataType enum
61855232f09SEwan Crawford     uint32_t kind;         // DataKind enum
61955232f09SEwan Crawford     uint32_t element_size; // Size of a single element, including padding
62026e52a70SEwan Crawford     uint16_t vector_size;  // Vector width
62126e52a70SEwan Crawford     uint32_t array_size;   // Number of elements in array
62255232f09SEwan Crawford   };
62355232f09SEwan Crawford 
62415f2bd95SEwan Crawford   // Monotonically increasing from 1
625b3f7f69dSAidan Dodds   static uint32_t ID;
62615f2bd95SEwan Crawford 
62715f2bd95SEwan Crawford   // Maps Allocation DataType enum and vector size to printable strings
62815f2bd95SEwan Crawford   // using mapping from RenderScript numerical types summary documentation
62915f2bd95SEwan Crawford   static const char *RsDataTypeToString[][4];
63015f2bd95SEwan Crawford 
63115f2bd95SEwan Crawford   // Maps Allocation DataKind enum to printable strings
63215f2bd95SEwan Crawford   static const char *RsDataKindToString[];
63315f2bd95SEwan Crawford 
634a0f08674SEwan Crawford   // Maps allocation types to format sizes for printing.
635b3f7f69dSAidan Dodds   static const uint32_t RSTypeToFormat[][3];
636a0f08674SEwan Crawford 
63715f2bd95SEwan Crawford   // Give each allocation an ID as a way
63815f2bd95SEwan Crawford   // for commands to reference it.
639b3f7f69dSAidan Dodds   const uint32_t id;
64015f2bd95SEwan Crawford 
6418b244e21SEwan Crawford   RenderScriptRuntime::Element element; // Allocation Element type
64215f2bd95SEwan Crawford   empirical_type<Dimension> dimension;  // Dimensions of the Allocation
643b9c1b51eSKate Stone   empirical_type<lldb::addr_t>
644b9c1b51eSKate Stone       address; // Pointer to address of the RS Allocation
645b9c1b51eSKate Stone   empirical_type<lldb::addr_t>
646b9c1b51eSKate Stone       data_ptr; // Pointer to the data held by the Allocation
647b9c1b51eSKate Stone   empirical_type<lldb::addr_t>
648b9c1b51eSKate Stone       type_ptr; // Pointer to the RS Type of the Allocation
649b9c1b51eSKate Stone   empirical_type<lldb::addr_t>
650b9c1b51eSKate Stone       context;                   // Pointer to the RS Context of the Allocation
651a0f08674SEwan Crawford   empirical_type<uint32_t> size; // Size of the allocation
652a0f08674SEwan Crawford   empirical_type<uint32_t> stride; // Stride between rows of the allocation
65315f2bd95SEwan Crawford 
65415f2bd95SEwan Crawford   // Give each allocation an id, so we can reference it in user commands.
655b3f7f69dSAidan Dodds   AllocationDetails() : id(ID++) {}
6568b59062aSEwan Crawford 
657b9c1b51eSKate Stone   bool shouldRefresh() const {
6588b59062aSEwan Crawford     bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
6598b59062aSEwan Crawford     valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
660b9c1b51eSKate Stone     return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
661b9c1b51eSKate Stone            element.shouldRefresh();
6628b59062aSEwan Crawford   }
66315f2bd95SEwan Crawford };
66415f2bd95SEwan Crawford 
665b9c1b51eSKate Stone const ConstString &RenderScriptRuntime::Element::GetFallbackStructName() {
666fe06b5adSAdrian McCarthy   static const ConstString FallbackStructName("struct");
667fe06b5adSAdrian McCarthy   return FallbackStructName;
668fe06b5adSAdrian McCarthy }
6698b244e21SEwan Crawford 
670b3f7f69dSAidan Dodds uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
67115f2bd95SEwan Crawford 
672b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
673b9c1b51eSKate Stone     "User",       "Undefined",   "Undefined", "Undefined",
674b9c1b51eSKate Stone     "Undefined",  "Undefined",   "Undefined", // Enum jumps from 0 to 7
675b3f7f69dSAidan Dodds     "L Pixel",    "A Pixel",     "LA Pixel",  "RGB Pixel",
676b3f7f69dSAidan Dodds     "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
67715f2bd95SEwan Crawford 
678b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
67915f2bd95SEwan Crawford     {"None", "None", "None", "None"},
68015f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
68115f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
68215f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
68315f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
68415f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
68515f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
68615f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
68715f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
68815f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
68915f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
69015f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
6912e920715SEwan Crawford     {"bool", "bool2", "bool3", "bool4"},
6922e920715SEwan Crawford     {"packed_565", "packed_565", "packed_565", "packed_565"},
6932e920715SEwan Crawford     {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
6942e920715SEwan Crawford     {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
6952e920715SEwan Crawford     {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
6962e920715SEwan Crawford     {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
6972e920715SEwan Crawford     {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
6982e920715SEwan Crawford 
6992e920715SEwan Crawford     // Handlers
7002e920715SEwan Crawford     {"RS Element", "RS Element", "RS Element", "RS Element"},
7012e920715SEwan Crawford     {"RS Type", "RS Type", "RS Type", "RS Type"},
7022e920715SEwan Crawford     {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
7032e920715SEwan Crawford     {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
7042e920715SEwan Crawford     {"RS Script", "RS Script", "RS Script", "RS Script"},
7052e920715SEwan Crawford 
7062e920715SEwan Crawford     // Deprecated
7072e920715SEwan Crawford     {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
708b9c1b51eSKate Stone     {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
709b9c1b51eSKate Stone      "RS Program Fragment"},
710b9c1b51eSKate Stone     {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
711b9c1b51eSKate Stone      "RS Program Vertex"},
712b9c1b51eSKate Stone     {"RS Program Raster", "RS Program Raster", "RS Program Raster",
713b9c1b51eSKate Stone      "RS Program Raster"},
714b9c1b51eSKate Stone     {"RS Program Store", "RS Program Store", "RS Program Store",
715b9c1b51eSKate Stone      "RS Program Store"},
716b3f7f69dSAidan Dodds     {"RS Font", "RS Font", "RS Font", "RS Font"}};
71778f339d1SEwan Crawford 
718a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
719b9c1b51eSKate Stone enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
720a0f08674SEwan Crawford 
721b9c1b51eSKate Stone // { format enum of single element, format enum of element vector, size of
722b9c1b51eSKate Stone // element}
723b3f7f69dSAidan Dodds const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
724a0f08674SEwan Crawford     {eFormatHex, eFormatHex, 1},                            // RS_TYPE_NONE
725a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat16, 2},              // RS_TYPE_FLOAT_16
726a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},  // RS_TYPE_FLOAT_32
727a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)}, // RS_TYPE_FLOAT_64
728a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)}, // RS_TYPE_SIGNED_8
729b9c1b51eSKate Stone     {eFormatDecimal, eFormatVectorOfSInt16,
730b9c1b51eSKate Stone      sizeof(int16_t)}, // RS_TYPE_SIGNED_16
731b9c1b51eSKate Stone     {eFormatDecimal, eFormatVectorOfSInt32,
732b9c1b51eSKate Stone      sizeof(int32_t)}, // RS_TYPE_SIGNED_32
733b9c1b51eSKate Stone     {eFormatDecimal, eFormatVectorOfSInt64,
734b9c1b51eSKate Stone      sizeof(int64_t)}, // RS_TYPE_SIGNED_64
735b9c1b51eSKate Stone     {eFormatDecimal, eFormatVectorOfUInt8,
736b9c1b51eSKate Stone      sizeof(uint8_t)}, // RS_TYPE_UNSIGNED_8
737b9c1b51eSKate Stone     {eFormatDecimal, eFormatVectorOfUInt16,
738b9c1b51eSKate Stone      sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_16
739b9c1b51eSKate Stone     {eFormatDecimal, eFormatVectorOfUInt32,
740b9c1b51eSKate Stone      sizeof(uint32_t)}, // RS_TYPE_UNSIGNED_32
741b9c1b51eSKate Stone     {eFormatDecimal, eFormatVectorOfUInt64,
742b9c1b51eSKate Stone      sizeof(uint64_t)},                         // RS_TYPE_UNSIGNED_64
7432e920715SEwan Crawford     {eFormatBoolean, eFormatBoolean, 1},        // RS_TYPE_BOOL
7442e920715SEwan Crawford     {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_5_6_5
7452e920715SEwan Crawford     {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_5_5_5_1
7462e920715SEwan Crawford     {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_4_4_4_4
747b9c1b51eSKate Stone     {eFormatVectorOfFloat32, eFormatVectorOfFloat32,
748b9c1b51eSKate Stone      sizeof(float) * 16}, // RS_TYPE_MATRIX_4X4
749b9c1b51eSKate Stone     {eFormatVectorOfFloat32, eFormatVectorOfFloat32,
750b9c1b51eSKate Stone      sizeof(float) * 9}, // RS_TYPE_MATRIX_3X3
751b9c1b51eSKate Stone     {eFormatVectorOfFloat32, eFormatVectorOfFloat32,
752b9c1b51eSKate Stone      sizeof(float) * 4} // RS_TYPE_MATRIX_2X2
753a0f08674SEwan Crawford };
754a0f08674SEwan Crawford 
7555ec532a9SColin Riley //------------------------------------------------------------------
7565ec532a9SColin Riley // Static Functions
7575ec532a9SColin Riley //------------------------------------------------------------------
7585ec532a9SColin Riley LanguageRuntime *
759b9c1b51eSKate Stone RenderScriptRuntime::CreateInstance(Process *process,
760b9c1b51eSKate Stone                                     lldb::LanguageType language) {
7615ec532a9SColin Riley 
7625ec532a9SColin Riley   if (language == eLanguageTypeExtRenderScript)
7635ec532a9SColin Riley     return new RenderScriptRuntime(process);
7645ec532a9SColin Riley   else
765b3f7f69dSAidan Dodds     return nullptr;
7665ec532a9SColin Riley }
7675ec532a9SColin Riley 
76898156583SEwan Crawford // Callback with a module to search for matching symbols.
76998156583SEwan Crawford // We first check that the module contains RS kernels.
77098156583SEwan Crawford // Then look for a symbol which matches our kernel name.
77198156583SEwan Crawford // The breakpoint address is finally set using the address of this symbol.
77298156583SEwan Crawford Searcher::CallbackReturn
773b9c1b51eSKate Stone RSBreakpointResolver::SearchCallback(SearchFilter &filter,
774b9c1b51eSKate Stone                                      SymbolContext &context, Address *, bool) {
77598156583SEwan Crawford   ModuleSP module = context.module_sp;
77698156583SEwan Crawford 
77798156583SEwan Crawford   if (!module)
77898156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
77998156583SEwan Crawford 
78098156583SEwan Crawford   // Is this a module containing renderscript kernels?
781b9c1b51eSKate Stone   if (nullptr ==
782b9c1b51eSKate Stone       module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
783b9c1b51eSKate Stone                                              eSymbolTypeData))
78498156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
78598156583SEwan Crawford 
786b9c1b51eSKate Stone   // Attempt to set a breakpoint on the kernel name symbol within the module
787b9c1b51eSKate Stone   // library.
78898156583SEwan Crawford   // If it's not found, it's likely debug info is unavailable - try to set a
78998156583SEwan Crawford   // breakpoint on <name>.expand.
79098156583SEwan Crawford 
791b9c1b51eSKate Stone   const Symbol *kernel_sym =
792b9c1b51eSKate Stone       module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
793b9c1b51eSKate Stone   if (!kernel_sym) {
79498156583SEwan Crawford     std::string kernel_name_expanded(m_kernel_name.AsCString());
79598156583SEwan Crawford     kernel_name_expanded.append(".expand");
796b9c1b51eSKate Stone     kernel_sym = module->FindFirstSymbolWithNameAndType(
797b9c1b51eSKate Stone         ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
79898156583SEwan Crawford   }
79998156583SEwan Crawford 
800b9c1b51eSKate Stone   if (kernel_sym) {
80198156583SEwan Crawford     Address bp_addr = kernel_sym->GetAddress();
80298156583SEwan Crawford     if (filter.AddressPasses(bp_addr))
80398156583SEwan Crawford       m_breakpoint->AddLocation(bp_addr);
80498156583SEwan Crawford   }
80598156583SEwan Crawford 
80698156583SEwan Crawford   return Searcher::eCallbackReturnContinue;
80798156583SEwan Crawford }
80898156583SEwan Crawford 
809b9c1b51eSKate Stone void RenderScriptRuntime::Initialize() {
810b9c1b51eSKate Stone   PluginManager::RegisterPlugin(GetPluginNameStatic(),
811b9c1b51eSKate Stone                                 "RenderScript language support", CreateInstance,
812b3f7f69dSAidan Dodds                                 GetCommandObject);
8135ec532a9SColin Riley }
8145ec532a9SColin Riley 
815b9c1b51eSKate Stone void RenderScriptRuntime::Terminate() {
8165ec532a9SColin Riley   PluginManager::UnregisterPlugin(CreateInstance);
8175ec532a9SColin Riley }
8185ec532a9SColin Riley 
819b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginNameStatic() {
8205ec532a9SColin Riley   static ConstString g_name("renderscript");
8215ec532a9SColin Riley   return g_name;
8225ec532a9SColin Riley }
8235ec532a9SColin Riley 
824ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
825b9c1b51eSKate Stone RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
826b9c1b51eSKate Stone   if (module_sp) {
827ef20b08fSColin Riley     // Is this a module containing renderscript kernels?
828b9c1b51eSKate Stone     const Symbol *info_sym = module_sp->FindFirstSymbolWithNameAndType(
829b9c1b51eSKate Stone         ConstString(".rs.info"), eSymbolTypeData);
830b9c1b51eSKate Stone     if (info_sym) {
831ef20b08fSColin Riley       return eModuleKindKernelObj;
832ef20b08fSColin Riley     }
8334640cde1SColin Riley 
8344640cde1SColin Riley     // Is this the main RS runtime library
8354640cde1SColin Riley     const ConstString rs_lib("libRS.so");
836b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
8374640cde1SColin Riley       return eModuleKindLibRS;
8384640cde1SColin Riley     }
8394640cde1SColin Riley 
8404640cde1SColin Riley     const ConstString rs_driverlib("libRSDriver.so");
841b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
8424640cde1SColin Riley       return eModuleKindDriver;
8434640cde1SColin Riley     }
8444640cde1SColin Riley 
84515f2bd95SEwan Crawford     const ConstString rs_cpureflib("libRSCpuRef.so");
846b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
8474640cde1SColin Riley       return eModuleKindImpl;
8484640cde1SColin Riley     }
849ef20b08fSColin Riley   }
850ef20b08fSColin Riley   return eModuleKindIgnored;
851ef20b08fSColin Riley }
852ef20b08fSColin Riley 
853b9c1b51eSKate Stone bool RenderScriptRuntime::IsRenderScriptModule(
854b9c1b51eSKate Stone     const lldb::ModuleSP &module_sp) {
855ef20b08fSColin Riley   return GetModuleKind(module_sp) != eModuleKindIgnored;
856ef20b08fSColin Riley }
857ef20b08fSColin Riley 
858b9c1b51eSKate Stone void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
859bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
860ef20b08fSColin Riley 
861ef20b08fSColin Riley   size_t num_modules = module_list.GetSize();
862b9c1b51eSKate Stone   for (size_t i = 0; i < num_modules; i++) {
863ef20b08fSColin Riley     auto mod = module_list.GetModuleAtIndex(i);
864b9c1b51eSKate Stone     if (IsRenderScriptModule(mod)) {
865ef20b08fSColin Riley       LoadModule(mod);
866ef20b08fSColin Riley     }
867ef20b08fSColin Riley   }
868ef20b08fSColin Riley }
869ef20b08fSColin Riley 
8705ec532a9SColin Riley //------------------------------------------------------------------
8715ec532a9SColin Riley // PluginInterface protocol
8725ec532a9SColin Riley //------------------------------------------------------------------
873b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginName() {
8745ec532a9SColin Riley   return GetPluginNameStatic();
8755ec532a9SColin Riley }
8765ec532a9SColin Riley 
877b9c1b51eSKate Stone uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; }
8785ec532a9SColin Riley 
879b9c1b51eSKate Stone bool RenderScriptRuntime::IsVTableName(const char *name) { return false; }
8805ec532a9SColin Riley 
881b9c1b51eSKate Stone bool RenderScriptRuntime::GetDynamicTypeAndAddress(
882b9c1b51eSKate Stone     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
8835f57b6eeSEnrico Granata     TypeAndOrName &class_type_or_name, Address &address,
884b9c1b51eSKate Stone     Value::ValueType &value_type) {
8855ec532a9SColin Riley   return false;
8865ec532a9SColin Riley }
8875ec532a9SColin Riley 
888c74275bcSEnrico Granata TypeAndOrName
889b9c1b51eSKate Stone RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
890b9c1b51eSKate Stone                                       ValueObject &static_value) {
891c74275bcSEnrico Granata   return type_and_or_name;
892c74275bcSEnrico Granata }
893c74275bcSEnrico Granata 
894b9c1b51eSKate Stone bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
8955ec532a9SColin Riley   return false;
8965ec532a9SColin Riley }
8975ec532a9SColin Riley 
8985ec532a9SColin Riley lldb::BreakpointResolverSP
899b9c1b51eSKate Stone RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp,
900b9c1b51eSKate Stone                                              bool throw_bp) {
9015ec532a9SColin Riley   BreakpointResolverSP resolver_sp;
9025ec532a9SColin Riley   return resolver_sp;
9035ec532a9SColin Riley }
9045ec532a9SColin Riley 
905b9c1b51eSKate Stone const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
906b9c1b51eSKate Stone     {
9074640cde1SColin Riley         // rsdScript
908b9c1b51eSKate Stone         {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
909b9c1b51eSKate Stone                           "NS0_7ScriptCEPKcS7_PKhjj",
910b9c1b51eSKate Stone          "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
911b9c1b51eSKate Stone          "7ScriptCEPKcS7_PKhmj",
912b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
913b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInit},
914b9c1b51eSKate Stone         {"rsdScriptInvokeForEachMulti",
915b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
916b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
917b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
918b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
919b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
920b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
921b9c1b51eSKate Stone         {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
922b9c1b51eSKate Stone                                   "script7ContextEPKNS0_6ScriptEjPvj",
923b9c1b51eSKate Stone          "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
924b9c1b51eSKate Stone          "6ScriptEjPvm",
925b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
926b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
9274640cde1SColin Riley 
9284640cde1SColin Riley         // rsdAllocation
929b9c1b51eSKate Stone         {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
930b9c1b51eSKate Stone                               "ontextEPNS0_10AllocationEb",
931b9c1b51eSKate Stone          "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
932b9c1b51eSKate Stone          "10AllocationEb",
933b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
934b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
935b9c1b51eSKate Stone         {"rsdAllocationRead2D",
936b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
937b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
938b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
939b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
940b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver, nullptr},
941b9c1b51eSKate Stone         {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
942b9c1b51eSKate Stone                                  "ript7ContextEPNS0_10AllocationE",
943b9c1b51eSKate Stone          "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
944b9c1b51eSKate Stone          "10AllocationE",
945b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
946b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
9474640cde1SColin Riley };
9484640cde1SColin Riley 
949b9c1b51eSKate Stone const size_t RenderScriptRuntime::s_runtimeHookCount =
950b9c1b51eSKate Stone     sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
9514640cde1SColin Riley 
952b9c1b51eSKate Stone bool RenderScriptRuntime::HookCallback(void *baton,
953b9c1b51eSKate Stone                                        StoppointCallbackContext *ctx,
954b9c1b51eSKate Stone                                        lldb::user_id_t break_id,
955b9c1b51eSKate Stone                                        lldb::user_id_t break_loc_id) {
9564640cde1SColin Riley   RuntimeHook *hook_info = (RuntimeHook *)baton;
9574640cde1SColin Riley   ExecutionContext context(ctx->exe_ctx_ref);
9584640cde1SColin Riley 
959b3f7f69dSAidan Dodds   RenderScriptRuntime *lang_rt =
960b9c1b51eSKate Stone       (RenderScriptRuntime *)context.GetProcessPtr()->GetLanguageRuntime(
961b9c1b51eSKate Stone           eLanguageTypeExtRenderScript);
9624640cde1SColin Riley 
9634640cde1SColin Riley   lang_rt->HookCallback(hook_info, context);
9644640cde1SColin Riley 
9654640cde1SColin Riley   return false;
9664640cde1SColin Riley }
9674640cde1SColin Riley 
968b9c1b51eSKate Stone void RenderScriptRuntime::HookCallback(RuntimeHook *hook_info,
969b9c1b51eSKate Stone                                        ExecutionContext &context) {
9704640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
9714640cde1SColin Riley 
9724640cde1SColin Riley   if (log)
973b3f7f69dSAidan Dodds     log->Printf("%s - '%s'", __FUNCTION__, hook_info->defn->name);
9744640cde1SColin Riley 
975b9c1b51eSKate Stone   if (hook_info->defn->grabber) {
9764640cde1SColin Riley     (this->*(hook_info->defn->grabber))(hook_info, context);
9774640cde1SColin Riley   }
9784640cde1SColin Riley }
9794640cde1SColin Riley 
980b9c1b51eSKate Stone void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
981b9c1b51eSKate Stone     RuntimeHook *hook_info, ExecutionContext &context) {
982e09c44b6SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
983e09c44b6SAidan Dodds 
984b9c1b51eSKate Stone   enum {
985f4786785SAidan Dodds     eRsContext = 0,
986f4786785SAidan Dodds     eRsScript,
987f4786785SAidan Dodds     eRsSlot,
988f4786785SAidan Dodds     eRsAIns,
989f4786785SAidan Dodds     eRsInLen,
990f4786785SAidan Dodds     eRsAOut,
991f4786785SAidan Dodds     eRsUsr,
992f4786785SAidan Dodds     eRsUsrLen,
993f4786785SAidan Dodds     eRsSc,
994f4786785SAidan Dodds   };
995e09c44b6SAidan Dodds 
9961ee07253SSaleem Abdulrasool   std::array<ArgItem, 9> args{{
997f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Context       *rsc
998f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Script              *s
999f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // uint32_t             slot
1000f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Allocation   **aIns
1001f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               inLen
1002f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Allocation          *aout
1003f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const void          *usr
1004f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               usrLen
1005f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall  *sc
10061ee07253SSaleem Abdulrasool   }};
1007e09c44b6SAidan Dodds 
1008f4786785SAidan Dodds   bool success = GetArgs(context, &args[0], args.size());
1009b9c1b51eSKate Stone   if (!success) {
1010e09c44b6SAidan Dodds     if (log)
1011b9c1b51eSKate Stone       log->Printf("%s - Error while reading the function parameters",
1012b9c1b51eSKate Stone                   __FUNCTION__);
1013e09c44b6SAidan Dodds     return;
1014e09c44b6SAidan Dodds   }
1015e09c44b6SAidan Dodds 
1016e09c44b6SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1017e09c44b6SAidan Dodds   Error error;
1018e09c44b6SAidan Dodds   std::vector<uint64_t> allocs;
1019e09c44b6SAidan Dodds 
1020e09c44b6SAidan Dodds   // traverse allocation list
1021b9c1b51eSKate Stone   for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1022e09c44b6SAidan Dodds     // calculate offest to allocation pointer
1023f4786785SAidan Dodds     const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1024e09c44b6SAidan Dodds 
1025b9c1b51eSKate Stone     // Note: due to little endian layout, reading 32bits or 64bits into res64
1026b9c1b51eSKate Stone     // will
1027e09c44b6SAidan Dodds     //       give the correct results.
1028e09c44b6SAidan Dodds 
1029e09c44b6SAidan Dodds     uint64_t res64 = 0;
1030e09c44b6SAidan Dodds     size_t read = m_process->ReadMemory(addr, &res64, target_ptr_size, error);
1031b9c1b51eSKate Stone     if (read != target_ptr_size || !error.Success()) {
1032e09c44b6SAidan Dodds       if (log)
1033b9c1b51eSKate Stone         log->Printf(
1034b9c1b51eSKate Stone             "%s - Error while reading allocation list argument %" PRIu64,
1035b9c1b51eSKate Stone             __FUNCTION__, i);
1036b9c1b51eSKate Stone     } else {
1037e09c44b6SAidan Dodds       allocs.push_back(res64);
1038e09c44b6SAidan Dodds     }
1039e09c44b6SAidan Dodds   }
1040e09c44b6SAidan Dodds 
1041e09c44b6SAidan Dodds   // if there is an output allocation track it
1042b9c1b51eSKate Stone   if (uint64_t aOut = uint64_t(args[eRsAOut])) {
1043f4786785SAidan Dodds     allocs.push_back(aOut);
1044e09c44b6SAidan Dodds   }
1045e09c44b6SAidan Dodds 
1046e09c44b6SAidan Dodds   // for all allocations we have found
1047b9c1b51eSKate Stone   for (const uint64_t alloc_addr : allocs) {
10485d057637SLuke Drummond     AllocationDetails *alloc = LookUpAllocation(alloc_addr);
10495d057637SLuke Drummond     if (!alloc)
10505d057637SLuke Drummond       alloc = CreateAllocation(alloc_addr);
10515d057637SLuke Drummond 
1052b9c1b51eSKate Stone     if (alloc) {
1053e09c44b6SAidan Dodds       // save the allocation address
1054b9c1b51eSKate Stone       if (alloc->address.isValid()) {
1055e09c44b6SAidan Dodds         // check the allocation address we already have matches
1056e09c44b6SAidan Dodds         assert(*alloc->address.get() == alloc_addr);
1057b9c1b51eSKate Stone       } else {
1058e09c44b6SAidan Dodds         alloc->address = alloc_addr;
1059e09c44b6SAidan Dodds       }
1060e09c44b6SAidan Dodds 
1061e09c44b6SAidan Dodds       // save the context
1062b9c1b51eSKate Stone       if (log) {
1063b9c1b51eSKate Stone         if (alloc->context.isValid() &&
1064b9c1b51eSKate Stone             *alloc->context.get() != addr_t(args[eRsContext]))
1065b9c1b51eSKate Stone           log->Printf("%s - Allocation used by multiple contexts",
1066b9c1b51eSKate Stone                       __FUNCTION__);
1067e09c44b6SAidan Dodds       }
1068f4786785SAidan Dodds       alloc->context = addr_t(args[eRsContext]);
1069e09c44b6SAidan Dodds     }
1070e09c44b6SAidan Dodds   }
1071e09c44b6SAidan Dodds 
1072e09c44b6SAidan Dodds   // make sure we track this script object
1073b9c1b51eSKate Stone   if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1074b9c1b51eSKate Stone           LookUpScript(addr_t(args[eRsScript]), true)) {
1075b9c1b51eSKate Stone     if (log) {
1076b9c1b51eSKate Stone       if (script->context.isValid() &&
1077b9c1b51eSKate Stone           *script->context.get() != addr_t(args[eRsContext]))
1078b3f7f69dSAidan Dodds         log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1079e09c44b6SAidan Dodds     }
1080f4786785SAidan Dodds     script->context = addr_t(args[eRsContext]);
1081e09c44b6SAidan Dodds   }
1082e09c44b6SAidan Dodds }
1083e09c44b6SAidan Dodds 
1084b9c1b51eSKate Stone void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook_info,
1085b9c1b51eSKate Stone                                               ExecutionContext &context) {
10864640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
10874640cde1SColin Riley 
1088b9c1b51eSKate Stone   enum {
1089f4786785SAidan Dodds     eRsContext,
1090f4786785SAidan Dodds     eRsScript,
1091f4786785SAidan Dodds     eRsId,
1092f4786785SAidan Dodds     eRsData,
1093f4786785SAidan Dodds     eRsLength,
1094f4786785SAidan Dodds   };
10954640cde1SColin Riley 
10961ee07253SSaleem Abdulrasool   std::array<ArgItem, 5> args{{
1097f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1098f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsScript
1099f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsId
1100f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsData
1101f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsLength
11021ee07253SSaleem Abdulrasool   }};
11034640cde1SColin Riley 
1104f4786785SAidan Dodds   bool success = GetArgs(context, &args[0], args.size());
1105b9c1b51eSKate Stone   if (!success) {
110682780287SAidan Dodds     if (log)
1107b3f7f69dSAidan Dodds       log->Printf("%s - error reading the function parameters.", __FUNCTION__);
110882780287SAidan Dodds     return;
110982780287SAidan Dodds   }
11104640cde1SColin Riley 
1111b9c1b51eSKate Stone   if (log) {
1112b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1113b9c1b51eSKate Stone                 ":%" PRIu64 "bytes.",
1114b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1115b9c1b51eSKate Stone                 uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1116f4786785SAidan Dodds                 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
11174640cde1SColin Riley 
1118f4786785SAidan Dodds     addr_t script_addr = addr_t(args[eRsScript]);
1119b9c1b51eSKate Stone     if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
11204640cde1SColin Riley       auto rsm = m_scriptMappings[script_addr];
1121b9c1b51eSKate Stone       if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1122f4786785SAidan Dodds         auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1123b9c1b51eSKate Stone         log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__,
1124b9c1b51eSKate Stone                     rsg.m_name.AsCString(),
1125f4786785SAidan Dodds                     rsm->m_module->GetFileSpec().GetFilename().AsCString());
11264640cde1SColin Riley       }
11274640cde1SColin Riley     }
11284640cde1SColin Riley   }
11294640cde1SColin Riley }
11304640cde1SColin Riley 
1131b9c1b51eSKate Stone void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook_info,
1132b9c1b51eSKate Stone                                                 ExecutionContext &context) {
11334640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11344640cde1SColin Riley 
1135b9c1b51eSKate Stone   enum { eRsContext, eRsAlloc, eRsForceZero };
11364640cde1SColin Riley 
11371ee07253SSaleem Abdulrasool   std::array<ArgItem, 3> args{{
1138f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1139f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1140f4786785SAidan Dodds       ArgItem{ArgItem::eBool, 0},    // eRsForceZero
11411ee07253SSaleem Abdulrasool   }};
11424640cde1SColin Riley 
1143f4786785SAidan Dodds   bool success = GetArgs(context, &args[0], args.size());
114482780287SAidan Dodds   if (!success) // error case
114582780287SAidan Dodds   {
114682780287SAidan Dodds     if (log)
1147b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters",
1148b9c1b51eSKate Stone                   __FUNCTION__);
114982780287SAidan Dodds     return; // abort
115082780287SAidan Dodds   }
11514640cde1SColin Riley 
11524640cde1SColin Riley   if (log)
1153b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1154b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1155f4786785SAidan Dodds                 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
115678f339d1SEwan Crawford 
11575d057637SLuke Drummond   AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
115878f339d1SEwan Crawford   if (alloc)
1159f4786785SAidan Dodds     alloc->context = uint64_t(args[eRsContext]);
11604640cde1SColin Riley }
11614640cde1SColin Riley 
1162b9c1b51eSKate Stone void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook_info,
1163b9c1b51eSKate Stone                                                    ExecutionContext &context) {
1164e69df382SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1165e69df382SEwan Crawford 
1166b9c1b51eSKate Stone   enum {
1167f4786785SAidan Dodds     eRsContext,
1168f4786785SAidan Dodds     eRsAlloc,
1169f4786785SAidan Dodds   };
1170e69df382SEwan Crawford 
11711ee07253SSaleem Abdulrasool   std::array<ArgItem, 2> args{{
1172f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1173f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
11741ee07253SSaleem Abdulrasool   }};
1175f4786785SAidan Dodds 
1176f4786785SAidan Dodds   bool success = GetArgs(context, &args[0], args.size());
1177b9c1b51eSKate Stone   if (!success) {
1178e69df382SEwan Crawford     if (log)
1179b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1180b9c1b51eSKate Stone                   __FUNCTION__);
1181b3f7f69dSAidan Dodds     return;
1182e69df382SEwan Crawford   }
1183e69df382SEwan Crawford 
1184e69df382SEwan Crawford   if (log)
1185b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1186b9c1b51eSKate Stone                 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1187e69df382SEwan Crawford 
1188b9c1b51eSKate Stone   for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1189e69df382SEwan Crawford     auto &allocation_ap = *iter; // get the unique pointer
1190b9c1b51eSKate Stone     if (allocation_ap->address.isValid() &&
1191b9c1b51eSKate Stone         *allocation_ap->address.get() == addr_t(args[eRsAlloc])) {
1192e69df382SEwan Crawford       m_allocations.erase(iter);
1193e69df382SEwan Crawford       if (log)
1194b3f7f69dSAidan Dodds         log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1195e69df382SEwan Crawford       return;
1196e69df382SEwan Crawford     }
1197e69df382SEwan Crawford   }
1198e69df382SEwan Crawford 
1199e69df382SEwan Crawford   if (log)
1200b3f7f69dSAidan Dodds     log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1201e69df382SEwan Crawford }
1202e69df382SEwan Crawford 
1203b9c1b51eSKate Stone void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook_info,
1204b9c1b51eSKate Stone                                             ExecutionContext &context) {
12054640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
12064640cde1SColin Riley 
12074640cde1SColin Riley   Error error;
12084640cde1SColin Riley   Process *process = context.GetProcessPtr();
12094640cde1SColin Riley 
1210b9c1b51eSKate Stone   enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
12114640cde1SColin Riley 
1212b9c1b51eSKate Stone   std::array<ArgItem, 4> args{
1213b9c1b51eSKate Stone       {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
12141ee07253SSaleem Abdulrasool        ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
1215f4786785SAidan Dodds   bool success = GetArgs(context, &args[0], args.size());
1216b9c1b51eSKate Stone   if (!success) {
121782780287SAidan Dodds     if (log)
1218b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1219b9c1b51eSKate Stone                   __FUNCTION__);
122082780287SAidan Dodds     return;
122182780287SAidan Dodds   }
122282780287SAidan Dodds 
1223f4786785SAidan Dodds   std::string resname;
1224f4786785SAidan Dodds   process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), resname, error);
1225b9c1b51eSKate Stone   if (error.Fail()) {
12264640cde1SColin Riley     if (log)
1227b9c1b51eSKate Stone       log->Printf("%s - error reading resname: %s.", __FUNCTION__,
1228b9c1b51eSKate Stone                   error.AsCString());
12294640cde1SColin Riley   }
12304640cde1SColin Riley 
1231f4786785SAidan Dodds   std::string cachedir;
1232b9c1b51eSKate Stone   process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cachedir,
1233b9c1b51eSKate Stone                                  error);
1234b9c1b51eSKate Stone   if (error.Fail()) {
12354640cde1SColin Riley     if (log)
1236b9c1b51eSKate Stone       log->Printf("%s - error reading cachedir: %s.", __FUNCTION__,
1237b9c1b51eSKate Stone                   error.AsCString());
12384640cde1SColin Riley   }
12394640cde1SColin Riley 
12404640cde1SColin Riley   if (log)
1241b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1242b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1243f4786785SAidan Dodds                 uint64_t(args[eRsScript]), resname.c_str(), cachedir.c_str());
12444640cde1SColin Riley 
1245b9c1b51eSKate Stone   if (resname.size() > 0) {
12464640cde1SColin Riley     StreamString strm;
12474640cde1SColin Riley     strm.Printf("librs.%s.so", resname.c_str());
12484640cde1SColin Riley 
1249f4786785SAidan Dodds     ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1250b9c1b51eSKate Stone     if (script) {
125178f339d1SEwan Crawford       script->type = ScriptDetails::eScriptC;
125278f339d1SEwan Crawford       script->cacheDir = cachedir;
125378f339d1SEwan Crawford       script->resName = resname;
125478f339d1SEwan Crawford       script->scriptDyLib = strm.GetData();
1255f4786785SAidan Dodds       script->context = addr_t(args[eRsContext]);
125678f339d1SEwan Crawford     }
12574640cde1SColin Riley 
12584640cde1SColin Riley     if (log)
1259b9c1b51eSKate Stone       log->Printf("%s - '%s' tagged with context 0x%" PRIx64
1260b9c1b51eSKate Stone                   " and script 0x%" PRIx64 ".",
1261b9c1b51eSKate Stone                   __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1262b9c1b51eSKate Stone                   uint64_t(args[eRsScript]));
1263b9c1b51eSKate Stone   } else if (log) {
1264b3f7f69dSAidan Dodds     log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
12654640cde1SColin Riley   }
12664640cde1SColin Riley }
12674640cde1SColin Riley 
1268b9c1b51eSKate Stone void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1269b9c1b51eSKate Stone                                            ModuleKind kind) {
12704640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
12714640cde1SColin Riley 
1272b9c1b51eSKate Stone   if (!module) {
12734640cde1SColin Riley     return;
12744640cde1SColin Riley   }
12754640cde1SColin Riley 
127682780287SAidan Dodds   Target &target = GetProcess()->GetTarget();
127782780287SAidan Dodds   llvm::Triple::ArchType targetArchType = target.GetArchitecture().GetMachine();
127882780287SAidan Dodds 
1279b3f7f69dSAidan Dodds   if (targetArchType != llvm::Triple::ArchType::x86 &&
1280b3f7f69dSAidan Dodds       targetArchType != llvm::Triple::ArchType::arm &&
1281b3f7f69dSAidan Dodds       targetArchType != llvm::Triple::ArchType::aarch64 &&
1282b3f7f69dSAidan Dodds       targetArchType != llvm::Triple::ArchType::mipsel &&
1283b3f7f69dSAidan Dodds       targetArchType != llvm::Triple::ArchType::mips64el &&
1284b9c1b51eSKate Stone       targetArchType != llvm::Triple::ArchType::x86_64) {
12854640cde1SColin Riley     if (log)
1286b3f7f69dSAidan Dodds       log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
12874640cde1SColin Riley     return;
12884640cde1SColin Riley   }
12894640cde1SColin Riley 
129082780287SAidan Dodds   uint32_t archByteSize = target.GetArchitecture().GetAddressByteSize();
12914640cde1SColin Riley 
1292b9c1b51eSKate Stone   for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
12934640cde1SColin Riley     const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1294b9c1b51eSKate Stone     if (hook_defn->kind != kind) {
12954640cde1SColin Riley       continue;
12964640cde1SColin Riley     }
12974640cde1SColin Riley 
1298b9c1b51eSKate Stone     const char *symbol_name = (archByteSize == 4) ? hook_defn->symbol_name_m32
1299b9c1b51eSKate Stone                                                   : hook_defn->symbol_name_m64;
130082780287SAidan Dodds 
1301b9c1b51eSKate Stone     const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1302b9c1b51eSKate Stone         ConstString(symbol_name), eSymbolTypeCode);
1303b9c1b51eSKate Stone     if (!sym) {
1304b9c1b51eSKate Stone       if (log) {
1305b3f7f69dSAidan Dodds         log->Printf("%s - symbol '%s' related to the function %s not found",
1306b3f7f69dSAidan Dodds                     __FUNCTION__, symbol_name, hook_defn->name);
130782780287SAidan Dodds       }
130882780287SAidan Dodds       continue;
130982780287SAidan Dodds     }
13104640cde1SColin Riley 
1311358cf1eaSGreg Clayton     addr_t addr = sym->GetLoadAddress(&target);
1312b9c1b51eSKate Stone     if (addr == LLDB_INVALID_ADDRESS) {
13134640cde1SColin Riley       if (log)
1314b9c1b51eSKate Stone         log->Printf("%s - unable to resolve the address of hook function '%s' "
1315b9c1b51eSKate Stone                     "with symbol '%s'.",
1316b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, symbol_name);
13174640cde1SColin Riley       continue;
1318b9c1b51eSKate Stone     } else {
131982780287SAidan Dodds       if (log)
1320b3f7f69dSAidan Dodds         log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1321b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, addr);
132282780287SAidan Dodds     }
13234640cde1SColin Riley 
13244640cde1SColin Riley     RuntimeHookSP hook(new RuntimeHook());
13254640cde1SColin Riley     hook->address = addr;
13264640cde1SColin Riley     hook->defn = hook_defn;
13274640cde1SColin Riley     hook->bp_sp = target.CreateBreakpoint(addr, true, false);
13284640cde1SColin Riley     hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
13294640cde1SColin Riley     m_runtimeHooks[addr] = hook;
1330b9c1b51eSKate Stone     if (log) {
1331b9c1b51eSKate Stone       log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64
1332b9c1b51eSKate Stone                   " at 0x%" PRIx64 ".",
1333b9c1b51eSKate Stone                   __FUNCTION__, hook_defn->name,
1334b9c1b51eSKate Stone                   module->GetFileSpec().GetFilename().AsCString(),
1335b3f7f69dSAidan Dodds                   (uint64_t)hook_defn->version, (uint64_t)addr);
13364640cde1SColin Riley     }
13374640cde1SColin Riley   }
13384640cde1SColin Riley }
13394640cde1SColin Riley 
1340b9c1b51eSKate Stone void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
13414640cde1SColin Riley   if (!rsmodule_sp)
13424640cde1SColin Riley     return;
13434640cde1SColin Riley 
13444640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
13454640cde1SColin Riley 
13464640cde1SColin Riley   const ModuleSP module = rsmodule_sp->m_module;
13474640cde1SColin Riley   const FileSpec &file = module->GetPlatformFileSpec();
13484640cde1SColin Riley 
134978f339d1SEwan Crawford   // Iterate over all of the scripts that we currently know of.
135078f339d1SEwan Crawford   // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
1351b9c1b51eSKate Stone   for (const auto &rs_script : m_scripts) {
135278f339d1SEwan Crawford     // Extract the expected .so file path for this script.
135378f339d1SEwan Crawford     std::string dylib;
135478f339d1SEwan Crawford     if (!rs_script->scriptDyLib.get(dylib))
135578f339d1SEwan Crawford       continue;
135678f339d1SEwan Crawford 
135778f339d1SEwan Crawford     // Only proceed if the module that has loaded corresponds to this script.
135878f339d1SEwan Crawford     if (file.GetFilename() != ConstString(dylib.c_str()))
135978f339d1SEwan Crawford       continue;
136078f339d1SEwan Crawford 
136178f339d1SEwan Crawford     // Obtain the script address which we use as a key.
136278f339d1SEwan Crawford     lldb::addr_t script;
136378f339d1SEwan Crawford     if (!rs_script->script.get(script))
136478f339d1SEwan Crawford       continue;
136578f339d1SEwan Crawford 
136678f339d1SEwan Crawford     // If we have a script mapping for the current script.
1367b9c1b51eSKate Stone     if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
136878f339d1SEwan Crawford       // if the module we have stored is different to the one we just received.
1369b9c1b51eSKate Stone       if (m_scriptMappings[script] != rsmodule_sp) {
13704640cde1SColin Riley         if (log)
1371b9c1b51eSKate Stone           log->Printf(
1372b9c1b51eSKate Stone               "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1373b9c1b51eSKate Stone               __FUNCTION__, (uint64_t)script,
1374b9c1b51eSKate Stone               rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
13754640cde1SColin Riley       }
13764640cde1SColin Riley     }
137778f339d1SEwan Crawford     // We don't have a script mapping for the current script.
1378b9c1b51eSKate Stone     else {
137978f339d1SEwan Crawford       // Obtain the script resource name.
138078f339d1SEwan Crawford       std::string resName;
138178f339d1SEwan Crawford       if (rs_script->resName.get(resName))
138278f339d1SEwan Crawford         // Set the modules resource name.
138378f339d1SEwan Crawford         rsmodule_sp->m_resname = resName;
138478f339d1SEwan Crawford       // Add Script/Module pair to map.
138578f339d1SEwan Crawford       m_scriptMappings[script] = rsmodule_sp;
13864640cde1SColin Riley       if (log)
1387b9c1b51eSKate Stone         log->Printf(
1388b9c1b51eSKate Stone             "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1389b9c1b51eSKate Stone             __FUNCTION__, (uint64_t)script,
1390b9c1b51eSKate Stone             rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
13914640cde1SColin Riley     }
13924640cde1SColin Riley   }
13934640cde1SColin Riley }
13944640cde1SColin Riley 
1395b9c1b51eSKate Stone // Uses the Target API to evaluate the expression passed as a parameter to the
1396b9c1b51eSKate Stone // function
1397b9c1b51eSKate Stone // The result of that expression is returned an unsigned 64 bit int, via the
1398b9c1b51eSKate Stone // result* parameter.
139915f2bd95SEwan Crawford // Function returns true on success, and false on failure
1400b9c1b51eSKate Stone bool RenderScriptRuntime::EvalRSExpression(const char *expression,
1401b9c1b51eSKate Stone                                            StackFrame *frame_ptr,
1402b9c1b51eSKate Stone                                            uint64_t *result) {
140315f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
140415f2bd95SEwan Crawford   if (log)
1405b3f7f69dSAidan Dodds     log->Printf("%s(%s)", __FUNCTION__, expression);
140615f2bd95SEwan Crawford 
140715f2bd95SEwan Crawford   ValueObjectSP expr_result;
14088433fdbeSAidan Dodds   EvaluateExpressionOptions options;
14098433fdbeSAidan Dodds   options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
141015f2bd95SEwan Crawford   // Perform the actual expression evaluation
1411b9c1b51eSKate Stone   GetProcess()->GetTarget().EvaluateExpression(expression, frame_ptr,
1412b9c1b51eSKate Stone                                                expr_result, options);
141315f2bd95SEwan Crawford 
1414b9c1b51eSKate Stone   if (!expr_result) {
141515f2bd95SEwan Crawford     if (log)
1416b3f7f69dSAidan Dodds       log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
141715f2bd95SEwan Crawford     return false;
141815f2bd95SEwan Crawford   }
141915f2bd95SEwan Crawford 
142015f2bd95SEwan Crawford   // The result of the expression is invalid
1421b9c1b51eSKate Stone   if (!expr_result->GetError().Success()) {
142215f2bd95SEwan Crawford     Error err = expr_result->GetError();
1423b9c1b51eSKate Stone     if (err.GetError() == UserExpression::kNoResult) // Expression returned
1424b9c1b51eSKate Stone                                                      // void, so this is
1425b9c1b51eSKate Stone                                                      // actually a success
142615f2bd95SEwan Crawford     {
142715f2bd95SEwan Crawford       if (log)
1428b3f7f69dSAidan Dodds         log->Printf("%s - expression returned void.", __FUNCTION__);
142915f2bd95SEwan Crawford 
143015f2bd95SEwan Crawford       result = nullptr;
143115f2bd95SEwan Crawford       return true;
143215f2bd95SEwan Crawford     }
143315f2bd95SEwan Crawford 
143415f2bd95SEwan Crawford     if (log)
1435b3f7f69dSAidan Dodds       log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1436b3f7f69dSAidan Dodds                   err.AsCString());
143715f2bd95SEwan Crawford     return false;
143815f2bd95SEwan Crawford   }
143915f2bd95SEwan Crawford 
144015f2bd95SEwan Crawford   bool success = false;
1441b9c1b51eSKate Stone   *result = expr_result->GetValueAsUnsigned(
1442b9c1b51eSKate Stone       0, &success); // We only read the result as an uint32_t.
144315f2bd95SEwan Crawford 
1444b9c1b51eSKate Stone   if (!success) {
144515f2bd95SEwan Crawford     if (log)
1446b9c1b51eSKate Stone       log->Printf("%s - couldn't convert expression result to uint32_t",
1447b9c1b51eSKate Stone                   __FUNCTION__);
144815f2bd95SEwan Crawford     return false;
144915f2bd95SEwan Crawford   }
145015f2bd95SEwan Crawford 
145115f2bd95SEwan Crawford   return true;
145215f2bd95SEwan Crawford }
145315f2bd95SEwan Crawford 
1454b9c1b51eSKate Stone namespace {
1455836d9651SEwan Crawford // Used to index expression format strings
1456b9c1b51eSKate Stone enum ExpressionStrings {
1457836d9651SEwan Crawford   eExprGetOffsetPtr = 0,
1458836d9651SEwan Crawford   eExprAllocGetType,
1459836d9651SEwan Crawford   eExprTypeDimX,
1460836d9651SEwan Crawford   eExprTypeDimY,
1461836d9651SEwan Crawford   eExprTypeDimZ,
1462836d9651SEwan Crawford   eExprTypeElemPtr,
1463836d9651SEwan Crawford   eExprElementType,
1464836d9651SEwan Crawford   eExprElementKind,
1465836d9651SEwan Crawford   eExprElementVec,
1466836d9651SEwan Crawford   eExprElementFieldCount,
1467836d9651SEwan Crawford   eExprSubelementsId,
1468836d9651SEwan Crawford   eExprSubelementsName,
1469ea0636b5SEwan Crawford   eExprSubelementsArrSize,
1470ea0636b5SEwan Crawford 
1471ea0636b5SEwan Crawford   _eExprLast // keep at the end, implicit size of the array runtimeExpressions
1472836d9651SEwan Crawford };
147315f2bd95SEwan Crawford 
1474ea0636b5SEwan Crawford // max length of an expanded expression
1475ea0636b5SEwan Crawford const int jit_max_expr_size = 512;
1476ea0636b5SEwan Crawford 
1477ea0636b5SEwan Crawford // Retrieve the string to JIT for the given expression
1478b9c1b51eSKate Stone const char *JITTemplate(ExpressionStrings e) {
1479ea0636b5SEwan Crawford   // Format strings containing the expressions we may need to evaluate.
1480b9c1b51eSKate Stone   static std::array<const char *, _eExprLast> runtimeExpressions = {
1481b9c1b51eSKate Stone       {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1482b9c1b51eSKate Stone        "(int*)_"
1483b9c1b51eSKate Stone        "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1484b9c1b51eSKate Stone        "CubemapFace"
1485577570b4SAidan Dodds        "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)",
148615f2bd95SEwan Crawford 
148715f2bd95SEwan Crawford        // Type* rsaAllocationGetType(Context*, Allocation*)
1488577570b4SAidan Dodds        "(void*)rsaAllocationGetType(0x%" PRIx64 ", 0x%" PRIx64 ")",
148915f2bd95SEwan Crawford 
149015f2bd95SEwan Crawford        // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
1491b9c1b51eSKate Stone        // Pack the data in the following way mHal.state.dimX; mHal.state.dimY;
1492b9c1b51eSKate Stone        // mHal.state.dimZ;
149315f2bd95SEwan Crawford        // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
1494b9c1b51eSKate Stone        // Need to specify 32 or 64 bit for uint_t since this differs between
1495b9c1b51eSKate Stone        // devices
1496b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1497b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[0]", // X dim
1498b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1499b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[1]", // Y dim
1500b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1501b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[2]", // Z dim
1502b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1503b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[5]", // Element ptr
150415f2bd95SEwan Crawford 
150515f2bd95SEwan Crawford        // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1506b9c1b51eSKate Stone        // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1507b9c1b51eSKate Stone        // elemData
1508b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1509b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[0]", // Type
1510b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1511b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[1]", // Kind
1512b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1513b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[3]", // Vector Size
1514b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1515b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[4]", // Field Count
15168b244e21SEwan Crawford 
1517b9c1b51eSKate Stone        // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
1518b9c1b51eSKate Stone        // *ids, const char **names,
15198b244e21SEwan Crawford        // size_t *arraySizes, uint32_t dataSize)
1520b9c1b51eSKate Stone        // Needed for Allocations of structs to gather details about
1521b9c1b51eSKate Stone        // fields/Subelements
1522577570b4SAidan Dodds        // Element* of field
1523b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1524b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1525b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1526b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]",
15278b244e21SEwan Crawford 
1528577570b4SAidan Dodds        // Name of field
1529b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1530b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1531b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1532b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]",
15338b244e21SEwan Crawford 
1534577570b4SAidan Dodds        // Array size of field
1535b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1536b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1537b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1538b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}};
1539ea0636b5SEwan Crawford 
1540ea0636b5SEwan Crawford   return runtimeExpressions[e];
1541ea0636b5SEwan Crawford }
1542ea0636b5SEwan Crawford } // end of the anonymous namespace
1543ea0636b5SEwan Crawford 
154415f2bd95SEwan Crawford // JITs the RS runtime for the internal data pointer of an allocation.
154515f2bd95SEwan Crawford // Is passed x,y,z coordinates for the pointer to a specific element.
154615f2bd95SEwan Crawford // Then sets the data_ptr member in Allocation with the result.
154715f2bd95SEwan Crawford // Returns true on success, false otherwise
1548b9c1b51eSKate Stone bool RenderScriptRuntime::JITDataPointer(AllocationDetails *allocation,
1549b9c1b51eSKate Stone                                          StackFrame *frame_ptr, uint32_t x,
1550b9c1b51eSKate Stone                                          uint32_t y, uint32_t z) {
155115f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
155215f2bd95SEwan Crawford 
1553b9c1b51eSKate Stone   if (!allocation->address.isValid()) {
155415f2bd95SEwan Crawford     if (log)
1555b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
155615f2bd95SEwan Crawford     return false;
155715f2bd95SEwan Crawford   }
155815f2bd95SEwan Crawford 
1559ea0636b5SEwan Crawford   const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1560ea0636b5SEwan Crawford   char buffer[jit_max_expr_size];
156115f2bd95SEwan Crawford 
1562b9c1b51eSKate Stone   int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr,
1563b9c1b51eSKate Stone                                *allocation->address.get(), x, y, z);
1564b9c1b51eSKate Stone   if (chars_written < 0) {
156515f2bd95SEwan Crawford     if (log)
1566b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
156715f2bd95SEwan Crawford     return false;
1568b9c1b51eSKate Stone   } else if (chars_written >= jit_max_expr_size) {
156915f2bd95SEwan Crawford     if (log)
1570b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
157115f2bd95SEwan Crawford     return false;
157215f2bd95SEwan Crawford   }
157315f2bd95SEwan Crawford 
157415f2bd95SEwan Crawford   uint64_t result = 0;
157515f2bd95SEwan Crawford   if (!EvalRSExpression(buffer, frame_ptr, &result))
157615f2bd95SEwan Crawford     return false;
157715f2bd95SEwan Crawford 
157815f2bd95SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
157915f2bd95SEwan Crawford   allocation->data_ptr = mem_ptr;
158015f2bd95SEwan Crawford 
158115f2bd95SEwan Crawford   return true;
158215f2bd95SEwan Crawford }
158315f2bd95SEwan Crawford 
158415f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
158515f2bd95SEwan Crawford // Then sets the type_ptr member in Allocation with the result.
158615f2bd95SEwan Crawford // Returns true on success, false otherwise
1587b9c1b51eSKate Stone bool RenderScriptRuntime::JITTypePointer(AllocationDetails *allocation,
1588b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
158915f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
159015f2bd95SEwan Crawford 
1591b9c1b51eSKate Stone   if (!allocation->address.isValid() || !allocation->context.isValid()) {
159215f2bd95SEwan Crawford     if (log)
1593b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
159415f2bd95SEwan Crawford     return false;
159515f2bd95SEwan Crawford   }
159615f2bd95SEwan Crawford 
1597ea0636b5SEwan Crawford   const char *expr_cstr = JITTemplate(eExprAllocGetType);
1598ea0636b5SEwan Crawford   char buffer[jit_max_expr_size];
159915f2bd95SEwan Crawford 
1600ea0636b5SEwan Crawford   int chars_written =
1601b9c1b51eSKate Stone       snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->context.get(),
1602b9c1b51eSKate Stone                *allocation->address.get());
1603b9c1b51eSKate Stone   if (chars_written < 0) {
160415f2bd95SEwan Crawford     if (log)
1605b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
160615f2bd95SEwan Crawford     return false;
1607b9c1b51eSKate Stone   } else if (chars_written >= jit_max_expr_size) {
160815f2bd95SEwan Crawford     if (log)
1609b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
161015f2bd95SEwan Crawford     return false;
161115f2bd95SEwan Crawford   }
161215f2bd95SEwan Crawford 
161315f2bd95SEwan Crawford   uint64_t result = 0;
161415f2bd95SEwan Crawford   if (!EvalRSExpression(buffer, frame_ptr, &result))
161515f2bd95SEwan Crawford     return false;
161615f2bd95SEwan Crawford 
161715f2bd95SEwan Crawford   addr_t type_ptr = static_cast<lldb::addr_t>(result);
161815f2bd95SEwan Crawford   allocation->type_ptr = type_ptr;
161915f2bd95SEwan Crawford 
162015f2bd95SEwan Crawford   return true;
162115f2bd95SEwan Crawford }
162215f2bd95SEwan Crawford 
1623b9c1b51eSKate Stone // JITs the RS runtime for information about the dimensions and type of an
1624b9c1b51eSKate Stone // allocation
162515f2bd95SEwan Crawford // Then sets dimension and element_ptr members in Allocation with the result.
162615f2bd95SEwan Crawford // Returns true on success, false otherwise
1627b9c1b51eSKate Stone bool RenderScriptRuntime::JITTypePacked(AllocationDetails *allocation,
1628b9c1b51eSKate Stone                                         StackFrame *frame_ptr) {
162915f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
163015f2bd95SEwan Crawford 
1631b9c1b51eSKate Stone   if (!allocation->type_ptr.isValid() || !allocation->context.isValid()) {
163215f2bd95SEwan Crawford     if (log)
1633b3f7f69dSAidan Dodds       log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
163415f2bd95SEwan Crawford     return false;
163515f2bd95SEwan Crawford   }
163615f2bd95SEwan Crawford 
163715f2bd95SEwan Crawford   // Expression is different depending on if device is 32 or 64 bit
1638b9c1b51eSKate Stone   uint32_t archByteSize =
1639b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
1640b3f7f69dSAidan Dodds   const uint32_t bits = archByteSize == 4 ? 32 : 64;
164115f2bd95SEwan Crawford 
164215f2bd95SEwan Crawford   // We want 4 elements from packed data
1643b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
1644b9c1b51eSKate Stone   assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) &&
1645b9c1b51eSKate Stone          "Invalid number of expressions");
164615f2bd95SEwan Crawford 
1647ea0636b5SEwan Crawford   char buffer[num_exprs][jit_max_expr_size];
164815f2bd95SEwan Crawford   uint64_t results[num_exprs];
164915f2bd95SEwan Crawford 
1650b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; ++i) {
1651ea0636b5SEwan Crawford     const char *expr_cstr = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
1652b9c1b51eSKate Stone     int chars_written =
1653b9c1b51eSKate Stone         snprintf(buffer[i], jit_max_expr_size, expr_cstr, bits,
1654b9c1b51eSKate Stone                  *allocation->context.get(), *allocation->type_ptr.get());
1655b9c1b51eSKate Stone     if (chars_written < 0) {
165615f2bd95SEwan Crawford       if (log)
1657b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
165815f2bd95SEwan Crawford       return false;
1659b9c1b51eSKate Stone     } else if (chars_written >= jit_max_expr_size) {
166015f2bd95SEwan Crawford       if (log)
1661b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
166215f2bd95SEwan Crawford       return false;
166315f2bd95SEwan Crawford     }
166415f2bd95SEwan Crawford 
166515f2bd95SEwan Crawford     // Perform expression evaluation
166615f2bd95SEwan Crawford     if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
166715f2bd95SEwan Crawford       return false;
166815f2bd95SEwan Crawford   }
166915f2bd95SEwan Crawford 
167015f2bd95SEwan Crawford   // Assign results to allocation members
167115f2bd95SEwan Crawford   AllocationDetails::Dimension dims;
167215f2bd95SEwan Crawford   dims.dim_1 = static_cast<uint32_t>(results[0]);
167315f2bd95SEwan Crawford   dims.dim_2 = static_cast<uint32_t>(results[1]);
167415f2bd95SEwan Crawford   dims.dim_3 = static_cast<uint32_t>(results[2]);
167515f2bd95SEwan Crawford   allocation->dimension = dims;
167615f2bd95SEwan Crawford 
167715f2bd95SEwan Crawford   addr_t elem_ptr = static_cast<lldb::addr_t>(results[3]);
16788b244e21SEwan Crawford   allocation->element.element_ptr = elem_ptr;
167915f2bd95SEwan Crawford 
168015f2bd95SEwan Crawford   if (log)
1681b9c1b51eSKate Stone     log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
1682b9c1b51eSKate Stone                 ") Element*: 0x%" PRIx64 ".",
1683b9c1b51eSKate Stone                 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, elem_ptr);
168415f2bd95SEwan Crawford 
168515f2bd95SEwan Crawford   return true;
168615f2bd95SEwan Crawford }
168715f2bd95SEwan Crawford 
168815f2bd95SEwan Crawford // JITs the RS runtime for information about the Element of an allocation
1689b9c1b51eSKate Stone // Then sets type, type_vec_size, field_count and type_kind members in Element
1690b9c1b51eSKate Stone // with the result.
169115f2bd95SEwan Crawford // Returns true on success, false otherwise
1692b9c1b51eSKate Stone bool RenderScriptRuntime::JITElementPacked(Element &elem,
1693b9c1b51eSKate Stone                                            const lldb::addr_t context,
1694b9c1b51eSKate Stone                                            StackFrame *frame_ptr) {
169515f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
169615f2bd95SEwan Crawford 
1697b9c1b51eSKate Stone   if (!elem.element_ptr.isValid()) {
169815f2bd95SEwan Crawford     if (log)
1699b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
170015f2bd95SEwan Crawford     return false;
170115f2bd95SEwan Crawford   }
170215f2bd95SEwan Crawford 
17038b244e21SEwan Crawford   // We want 4 elements from packed data
1704b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
1705b9c1b51eSKate Stone   assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) &&
1706b9c1b51eSKate Stone          "Invalid number of expressions");
170715f2bd95SEwan Crawford 
1708ea0636b5SEwan Crawford   char buffer[num_exprs][jit_max_expr_size];
170915f2bd95SEwan Crawford   uint64_t results[num_exprs];
171015f2bd95SEwan Crawford 
1711b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; i++) {
1712b9c1b51eSKate Stone     const char *expr_cstr =
1713b9c1b51eSKate Stone         JITTemplate(ExpressionStrings(eExprElementType + i));
1714b9c1b51eSKate Stone     int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr,
1715b9c1b51eSKate Stone                                  context, *elem.element_ptr.get());
1716b9c1b51eSKate Stone     if (chars_written < 0) {
171715f2bd95SEwan Crawford       if (log)
1718b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
171915f2bd95SEwan Crawford       return false;
1720b9c1b51eSKate Stone     } else if (chars_written >= jit_max_expr_size) {
172115f2bd95SEwan Crawford       if (log)
1722b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
172315f2bd95SEwan Crawford       return false;
172415f2bd95SEwan Crawford     }
172515f2bd95SEwan Crawford 
172615f2bd95SEwan Crawford     // Perform expression evaluation
172715f2bd95SEwan Crawford     if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
172815f2bd95SEwan Crawford       return false;
172915f2bd95SEwan Crawford   }
173015f2bd95SEwan Crawford 
173115f2bd95SEwan Crawford   // Assign results to allocation members
17328b244e21SEwan Crawford   elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
1733b9c1b51eSKate Stone   elem.type_kind =
1734b9c1b51eSKate Stone       static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
17358b244e21SEwan Crawford   elem.type_vec_size = static_cast<uint32_t>(results[2]);
17368b244e21SEwan Crawford   elem.field_count = static_cast<uint32_t>(results[3]);
173715f2bd95SEwan Crawford 
173815f2bd95SEwan Crawford   if (log)
1739b9c1b51eSKate Stone     log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32
1740b9c1b51eSKate Stone                 ", vector size %" PRIu32 ", field count %" PRIu32,
1741b9c1b51eSKate Stone                 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
1742b9c1b51eSKate Stone                 *elem.type_vec_size.get(), *elem.field_count.get());
17438b244e21SEwan Crawford 
1744b9c1b51eSKate Stone   // If this Element has subelements then JIT rsaElementGetSubElements() for
1745b9c1b51eSKate Stone   // details about its fields
17468b244e21SEwan Crawford   if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
17478b244e21SEwan Crawford     return false;
17488b244e21SEwan Crawford 
17498b244e21SEwan Crawford   return true;
17508b244e21SEwan Crawford }
17518b244e21SEwan Crawford 
1752b9c1b51eSKate Stone // JITs the RS runtime for information about the subelements/fields of a struct
1753b9c1b51eSKate Stone // allocation
1754b9c1b51eSKate Stone // This is necessary for infering the struct type so we can pretty print the
1755b9c1b51eSKate Stone // allocation's contents.
17568b244e21SEwan Crawford // Returns true on success, false otherwise
1757b9c1b51eSKate Stone bool RenderScriptRuntime::JITSubelements(Element &elem,
1758b9c1b51eSKate Stone                                          const lldb::addr_t context,
1759b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
17608b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
17618b244e21SEwan Crawford 
1762b9c1b51eSKate Stone   if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
17638b244e21SEwan Crawford     if (log)
1764b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
17658b244e21SEwan Crawford     return false;
17668b244e21SEwan Crawford   }
17678b244e21SEwan Crawford 
17688b244e21SEwan Crawford   const short num_exprs = 3;
1769b9c1b51eSKate Stone   assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) &&
1770b9c1b51eSKate Stone          "Invalid number of expressions");
17718b244e21SEwan Crawford 
1772ea0636b5SEwan Crawford   char expr_buffer[jit_max_expr_size];
17738b244e21SEwan Crawford   uint64_t results;
17748b244e21SEwan Crawford 
17758b244e21SEwan Crawford   // Iterate over struct fields.
17768b244e21SEwan Crawford   const uint32_t field_count = *elem.field_count.get();
1777b9c1b51eSKate Stone   for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
17788b244e21SEwan Crawford     Element child;
1779b9c1b51eSKate Stone     for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
1780b9c1b51eSKate Stone       const char *expr_cstr =
1781b9c1b51eSKate Stone           JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
1782b9c1b51eSKate Stone       int chars_written =
1783b9c1b51eSKate Stone           snprintf(expr_buffer, jit_max_expr_size, expr_cstr, field_count,
1784b9c1b51eSKate Stone                    field_count, field_count, context, *elem.element_ptr.get(),
1785b9c1b51eSKate Stone                    field_count, field_index);
1786b9c1b51eSKate Stone       if (chars_written < 0) {
17878b244e21SEwan Crawford         if (log)
1788b3f7f69dSAidan Dodds           log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
17898b244e21SEwan Crawford         return false;
1790b9c1b51eSKate Stone       } else if (chars_written >= jit_max_expr_size) {
17918b244e21SEwan Crawford         if (log)
1792b3f7f69dSAidan Dodds           log->Printf("%s - expression too long.", __FUNCTION__);
17938b244e21SEwan Crawford         return false;
17948b244e21SEwan Crawford       }
17958b244e21SEwan Crawford 
17968b244e21SEwan Crawford       // Perform expression evaluation
17978b244e21SEwan Crawford       if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
17988b244e21SEwan Crawford         return false;
17998b244e21SEwan Crawford 
18008b244e21SEwan Crawford       if (log)
1801b3f7f69dSAidan Dodds         log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
18028b244e21SEwan Crawford 
1803b9c1b51eSKate Stone       switch (expr_index) {
18048b244e21SEwan Crawford       case 0: // Element* of child
18058b244e21SEwan Crawford         child.element_ptr = static_cast<addr_t>(results);
18068b244e21SEwan Crawford         break;
18078b244e21SEwan Crawford       case 1: // Name of child
18088b244e21SEwan Crawford       {
18098b244e21SEwan Crawford         lldb::addr_t address = static_cast<addr_t>(results);
18108b244e21SEwan Crawford         Error err;
18118b244e21SEwan Crawford         std::string name;
18128b244e21SEwan Crawford         GetProcess()->ReadCStringFromMemory(address, name, err);
18138b244e21SEwan Crawford         if (!err.Fail())
18148b244e21SEwan Crawford           child.type_name = ConstString(name);
1815b9c1b51eSKate Stone         else {
18168b244e21SEwan Crawford           if (log)
1817b9c1b51eSKate Stone             log->Printf("%s - warning: Couldn't read field name.",
1818b9c1b51eSKate Stone                         __FUNCTION__);
18198b244e21SEwan Crawford         }
18208b244e21SEwan Crawford         break;
18218b244e21SEwan Crawford       }
18228b244e21SEwan Crawford       case 2: // Array size of child
18238b244e21SEwan Crawford         child.array_size = static_cast<uint32_t>(results);
18248b244e21SEwan Crawford         break;
18258b244e21SEwan Crawford       }
18268b244e21SEwan Crawford     }
18278b244e21SEwan Crawford 
18288b244e21SEwan Crawford     // We need to recursively JIT each Element field of the struct since
18298b244e21SEwan Crawford     // structs can be nested inside structs.
18308b244e21SEwan Crawford     if (!JITElementPacked(child, context, frame_ptr))
18318b244e21SEwan Crawford       return false;
18328b244e21SEwan Crawford     elem.children.push_back(child);
18338b244e21SEwan Crawford   }
18348b244e21SEwan Crawford 
1835b9c1b51eSKate Stone   // Try to infer the name of the struct type so we can pretty print the
1836b9c1b51eSKate Stone   // allocation contents.
18378b244e21SEwan Crawford   FindStructTypeName(elem, frame_ptr);
183815f2bd95SEwan Crawford 
183915f2bd95SEwan Crawford   return true;
184015f2bd95SEwan Crawford }
184115f2bd95SEwan Crawford 
1842a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
1843b9c1b51eSKate Stone // The `elem_size` parameter represents the size of a single element, including
1844b9c1b51eSKate Stone // padding.
1845a0f08674SEwan Crawford // Which is needed as an offset from the last element pointer.
1846b9c1b51eSKate Stone // Using this offset minus the starting address we can calculate the size of the
1847b9c1b51eSKate Stone // allocation.
1848a0f08674SEwan Crawford // Returns true on success, false otherwise
1849b9c1b51eSKate Stone bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *allocation,
1850b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
1851a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1852a0f08674SEwan Crawford 
1853b9c1b51eSKate Stone   if (!allocation->address.isValid() || !allocation->dimension.isValid() ||
1854b9c1b51eSKate Stone       !allocation->data_ptr.isValid() ||
1855b9c1b51eSKate Stone       !allocation->element.datum_size.isValid()) {
1856a0f08674SEwan Crawford     if (log)
1857b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1858a0f08674SEwan Crawford     return false;
1859a0f08674SEwan Crawford   }
1860a0f08674SEwan Crawford 
1861a0f08674SEwan Crawford   // Find dimensions
1862b3f7f69dSAidan Dodds   uint32_t dim_x = allocation->dimension.get()->dim_1;
1863b3f7f69dSAidan Dodds   uint32_t dim_y = allocation->dimension.get()->dim_2;
1864b3f7f69dSAidan Dodds   uint32_t dim_z = allocation->dimension.get()->dim_3;
1865a0f08674SEwan Crawford 
1866b9c1b51eSKate Stone   // Our plan of jitting the last element address doesn't seem to work for
1867b9c1b51eSKate Stone   // struct Allocations
18688b244e21SEwan Crawford   // Instead try to infer the size ourselves without any inter element padding.
1869b9c1b51eSKate Stone   if (allocation->element.children.size() > 0) {
1870b9c1b51eSKate Stone     if (dim_x == 0)
1871b9c1b51eSKate Stone       dim_x = 1;
1872b9c1b51eSKate Stone     if (dim_y == 0)
1873b9c1b51eSKate Stone       dim_y = 1;
1874b9c1b51eSKate Stone     if (dim_z == 0)
1875b9c1b51eSKate Stone       dim_z = 1;
18768b244e21SEwan Crawford 
1877b9c1b51eSKate Stone     allocation->size =
1878b9c1b51eSKate Stone         dim_x * dim_y * dim_z * *allocation->element.datum_size.get();
18798b244e21SEwan Crawford 
18808b244e21SEwan Crawford     if (log)
1881b9c1b51eSKate Stone       log->Printf("%s - inferred size of struct allocation %" PRIu32 ".",
1882b9c1b51eSKate Stone                   __FUNCTION__, *allocation->size.get());
18838b244e21SEwan Crawford     return true;
18848b244e21SEwan Crawford   }
18858b244e21SEwan Crawford 
1886ea0636b5SEwan Crawford   const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1887ea0636b5SEwan Crawford   char buffer[jit_max_expr_size];
18888b244e21SEwan Crawford 
1889a0f08674SEwan Crawford   // Calculate last element
1890a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 0 : dim_x - 1;
1891a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 0 : dim_y - 1;
1892a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 0 : dim_z - 1;
1893a0f08674SEwan Crawford 
1894b9c1b51eSKate Stone   int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr,
1895b9c1b51eSKate Stone                                *allocation->address.get(), dim_x, dim_y, dim_z);
1896b9c1b51eSKate Stone   if (chars_written < 0) {
1897a0f08674SEwan Crawford     if (log)
1898b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1899a0f08674SEwan Crawford     return false;
1900b9c1b51eSKate Stone   } else if (chars_written >= jit_max_expr_size) {
1901a0f08674SEwan Crawford     if (log)
1902b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
1903a0f08674SEwan Crawford     return false;
1904a0f08674SEwan Crawford   }
1905a0f08674SEwan Crawford 
1906a0f08674SEwan Crawford   uint64_t result = 0;
1907a0f08674SEwan Crawford   if (!EvalRSExpression(buffer, frame_ptr, &result))
1908a0f08674SEwan Crawford     return false;
1909a0f08674SEwan Crawford 
1910a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1911a0f08674SEwan Crawford   // Find pointer to last element and add on size of an element
1912b3f7f69dSAidan Dodds   allocation->size =
1913b9c1b51eSKate Stone       static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()) +
1914b9c1b51eSKate Stone       *allocation->element.datum_size.get();
1915a0f08674SEwan Crawford 
1916a0f08674SEwan Crawford   return true;
1917a0f08674SEwan Crawford }
1918a0f08674SEwan Crawford 
1919b9c1b51eSKate Stone // JITs the RS runtime for information about the stride between rows in the
1920b9c1b51eSKate Stone // allocation.
1921a0f08674SEwan Crawford // This is done to detect padding, since allocated memory is 16-byte aligned.
1922a0f08674SEwan Crawford // Returns true on success, false otherwise
1923b9c1b51eSKate Stone bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *allocation,
1924b9c1b51eSKate Stone                                               StackFrame *frame_ptr) {
1925a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1926a0f08674SEwan Crawford 
1927b9c1b51eSKate Stone   if (!allocation->address.isValid() || !allocation->data_ptr.isValid()) {
1928a0f08674SEwan Crawford     if (log)
1929b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1930a0f08674SEwan Crawford     return false;
1931a0f08674SEwan Crawford   }
1932a0f08674SEwan Crawford 
1933ea0636b5SEwan Crawford   const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1934ea0636b5SEwan Crawford   char buffer[jit_max_expr_size];
1935a0f08674SEwan Crawford 
1936b9c1b51eSKate Stone   int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr,
1937b9c1b51eSKate Stone                                *allocation->address.get(), 0, 1, 0);
1938b9c1b51eSKate Stone   if (chars_written < 0) {
1939a0f08674SEwan Crawford     if (log)
1940b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1941a0f08674SEwan Crawford     return false;
1942b9c1b51eSKate Stone   } else if (chars_written >= jit_max_expr_size) {
1943a0f08674SEwan Crawford     if (log)
1944b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
1945a0f08674SEwan Crawford     return false;
1946a0f08674SEwan Crawford   }
1947a0f08674SEwan Crawford 
1948a0f08674SEwan Crawford   uint64_t result = 0;
1949a0f08674SEwan Crawford   if (!EvalRSExpression(buffer, frame_ptr, &result))
1950a0f08674SEwan Crawford     return false;
1951a0f08674SEwan Crawford 
1952a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1953b9c1b51eSKate Stone   allocation->stride =
1954b9c1b51eSKate Stone       static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get());
1955a0f08674SEwan Crawford 
1956a0f08674SEwan Crawford   return true;
1957a0f08674SEwan Crawford }
1958a0f08674SEwan Crawford 
195915f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
1960b9c1b51eSKate Stone bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *allocation,
1961b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
196215f2bd95SEwan Crawford   // GetOffsetPointer()
196315f2bd95SEwan Crawford   if (!JITDataPointer(allocation, frame_ptr))
196415f2bd95SEwan Crawford     return false;
196515f2bd95SEwan Crawford 
196615f2bd95SEwan Crawford   // rsaAllocationGetType()
196715f2bd95SEwan Crawford   if (!JITTypePointer(allocation, frame_ptr))
196815f2bd95SEwan Crawford     return false;
196915f2bd95SEwan Crawford 
197015f2bd95SEwan Crawford   // rsaTypeGetNativeData()
197115f2bd95SEwan Crawford   if (!JITTypePacked(allocation, frame_ptr))
197215f2bd95SEwan Crawford     return false;
197315f2bd95SEwan Crawford 
197415f2bd95SEwan Crawford   // rsaElementGetNativeData()
1975b9c1b51eSKate Stone   if (!JITElementPacked(allocation->element, *allocation->context.get(),
1976b9c1b51eSKate Stone                         frame_ptr))
197715f2bd95SEwan Crawford     return false;
197815f2bd95SEwan Crawford 
19798b244e21SEwan Crawford   // Sets the datum_size member in Element
19808b244e21SEwan Crawford   SetElementSize(allocation->element);
19818b244e21SEwan Crawford 
198255232f09SEwan Crawford   // Use GetOffsetPointer() to infer size of the allocation
19838b244e21SEwan Crawford   if (!JITAllocationSize(allocation, frame_ptr))
198455232f09SEwan Crawford     return false;
198555232f09SEwan Crawford 
198655232f09SEwan Crawford   return true;
198755232f09SEwan Crawford }
198855232f09SEwan Crawford 
1989b9c1b51eSKate Stone // Function attempts to set the type_name member of the paramaterised Element
1990b9c1b51eSKate Stone // object.
19918b244e21SEwan Crawford // This string should be the name of the struct type the Element represents.
19928b244e21SEwan Crawford // We need this string for pretty printing the Element to users.
1993b9c1b51eSKate Stone void RenderScriptRuntime::FindStructTypeName(Element &elem,
1994b9c1b51eSKate Stone                                              StackFrame *frame_ptr) {
19958b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
19968b244e21SEwan Crawford 
19978b244e21SEwan Crawford   if (!elem.type_name.IsEmpty()) // Name already set
19988b244e21SEwan Crawford     return;
19998b244e21SEwan Crawford   else
2000b9c1b51eSKate Stone     elem.type_name = Element::GetFallbackStructName(); // Default type name if
2001b9c1b51eSKate Stone                                                        // we don't succeed
20028b244e21SEwan Crawford 
20038b244e21SEwan Crawford   // Find all the global variables from the script rs modules
20048b244e21SEwan Crawford   VariableList variable_list;
20058b244e21SEwan Crawford   for (auto module_sp : m_rsmodules)
200695eae423SZachary Turner     module_sp->m_module->FindGlobalVariables(
200795eae423SZachary Turner         RegularExpression(llvm::StringRef(".")), true, UINT32_MAX,
200895eae423SZachary Turner         variable_list);
20098b244e21SEwan Crawford 
2010b9c1b51eSKate Stone   // Iterate over all the global variables looking for one with a matching type
2011b9c1b51eSKate Stone   // to the Element.
2012b9c1b51eSKate Stone   // We make the assumption a match exists since there needs to be a global
2013b9c1b51eSKate Stone   // variable to reflect the
20148b244e21SEwan Crawford   // struct type back into java host code.
2015b9c1b51eSKate Stone   for (uint32_t var_index = 0; var_index < variable_list.GetSize();
2016b9c1b51eSKate Stone        ++var_index) {
20178b244e21SEwan Crawford     const VariableSP var_sp(variable_list.GetVariableAtIndex(var_index));
20188b244e21SEwan Crawford     if (!var_sp)
20198b244e21SEwan Crawford       continue;
20208b244e21SEwan Crawford 
20218b244e21SEwan Crawford     ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
20228b244e21SEwan Crawford     if (!valobj_sp)
20238b244e21SEwan Crawford       continue;
20248b244e21SEwan Crawford 
20258b244e21SEwan Crawford     // Find the number of variable fields.
2026b9c1b51eSKate Stone     // If it has no fields, or more fields than our Element, then it can't be
2027b9c1b51eSKate Stone     // the struct we're looking for.
2028b9c1b51eSKate Stone     // Don't check for equality since RS can add extra struct members for
2029b9c1b51eSKate Stone     // padding.
20308b244e21SEwan Crawford     size_t num_children = valobj_sp->GetNumChildren();
20318b244e21SEwan Crawford     if (num_children > elem.children.size() || num_children == 0)
20328b244e21SEwan Crawford       continue;
20338b244e21SEwan Crawford 
20348b244e21SEwan Crawford     // Iterate over children looking for members with matching field names.
20358b244e21SEwan Crawford     // If all the field names match, this is likely the struct we want.
20368b244e21SEwan Crawford     //
2037b9c1b51eSKate Stone     //   TODO: This could be made more robust by also checking children data
2038b9c1b51eSKate Stone     //   sizes, or array size
20398b244e21SEwan Crawford     bool found = true;
2040b9c1b51eSKate Stone     for (size_t child_index = 0; child_index < num_children; ++child_index) {
20418b244e21SEwan Crawford       ValueObjectSP child = valobj_sp->GetChildAtIndex(child_index, true);
2042b9c1b51eSKate Stone       if (!child ||
2043b9c1b51eSKate Stone           (child->GetName() != elem.children[child_index].type_name)) {
20448b244e21SEwan Crawford         found = false;
20458b244e21SEwan Crawford         break;
20468b244e21SEwan Crawford       }
20478b244e21SEwan Crawford     }
20488b244e21SEwan Crawford 
2049b9c1b51eSKate Stone     // RS can add extra struct members for padding in the format
2050b9c1b51eSKate Stone     // '#rs_padding_[0-9]+'
2051b9c1b51eSKate Stone     if (found && num_children < elem.children.size()) {
2052b3f7f69dSAidan Dodds       const uint32_t size_diff = elem.children.size() - num_children;
20538b244e21SEwan Crawford       if (log)
2054b9c1b51eSKate Stone         log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2055b9c1b51eSKate Stone                     size_diff);
20568b244e21SEwan Crawford 
2057b9c1b51eSKate Stone       for (uint32_t padding_index = 0; padding_index < size_diff;
2058b9c1b51eSKate Stone            ++padding_index) {
2059b9c1b51eSKate Stone         const ConstString &name =
2060b9c1b51eSKate Stone             elem.children[num_children + padding_index].type_name;
20618b244e21SEwan Crawford         if (strcmp(name.AsCString(), "#rs_padding") < 0)
20628b244e21SEwan Crawford           found = false;
20638b244e21SEwan Crawford       }
20648b244e21SEwan Crawford     }
20658b244e21SEwan Crawford 
20668b244e21SEwan Crawford     // We've found a global var with matching type
2067b9c1b51eSKate Stone     if (found) {
20688b244e21SEwan Crawford       // Dereference since our Element type isn't a pointer.
2069b9c1b51eSKate Stone       if (valobj_sp->IsPointerType()) {
20708b244e21SEwan Crawford         Error err;
20718b244e21SEwan Crawford         ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
20728b244e21SEwan Crawford         if (!err.Fail())
20738b244e21SEwan Crawford           valobj_sp = deref_valobj;
20748b244e21SEwan Crawford       }
20758b244e21SEwan Crawford 
20768b244e21SEwan Crawford       // Save name of variable in Element.
20778b244e21SEwan Crawford       elem.type_name = valobj_sp->GetTypeName();
20788b244e21SEwan Crawford       if (log)
2079b9c1b51eSKate Stone         log->Printf("%s - element name set to %s", __FUNCTION__,
2080b9c1b51eSKate Stone                     elem.type_name.AsCString());
20818b244e21SEwan Crawford 
20828b244e21SEwan Crawford       return;
20838b244e21SEwan Crawford     }
20848b244e21SEwan Crawford   }
20858b244e21SEwan Crawford }
20868b244e21SEwan Crawford 
2087b9c1b51eSKate Stone // Function sets the datum_size member of Element. Representing the size of a
2088b9c1b51eSKate Stone // single instance including padding.
20898b244e21SEwan Crawford // Assumes the relevant allocation information has already been jitted.
2090b9c1b51eSKate Stone void RenderScriptRuntime::SetElementSize(Element &elem) {
20918b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
20928b244e21SEwan Crawford   const Element::DataType type = *elem.type.get();
2093b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2094b9c1b51eSKate Stone          "Invalid allocation type");
209555232f09SEwan Crawford 
2096b3f7f69dSAidan Dodds   const uint32_t vec_size = *elem.type_vec_size.get();
2097b3f7f69dSAidan Dodds   uint32_t data_size = 0;
2098b3f7f69dSAidan Dodds   uint32_t padding = 0;
209955232f09SEwan Crawford 
21008b244e21SEwan Crawford   // Element is of a struct type, calculate size recursively.
2101b9c1b51eSKate Stone   if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2102b9c1b51eSKate Stone     for (Element &child : elem.children) {
21038b244e21SEwan Crawford       SetElementSize(child);
2104b9c1b51eSKate Stone       const uint32_t array_size =
2105b9c1b51eSKate Stone           child.array_size.isValid() ? *child.array_size.get() : 1;
21068b244e21SEwan Crawford       data_size += *child.datum_size.get() * array_size;
21078b244e21SEwan Crawford     }
21088b244e21SEwan Crawford   }
2109b3f7f69dSAidan Dodds   // These have been packed already
2110b3f7f69dSAidan Dodds   else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2111b3f7f69dSAidan Dodds            type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2112b9c1b51eSKate Stone            type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
21132e920715SEwan Crawford     data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2114b9c1b51eSKate Stone   } else if (type < Element::RS_TYPE_ELEMENT) {
2115b9c1b51eSKate Stone     data_size =
2116b9c1b51eSKate Stone         vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
21172e920715SEwan Crawford     if (vec_size == 3)
21182e920715SEwan Crawford       padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2119b9c1b51eSKate Stone   } else
2120b9c1b51eSKate Stone     data_size =
2121b9c1b51eSKate Stone         GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
21228b244e21SEwan Crawford 
21238b244e21SEwan Crawford   elem.padding = padding;
21248b244e21SEwan Crawford   elem.datum_size = data_size + padding;
21258b244e21SEwan Crawford   if (log)
2126b9c1b51eSKate Stone     log->Printf("%s - element size set to %" PRIu32, __FUNCTION__,
2127b9c1b51eSKate Stone                 data_size + padding);
212855232f09SEwan Crawford }
212955232f09SEwan Crawford 
2130b9c1b51eSKate Stone // Given an allocation, this function copies the allocation contents from device
2131b9c1b51eSKate Stone // into a buffer on the heap.
213255232f09SEwan Crawford // Returning a shared pointer to the buffer containing the data.
213355232f09SEwan Crawford std::shared_ptr<uint8_t>
2134b9c1b51eSKate Stone RenderScriptRuntime::GetAllocationData(AllocationDetails *allocation,
2135b9c1b51eSKate Stone                                        StackFrame *frame_ptr) {
213655232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
213755232f09SEwan Crawford 
213855232f09SEwan Crawford   // JIT all the allocation details
2139b9c1b51eSKate Stone   if (allocation->shouldRefresh()) {
214055232f09SEwan Crawford     if (log)
2141b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info",
2142b9c1b51eSKate Stone                   __FUNCTION__);
214355232f09SEwan Crawford 
2144b9c1b51eSKate Stone     if (!RefreshAllocation(allocation, frame_ptr)) {
214555232f09SEwan Crawford       if (log)
2146b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
214755232f09SEwan Crawford       return nullptr;
214855232f09SEwan Crawford     }
214955232f09SEwan Crawford   }
215055232f09SEwan Crawford 
2151b3f7f69dSAidan Dodds   assert(allocation->data_ptr.isValid() && allocation->element.type.isValid() &&
2152b9c1b51eSKate Stone          allocation->element.type_vec_size.isValid() &&
2153b9c1b51eSKate Stone          allocation->size.isValid() && "Allocation information not available");
215455232f09SEwan Crawford 
215555232f09SEwan Crawford   // Allocate a buffer to copy data into
2156b3f7f69dSAidan Dodds   const uint32_t size = *allocation->size.get();
215755232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2158b9c1b51eSKate Stone   if (!buffer) {
215955232f09SEwan Crawford     if (log)
2160b9c1b51eSKate Stone       log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer",
2161b9c1b51eSKate Stone                   __FUNCTION__, size);
216255232f09SEwan Crawford     return nullptr;
216355232f09SEwan Crawford   }
216455232f09SEwan Crawford 
216555232f09SEwan Crawford   // Read the inferior memory
216655232f09SEwan Crawford   Error error;
216755232f09SEwan Crawford   lldb::addr_t data_ptr = *allocation->data_ptr.get();
216855232f09SEwan Crawford   GetProcess()->ReadMemory(data_ptr, buffer.get(), size, error);
2169b9c1b51eSKate Stone   if (error.Fail()) {
217055232f09SEwan Crawford     if (log)
2171b9c1b51eSKate Stone       log->Printf("%s - '%s' Couldn't read %" PRIu32
2172b9c1b51eSKate Stone                   " bytes of allocation data from 0x%" PRIx64,
2173b3f7f69dSAidan Dodds                   __FUNCTION__, error.AsCString(), size, data_ptr);
217455232f09SEwan Crawford     return nullptr;
217555232f09SEwan Crawford   }
217655232f09SEwan Crawford 
217755232f09SEwan Crawford   return buffer;
217855232f09SEwan Crawford }
217955232f09SEwan Crawford 
218055232f09SEwan Crawford // Function copies data from a binary file into an allocation.
2181b9c1b51eSKate Stone // There is a header at the start of the file, FileHeader, before the data
2182b9c1b51eSKate Stone // content itself.
2183b9c1b51eSKate Stone // Information from this header is used to display warnings to the user about
2184b9c1b51eSKate Stone // incompatibilities
2185b9c1b51eSKate Stone bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
2186b9c1b51eSKate Stone                                          const char *filename,
2187b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
218855232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
218955232f09SEwan Crawford 
219055232f09SEwan Crawford   // Find allocation with the given id
219155232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
219255232f09SEwan Crawford   if (!alloc)
219355232f09SEwan Crawford     return false;
219455232f09SEwan Crawford 
219555232f09SEwan Crawford   if (log)
2196b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2197b9c1b51eSKate Stone                 *alloc->address.get());
219855232f09SEwan Crawford 
219955232f09SEwan Crawford   // JIT all the allocation details
2200b9c1b51eSKate Stone   if (alloc->shouldRefresh()) {
220155232f09SEwan Crawford     if (log)
2202b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2203b9c1b51eSKate Stone                   __FUNCTION__);
220455232f09SEwan Crawford 
2205b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
220655232f09SEwan Crawford       if (log)
2207b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
22084cfc9198SSylvestre Ledru       return false;
220955232f09SEwan Crawford     }
221055232f09SEwan Crawford   }
221155232f09SEwan Crawford 
2212b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2213b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2214b9c1b51eSKate Stone          alloc->element.datum_size.isValid() &&
2215b9c1b51eSKate Stone          "Allocation information not available");
221655232f09SEwan Crawford 
221755232f09SEwan Crawford   // Check we can read from file
221855232f09SEwan Crawford   FileSpec file(filename, true);
2219b9c1b51eSKate Stone   if (!file.Exists()) {
222055232f09SEwan Crawford     strm.Printf("Error: File %s does not exist", filename);
222155232f09SEwan Crawford     strm.EOL();
222255232f09SEwan Crawford     return false;
222355232f09SEwan Crawford   }
222455232f09SEwan Crawford 
2225b9c1b51eSKate Stone   if (!file.Readable()) {
222655232f09SEwan Crawford     strm.Printf("Error: File %s does not have readable permissions", filename);
222755232f09SEwan Crawford     strm.EOL();
222855232f09SEwan Crawford     return false;
222955232f09SEwan Crawford   }
223055232f09SEwan Crawford 
223155232f09SEwan Crawford   // Read file into data buffer
223255232f09SEwan Crawford   DataBufferSP data_sp(file.ReadFileContents());
223355232f09SEwan Crawford 
223455232f09SEwan Crawford   // Cast start of buffer to FileHeader and use pointer to read metadata
223555232f09SEwan Crawford   void *file_buffer = data_sp->GetBytes();
2236b3f7f69dSAidan Dodds   if (file_buffer == nullptr ||
2237b9c1b51eSKate Stone       data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2238b9c1b51eSKate Stone                                 sizeof(AllocationDetails::ElementHeader))) {
2239b9c1b51eSKate Stone     strm.Printf("Error: File %s does not contain enough data for header",
2240b9c1b51eSKate Stone                 filename);
224126e52a70SEwan Crawford     strm.EOL();
224226e52a70SEwan Crawford     return false;
224326e52a70SEwan Crawford   }
2244b9c1b51eSKate Stone   const AllocationDetails::FileHeader *file_header =
2245b9c1b51eSKate Stone       static_cast<AllocationDetails::FileHeader *>(file_buffer);
224655232f09SEwan Crawford 
224726e52a70SEwan Crawford   // Check file starts with ascii characters "RSAD"
2248b9c1b51eSKate Stone   if (memcmp(file_header->ident, "RSAD", 4)) {
2249b9c1b51eSKate Stone     strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2250b9c1b51eSKate Stone                 "dump. Are you sure this is the correct file?");
225126e52a70SEwan Crawford     strm.EOL();
225226e52a70SEwan Crawford     return false;
225326e52a70SEwan Crawford   }
225426e52a70SEwan Crawford 
225526e52a70SEwan Crawford   // Look at the type of the root element in the header
225626e52a70SEwan Crawford   AllocationDetails::ElementHeader root_element_header;
2257b9c1b51eSKate Stone   memcpy(&root_element_header, static_cast<uint8_t *>(file_buffer) +
2258b9c1b51eSKate Stone                                    sizeof(AllocationDetails::FileHeader),
225926e52a70SEwan Crawford          sizeof(AllocationDetails::ElementHeader));
226055232f09SEwan Crawford 
226155232f09SEwan Crawford   if (log)
2262b9c1b51eSKate Stone     log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32,
2263b9c1b51eSKate Stone                 __FUNCTION__, root_element_header.type,
2264b9c1b51eSKate Stone                 root_element_header.element_size);
226555232f09SEwan Crawford 
2266b9c1b51eSKate Stone   // Check if the target allocation and file both have the same number of bytes
2267b9c1b51eSKate Stone   // for an Element
2268b9c1b51eSKate Stone   if (*alloc->element.datum_size.get() != root_element_header.element_size) {
2269b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2270b9c1b51eSKate Stone                 " bytes, allocation %" PRIu32 " bytes",
2271b9c1b51eSKate Stone                 root_element_header.element_size,
2272b9c1b51eSKate Stone                 *alloc->element.datum_size.get());
227355232f09SEwan Crawford     strm.EOL();
227455232f09SEwan Crawford   }
227555232f09SEwan Crawford 
227626e52a70SEwan Crawford   // Check if the target allocation and file both have the same type
2277b3f7f69dSAidan Dodds   const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
2278b3f7f69dSAidan Dodds   const uint32_t file_type = root_element_header.type;
227926e52a70SEwan Crawford 
2280b9c1b51eSKate Stone   if (file_type > Element::RS_TYPE_FONT) {
228126e52a70SEwan Crawford     strm.Printf("Warning: File has unknown allocation type");
228226e52a70SEwan Crawford     strm.EOL();
2283b9c1b51eSKate Stone   } else if (alloc_type != file_type) {
2284b9c1b51eSKate Stone     // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2285b9c1b51eSKate Stone     // array
2286b3f7f69dSAidan Dodds     uint32_t printable_target_type_index = alloc_type;
2287b3f7f69dSAidan Dodds     uint32_t printable_head_type_index = file_type;
2288b9c1b51eSKate Stone     if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2289b9c1b51eSKate Stone         alloc_type <= Element::RS_TYPE_FONT)
2290b9c1b51eSKate Stone       printable_target_type_index = static_cast<Element::DataType>(
2291b9c1b51eSKate Stone           (alloc_type - Element::RS_TYPE_ELEMENT) +
2292b3f7f69dSAidan Dodds           Element::RS_TYPE_MATRIX_2X2 + 1);
22932e920715SEwan Crawford 
2294b9c1b51eSKate Stone     if (file_type >= Element::RS_TYPE_ELEMENT &&
2295b9c1b51eSKate Stone         file_type <= Element::RS_TYPE_FONT)
2296b9c1b51eSKate Stone       printable_head_type_index = static_cast<Element::DataType>(
2297b9c1b51eSKate Stone           (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2298b9c1b51eSKate Stone           1);
22992e920715SEwan Crawford 
2300b9c1b51eSKate Stone     const char *file_type_cstr =
2301b9c1b51eSKate Stone         AllocationDetails::RsDataTypeToString[printable_head_type_index][0];
2302b9c1b51eSKate Stone     const char *target_type_cstr =
2303b9c1b51eSKate Stone         AllocationDetails::RsDataTypeToString[printable_target_type_index][0];
230455232f09SEwan Crawford 
2305b9c1b51eSKate Stone     strm.Printf(
2306b9c1b51eSKate Stone         "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
2307b9c1b51eSKate Stone         file_type_cstr, target_type_cstr);
230855232f09SEwan Crawford     strm.EOL();
230955232f09SEwan Crawford   }
231055232f09SEwan Crawford 
231126e52a70SEwan Crawford   // Advance buffer past header
231226e52a70SEwan Crawford   file_buffer = static_cast<uint8_t *>(file_buffer) + file_header->hdr_size;
231326e52a70SEwan Crawford 
231455232f09SEwan Crawford   // Calculate size of allocation data in file
231526e52a70SEwan Crawford   size_t length = data_sp->GetByteSize() - file_header->hdr_size;
231655232f09SEwan Crawford 
231755232f09SEwan Crawford   // Check if the target allocation and file both have the same total data size.
2318b3f7f69dSAidan Dodds   const uint32_t alloc_size = *alloc->size.get();
2319b9c1b51eSKate Stone   if (alloc_size != length) {
2320b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2321b9c1b51eSKate Stone                 " bytes, allocation 0x%" PRIx32 " bytes",
2322eba832beSJason Molenda                 (uint64_t)length, alloc_size);
232355232f09SEwan Crawford     strm.EOL();
2324b9c1b51eSKate Stone     length = alloc_size < length ? alloc_size
2325b9c1b51eSKate Stone                                  : length; // Set length to copy to minimum
232655232f09SEwan Crawford   }
232755232f09SEwan Crawford 
232855232f09SEwan Crawford   // Copy file data from our buffer into the target allocation.
232955232f09SEwan Crawford   lldb::addr_t alloc_data = *alloc->data_ptr.get();
233055232f09SEwan Crawford   Error error;
2331b9c1b51eSKate Stone   size_t bytes_written =
2332b9c1b51eSKate Stone       GetProcess()->WriteMemory(alloc_data, file_buffer, length, error);
2333b9c1b51eSKate Stone   if (!error.Success() || bytes_written != length) {
2334b9c1b51eSKate Stone     strm.Printf("Error: Couldn't write data to allocation %s",
2335b9c1b51eSKate Stone                 error.AsCString());
233655232f09SEwan Crawford     strm.EOL();
233755232f09SEwan Crawford     return false;
233855232f09SEwan Crawford   }
233955232f09SEwan Crawford 
2340b9c1b51eSKate Stone   strm.Printf("Contents of file '%s' read into allocation %" PRIu32, filename,
2341b9c1b51eSKate Stone               alloc->id);
234255232f09SEwan Crawford   strm.EOL();
234355232f09SEwan Crawford 
234455232f09SEwan Crawford   return true;
234555232f09SEwan Crawford }
234655232f09SEwan Crawford 
2347b9c1b51eSKate Stone // Function takes as parameters a byte buffer, which will eventually be written
2348b9c1b51eSKate Stone // to file as the element header,
2349b9c1b51eSKate Stone // an offset into that buffer, and an Element that will be saved into the buffer
2350b9c1b51eSKate Stone // at the parametrised offset.
235126e52a70SEwan Crawford // Return value is the new offset after writing the element into the buffer.
2352b9c1b51eSKate Stone // Elements are saved to the file as the ElementHeader struct followed by
2353b9c1b51eSKate Stone // offsets to the structs of all the element's
2354b3f7f69dSAidan Dodds // children.
2355b9c1b51eSKate Stone size_t RenderScriptRuntime::PopulateElementHeaders(
2356b9c1b51eSKate Stone     const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2357b9c1b51eSKate Stone     const Element &elem) {
2358b9c1b51eSKate Stone   // File struct for an element header with all the relevant details copied from
2359b9c1b51eSKate Stone   // elem.
236026e52a70SEwan Crawford   // We assume members are valid already.
236126e52a70SEwan Crawford   AllocationDetails::ElementHeader elem_header;
236226e52a70SEwan Crawford   elem_header.type = *elem.type.get();
236326e52a70SEwan Crawford   elem_header.kind = *elem.type_kind.get();
236426e52a70SEwan Crawford   elem_header.element_size = *elem.datum_size.get();
236526e52a70SEwan Crawford   elem_header.vector_size = *elem.type_vec_size.get();
2366b9c1b51eSKate Stone   elem_header.array_size =
2367b9c1b51eSKate Stone       elem.array_size.isValid() ? *elem.array_size.get() : 0;
236826e52a70SEwan Crawford   const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
236926e52a70SEwan Crawford 
237026e52a70SEwan Crawford   // Copy struct into buffer and advance offset
2371b9c1b51eSKate Stone   // We assume that header_buffer has been checked for nullptr before this
2372b9c1b51eSKate Stone   // method is called
237326e52a70SEwan Crawford   memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
237426e52a70SEwan Crawford   offset += elem_header_size;
237526e52a70SEwan Crawford 
237626e52a70SEwan Crawford   // Starting offset of child ElementHeader struct
2377b9c1b51eSKate Stone   size_t child_offset =
2378b9c1b51eSKate Stone       offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2379b9c1b51eSKate Stone   for (const RenderScriptRuntime::Element &child : elem.children) {
2380b9c1b51eSKate Stone     // Recursively populate the buffer with the element header structs of
2381b9c1b51eSKate Stone     // children.
2382b9c1b51eSKate Stone     // Then save the offsets where they were set after the parent element
2383b9c1b51eSKate Stone     // header.
238426e52a70SEwan Crawford     memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
238526e52a70SEwan Crawford     offset += sizeof(uint32_t);
238626e52a70SEwan Crawford 
238726e52a70SEwan Crawford     child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
238826e52a70SEwan Crawford   }
238926e52a70SEwan Crawford 
239026e52a70SEwan Crawford   // Zero indicates no more children
239126e52a70SEwan Crawford   memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
239226e52a70SEwan Crawford 
239326e52a70SEwan Crawford   return child_offset;
239426e52a70SEwan Crawford }
239526e52a70SEwan Crawford 
2396b9c1b51eSKate Stone // Given an Element object this function returns the total size needed in the
2397b9c1b51eSKate Stone // file header to store the element's
2398b3f7f69dSAidan Dodds // details.
2399b9c1b51eSKate Stone // Taking into account the size of the element header struct, plus the offsets
2400b9c1b51eSKate Stone // to all the element's children.
2401b9c1b51eSKate Stone // Function is recursive so that the size of all ancestors is taken into
2402b9c1b51eSKate Stone // account.
2403b9c1b51eSKate Stone size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
2404b9c1b51eSKate Stone   size_t size = (elem.children.size() + 1) *
2405b9c1b51eSKate Stone                 sizeof(uint32_t); // Offsets to children plus zero terminator
2406b9c1b51eSKate Stone   size += sizeof(AllocationDetails::ElementHeader); // Size of header struct
2407b9c1b51eSKate Stone                                                     // with type details
240826e52a70SEwan Crawford 
240926e52a70SEwan Crawford   // Calculate recursively for all descendants
241026e52a70SEwan Crawford   for (const Element &child : elem.children)
241126e52a70SEwan Crawford     size += CalculateElementHeaderSize(child);
241226e52a70SEwan Crawford 
241326e52a70SEwan Crawford   return size;
241426e52a70SEwan Crawford }
241526e52a70SEwan Crawford 
241655232f09SEwan Crawford // Function copies allocation contents into a binary file.
241755232f09SEwan Crawford // This file can then be loaded later into a different allocation.
2418b9c1b51eSKate Stone // There is a header, FileHeader, before the allocation data containing
2419b9c1b51eSKate Stone // meta-data.
2420b9c1b51eSKate Stone bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
2421b9c1b51eSKate Stone                                          const char *filename,
2422b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
242355232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
242455232f09SEwan Crawford 
242555232f09SEwan Crawford   // Find allocation with the given id
242655232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
242755232f09SEwan Crawford   if (!alloc)
242855232f09SEwan Crawford     return false;
242955232f09SEwan Crawford 
243055232f09SEwan Crawford   if (log)
2431b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2432b9c1b51eSKate Stone                 *alloc->address.get());
243355232f09SEwan Crawford 
243455232f09SEwan Crawford   // JIT all the allocation details
2435b9c1b51eSKate Stone   if (alloc->shouldRefresh()) {
243655232f09SEwan Crawford     if (log)
2437b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2438b9c1b51eSKate Stone                   __FUNCTION__);
243955232f09SEwan Crawford 
2440b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
244155232f09SEwan Crawford       if (log)
2442b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
24434cfc9198SSylvestre Ledru       return false;
244455232f09SEwan Crawford     }
244555232f09SEwan Crawford   }
244655232f09SEwan Crawford 
2447b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2448b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() &&
2449b9c1b51eSKate Stone          alloc->element.datum_size.get() &&
2450b9c1b51eSKate Stone          alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2451b3f7f69dSAidan Dodds          "Allocation information not available");
245255232f09SEwan Crawford 
245355232f09SEwan Crawford   // Check we can create writable file
245455232f09SEwan Crawford   FileSpec file_spec(filename, true);
2455b9c1b51eSKate Stone   File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate |
2456b9c1b51eSKate Stone                            File::eOpenOptionTruncate);
2457b9c1b51eSKate Stone   if (!file) {
245855232f09SEwan Crawford     strm.Printf("Error: Failed to open '%s' for writing", filename);
245955232f09SEwan Crawford     strm.EOL();
246055232f09SEwan Crawford     return false;
246155232f09SEwan Crawford   }
246255232f09SEwan Crawford 
246355232f09SEwan Crawford   // Read allocation into buffer of heap memory
246455232f09SEwan Crawford   const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2465b9c1b51eSKate Stone   if (!buffer) {
246655232f09SEwan Crawford     strm.Printf("Error: Couldn't read allocation data into buffer");
246755232f09SEwan Crawford     strm.EOL();
246855232f09SEwan Crawford     return false;
246955232f09SEwan Crawford   }
247055232f09SEwan Crawford 
247155232f09SEwan Crawford   // Create the file header
247255232f09SEwan Crawford   AllocationDetails::FileHeader head;
2473b3f7f69dSAidan Dodds   memcpy(head.ident, "RSAD", 4);
24742d62328aSEwan Crawford   head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
24752d62328aSEwan Crawford   head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
24762d62328aSEwan Crawford   head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
247726e52a70SEwan Crawford 
247826e52a70SEwan Crawford   const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2479b9c1b51eSKate Stone   assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2480b9c1b51eSKate Stone              UINT16_MAX &&
2481b9c1b51eSKate Stone          "Element header too large");
2482b9c1b51eSKate Stone   head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2483b9c1b51eSKate Stone                                         element_header_size);
248455232f09SEwan Crawford 
248555232f09SEwan Crawford   // Write the file header
248655232f09SEwan Crawford   size_t num_bytes = sizeof(AllocationDetails::FileHeader);
248726e52a70SEwan Crawford   if (log)
2488b9c1b51eSKate Stone     log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2489b9c1b51eSKate Stone                 (uint64_t)num_bytes);
249026e52a70SEwan Crawford 
249126e52a70SEwan Crawford   Error err = file.Write(&head, num_bytes);
2492b9c1b51eSKate Stone   if (!err.Success()) {
2493b9c1b51eSKate Stone     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(),
2494b9c1b51eSKate Stone                 filename);
249526e52a70SEwan Crawford     strm.EOL();
249626e52a70SEwan Crawford     return false;
249726e52a70SEwan Crawford   }
249826e52a70SEwan Crawford 
249926e52a70SEwan Crawford   // Create the headers describing the element type of the allocation.
2500b9c1b51eSKate Stone   std::shared_ptr<uint8_t> element_header_buffer(
2501b9c1b51eSKate Stone       new uint8_t[element_header_size]);
2502b9c1b51eSKate Stone   if (element_header_buffer == nullptr) {
2503b9c1b51eSKate Stone     strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2504b9c1b51eSKate Stone                 " bytes on the heap",
2505b9c1b51eSKate Stone                 (uint64_t)element_header_size);
250626e52a70SEwan Crawford     strm.EOL();
250726e52a70SEwan Crawford     return false;
250826e52a70SEwan Crawford   }
250926e52a70SEwan Crawford 
251026e52a70SEwan Crawford   PopulateElementHeaders(element_header_buffer, 0, alloc->element);
251126e52a70SEwan Crawford 
251226e52a70SEwan Crawford   // Write headers for allocation element type to file
251326e52a70SEwan Crawford   num_bytes = element_header_size;
251426e52a70SEwan Crawford   if (log)
2515b9c1b51eSKate Stone     log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.",
2516b9c1b51eSKate Stone                 __FUNCTION__, (uint64_t)num_bytes);
251726e52a70SEwan Crawford 
251826e52a70SEwan Crawford   err = file.Write(element_header_buffer.get(), num_bytes);
2519b9c1b51eSKate Stone   if (!err.Success()) {
2520b9c1b51eSKate Stone     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(),
2521b9c1b51eSKate Stone                 filename);
252255232f09SEwan Crawford     strm.EOL();
252355232f09SEwan Crawford     return false;
252455232f09SEwan Crawford   }
252555232f09SEwan Crawford 
252655232f09SEwan Crawford   // Write allocation data to file
252755232f09SEwan Crawford   num_bytes = static_cast<size_t>(*alloc->size.get());
252855232f09SEwan Crawford   if (log)
2529b9c1b51eSKate Stone     log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2530b9c1b51eSKate Stone                 (uint64_t)num_bytes);
253155232f09SEwan Crawford 
253255232f09SEwan Crawford   err = file.Write(buffer.get(), num_bytes);
2533b9c1b51eSKate Stone   if (!err.Success()) {
2534b9c1b51eSKate Stone     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(),
2535b9c1b51eSKate Stone                 filename);
253655232f09SEwan Crawford     strm.EOL();
253755232f09SEwan Crawford     return false;
253855232f09SEwan Crawford   }
253955232f09SEwan Crawford 
254055232f09SEwan Crawford   strm.Printf("Allocation written to file '%s'", filename);
254155232f09SEwan Crawford   strm.EOL();
254215f2bd95SEwan Crawford   return true;
254315f2bd95SEwan Crawford }
254415f2bd95SEwan Crawford 
2545b9c1b51eSKate Stone bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
25464640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
25474640cde1SColin Riley 
2548b9c1b51eSKate Stone   if (module_sp) {
2549b9c1b51eSKate Stone     for (const auto &rs_module : m_rsmodules) {
2550b9c1b51eSKate Stone       if (rs_module->m_module == module_sp) {
25517dc7771cSEwan Crawford         // Check if the user has enabled automatically breaking on
25527dc7771cSEwan Crawford         // all RS kernels.
25537dc7771cSEwan Crawford         if (m_breakAllKernels)
25547dc7771cSEwan Crawford           BreakOnModuleKernels(rs_module);
25557dc7771cSEwan Crawford 
25565ec532a9SColin Riley         return false;
25575ec532a9SColin Riley       }
25587dc7771cSEwan Crawford     }
2559ef20b08fSColin Riley     bool module_loaded = false;
2560b9c1b51eSKate Stone     switch (GetModuleKind(module_sp)) {
2561b9c1b51eSKate Stone     case eModuleKindKernelObj: {
25624640cde1SColin Riley       RSModuleDescriptorSP module_desc;
25634640cde1SColin Riley       module_desc.reset(new RSModuleDescriptor(module_sp));
2564b9c1b51eSKate Stone       if (module_desc->ParseRSInfo()) {
25655ec532a9SColin Riley         m_rsmodules.push_back(module_desc);
2566ef20b08fSColin Riley         module_loaded = true;
25675ec532a9SColin Riley       }
2568b9c1b51eSKate Stone       if (module_loaded) {
25694640cde1SColin Riley         FixupScriptDetails(module_desc);
25704640cde1SColin Riley       }
2571ef20b08fSColin Riley       break;
2572ef20b08fSColin Riley     }
2573b9c1b51eSKate Stone     case eModuleKindDriver: {
2574b9c1b51eSKate Stone       if (!m_libRSDriver) {
25754640cde1SColin Riley         m_libRSDriver = module_sp;
25764640cde1SColin Riley         LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
25774640cde1SColin Riley       }
25784640cde1SColin Riley       break;
25794640cde1SColin Riley     }
2580b9c1b51eSKate Stone     case eModuleKindImpl: {
25814640cde1SColin Riley       m_libRSCpuRef = module_sp;
25824640cde1SColin Riley       break;
25834640cde1SColin Riley     }
2584b9c1b51eSKate Stone     case eModuleKindLibRS: {
2585b9c1b51eSKate Stone       if (!m_libRS) {
25864640cde1SColin Riley         m_libRS = module_sp;
25874640cde1SColin Riley         static ConstString gDbgPresentStr("gDebuggerPresent");
2588b9c1b51eSKate Stone         const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2589b9c1b51eSKate Stone             gDbgPresentStr, eSymbolTypeData);
2590b9c1b51eSKate Stone         if (debug_present) {
25914640cde1SColin Riley           Error error;
25924640cde1SColin Riley           uint32_t flag = 0x00000001U;
25934640cde1SColin Riley           Target &target = GetProcess()->GetTarget();
2594358cf1eaSGreg Clayton           addr_t addr = debug_present->GetLoadAddress(&target);
25954640cde1SColin Riley           GetProcess()->WriteMemory(addr, &flag, sizeof(flag), error);
2596b9c1b51eSKate Stone           if (error.Success()) {
25974640cde1SColin Riley             if (log)
2598b9c1b51eSKate Stone               log->Printf("%s - debugger present flag set on debugee.",
2599b9c1b51eSKate Stone                           __FUNCTION__);
26004640cde1SColin Riley 
26014640cde1SColin Riley             m_debuggerPresentFlagged = true;
2602b9c1b51eSKate Stone           } else if (log) {
2603b9c1b51eSKate Stone             log->Printf("%s - error writing debugger present flags '%s' ",
2604b9c1b51eSKate Stone                         __FUNCTION__, error.AsCString());
26054640cde1SColin Riley           }
2606b9c1b51eSKate Stone         } else if (log) {
2607b9c1b51eSKate Stone           log->Printf(
2608b9c1b51eSKate Stone               "%s - error writing debugger present flags - symbol not found",
2609b9c1b51eSKate Stone               __FUNCTION__);
26104640cde1SColin Riley         }
26114640cde1SColin Riley       }
26124640cde1SColin Riley       break;
26134640cde1SColin Riley     }
2614ef20b08fSColin Riley     default:
2615ef20b08fSColin Riley       break;
2616ef20b08fSColin Riley     }
2617ef20b08fSColin Riley     if (module_loaded)
2618ef20b08fSColin Riley       Update();
2619ef20b08fSColin Riley     return module_loaded;
26205ec532a9SColin Riley   }
26215ec532a9SColin Riley   return false;
26225ec532a9SColin Riley }
26235ec532a9SColin Riley 
2624b9c1b51eSKate Stone void RenderScriptRuntime::Update() {
2625b9c1b51eSKate Stone   if (m_rsmodules.size() > 0) {
2626b9c1b51eSKate Stone     if (!m_initiated) {
2627ef20b08fSColin Riley       Initiate();
2628ef20b08fSColin Riley     }
2629ef20b08fSColin Riley   }
2630ef20b08fSColin Riley }
2631ef20b08fSColin Riley 
26327f193d69SLuke Drummond bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
26337f193d69SLuke Drummond                                           size_t n_lines) {
26347f193d69SLuke Drummond   // Skip the pragma prototype line
26357f193d69SLuke Drummond   ++lines;
26367f193d69SLuke Drummond   for (; n_lines--; ++lines) {
26377f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
26387f193d69SLuke Drummond     m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
26397f193d69SLuke Drummond   }
26407f193d69SLuke Drummond   return true;
26417f193d69SLuke Drummond }
26427f193d69SLuke Drummond 
26437f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
26447f193d69SLuke Drummond                                                 size_t n_lines) {
26457f193d69SLuke Drummond   // The list of reduction kernels in the `.rs.info` symbol is of the form
26467f193d69SLuke Drummond   // "signature - accumulatordatasize - reduction_name - initializer_name -
26477f193d69SLuke Drummond   // accumulator_name - combiner_name -
26487f193d69SLuke Drummond   // outconverter_name - halter_name"
26497f193d69SLuke Drummond   // Where a function is not explicitly named by the user, or is not generated
26507f193d69SLuke Drummond   // by the compiler, it is named "." so the
26517f193d69SLuke Drummond   // dash separated list should always be 8 items long
26527f193d69SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
26537f193d69SLuke Drummond   // Skip the exportReduceCount line
26547f193d69SLuke Drummond   ++lines;
26557f193d69SLuke Drummond   for (; n_lines--; ++lines) {
26567f193d69SLuke Drummond     llvm::SmallVector<llvm::StringRef, 8> spec;
26577f193d69SLuke Drummond     lines->split(spec, " - ");
26587f193d69SLuke Drummond     if (spec.size() != 8) {
26597f193d69SLuke Drummond       if (spec.size() < 8) {
26607f193d69SLuke Drummond         if (log)
26617f193d69SLuke Drummond           log->Error("Error parsing RenderScript reduction spec. wrong number "
26627f193d69SLuke Drummond                      "of fields");
26637f193d69SLuke Drummond         return false;
26647f193d69SLuke Drummond       } else if (log)
26657f193d69SLuke Drummond         log->Warning("Extraneous members in reduction spec: '%s'",
26667f193d69SLuke Drummond                      lines->str().c_str());
26677f193d69SLuke Drummond     }
26687f193d69SLuke Drummond 
26697f193d69SLuke Drummond     const auto sig_s = spec[0];
26707f193d69SLuke Drummond     uint32_t sig;
26717f193d69SLuke Drummond     if (sig_s.getAsInteger(10, sig)) {
26727f193d69SLuke Drummond       if (log)
26737f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid kernel "
26747f193d69SLuke Drummond                    "signature: '%s'",
26757f193d69SLuke Drummond                    sig_s.str().c_str());
26767f193d69SLuke Drummond       return false;
26777f193d69SLuke Drummond     }
26787f193d69SLuke Drummond 
26797f193d69SLuke Drummond     const auto accum_data_size_s = spec[1];
26807f193d69SLuke Drummond     uint32_t accum_data_size;
26817f193d69SLuke Drummond     if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
26827f193d69SLuke Drummond       if (log)
26837f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid "
26847f193d69SLuke Drummond                    "accumulator data size %s",
26857f193d69SLuke Drummond                    accum_data_size_s.str().c_str());
26867f193d69SLuke Drummond       return false;
26877f193d69SLuke Drummond     }
26887f193d69SLuke Drummond 
26897f193d69SLuke Drummond     if (log)
26907f193d69SLuke Drummond       log->Printf("Found RenderScript reduction '%s'", spec[2].str().c_str());
26917f193d69SLuke Drummond 
26927f193d69SLuke Drummond     m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
26937f193d69SLuke Drummond                                                  spec[2], spec[3], spec[4],
26947f193d69SLuke Drummond                                                  spec[5], spec[6], spec[7]));
26957f193d69SLuke Drummond   }
26967f193d69SLuke Drummond   return true;
26977f193d69SLuke Drummond }
26987f193d69SLuke Drummond 
26997f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
27007f193d69SLuke Drummond                                                  size_t n_lines) {
27017f193d69SLuke Drummond   // Skip the exportForeachCount line
27027f193d69SLuke Drummond   ++lines;
27037f193d69SLuke Drummond   for (; n_lines--; ++lines) {
27047f193d69SLuke Drummond     uint32_t slot;
27057f193d69SLuke Drummond     // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
27067f193d69SLuke Drummond     // pair per line
27077f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
27087f193d69SLuke Drummond     if (kv_pair.first.getAsInteger(10, slot))
27097f193d69SLuke Drummond       return false;
27107f193d69SLuke Drummond     m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
27117f193d69SLuke Drummond   }
27127f193d69SLuke Drummond   return true;
27137f193d69SLuke Drummond }
27147f193d69SLuke Drummond 
27157f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
27167f193d69SLuke Drummond                                              size_t n_lines) {
27177f193d69SLuke Drummond   // Skip the ExportVarCount line
27187f193d69SLuke Drummond   ++lines;
27197f193d69SLuke Drummond   for (; n_lines--; ++lines)
27207f193d69SLuke Drummond     m_globals.push_back(RSGlobalDescriptor(this, *lines));
27217f193d69SLuke Drummond   return true;
27227f193d69SLuke Drummond }
27235ec532a9SColin Riley 
2724b9c1b51eSKate Stone // The .rs.info symbol in renderscript modules contains a string which needs to
2725b9c1b51eSKate Stone // be parsed.
27265ec532a9SColin Riley // The string is basic and is parsed on a line by line basis.
2727b9c1b51eSKate Stone bool RSModuleDescriptor::ParseRSInfo() {
2728b0be30f7SAidan Dodds   assert(m_module);
27297f193d69SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2730b9c1b51eSKate Stone   const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
2731b9c1b51eSKate Stone       ConstString(".rs.info"), eSymbolTypeData);
2732b0be30f7SAidan Dodds   if (!info_sym)
2733b0be30f7SAidan Dodds     return false;
2734b0be30f7SAidan Dodds 
2735358cf1eaSGreg Clayton   const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
2736b0be30f7SAidan Dodds   if (addr == LLDB_INVALID_ADDRESS)
2737b0be30f7SAidan Dodds     return false;
2738b0be30f7SAidan Dodds 
27395ec532a9SColin Riley   const addr_t size = info_sym->GetByteSize();
27405ec532a9SColin Riley   const FileSpec fs = m_module->GetFileSpec();
27415ec532a9SColin Riley 
2742b0be30f7SAidan Dodds   const DataBufferSP buffer = fs.ReadFileContents(addr, size);
27435ec532a9SColin Riley   if (!buffer)
27445ec532a9SColin Riley     return false;
27455ec532a9SColin Riley 
2746b0be30f7SAidan Dodds   // split rs.info. contents into lines
27477f193d69SLuke Drummond   llvm::SmallVector<llvm::StringRef, 128> info_lines;
27485ec532a9SColin Riley   {
27497f193d69SLuke Drummond     const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
27507f193d69SLuke Drummond     raw_rs_info.split(info_lines, '\n');
27517f193d69SLuke Drummond     if (log)
27527f193d69SLuke Drummond       log->Printf("'.rs.info symbol for '%s':\n%s",
27537f193d69SLuke Drummond                   m_module->GetFileSpec().GetCString(),
27547f193d69SLuke Drummond                   raw_rs_info.str().c_str());
2755b0be30f7SAidan Dodds   }
2756b0be30f7SAidan Dodds 
27577f193d69SLuke Drummond   enum {
27587f193d69SLuke Drummond     eExportVar,
27597f193d69SLuke Drummond     eExportForEach,
27607f193d69SLuke Drummond     eExportReduce,
27617f193d69SLuke Drummond     ePragma,
27627f193d69SLuke Drummond     eBuildChecksum,
27637f193d69SLuke Drummond     eObjectSlot
27647f193d69SLuke Drummond   };
27657f193d69SLuke Drummond 
27667f193d69SLuke Drummond   static const llvm::StringMap<int> rs_info_handlers{
27677f193d69SLuke Drummond       {// The number of visible global variables in the script
27687f193d69SLuke Drummond        {"exportVarCount", eExportVar},
27697f193d69SLuke Drummond        // The number of RenderScrip `forEach` kernels __attribute__((kernel))
27707f193d69SLuke Drummond        {"exportForEachCount", eExportForEach},
27717f193d69SLuke Drummond        // The number of generalreductions: This marked in the script by `#pragma
27727f193d69SLuke Drummond        // reduce()`
27737f193d69SLuke Drummond        {"exportReduceCount", eExportReduce},
27747f193d69SLuke Drummond        // Total count of all RenderScript specific `#pragmas` used in the script
27757f193d69SLuke Drummond        {"pragmaCount", ePragma},
27767f193d69SLuke Drummond        {"objectSlotCount", eObjectSlot}}};
2777b0be30f7SAidan Dodds 
2778b0be30f7SAidan Dodds   // parse all text lines of .rs.info
2779b9c1b51eSKate Stone   for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
27807f193d69SLuke Drummond     const auto kv_pair = line->split(": ");
27817f193d69SLuke Drummond     const auto key = kv_pair.first;
27827f193d69SLuke Drummond     const auto val = kv_pair.second.trim();
27835ec532a9SColin Riley 
27847f193d69SLuke Drummond     const auto handler = rs_info_handlers.find(key);
27857f193d69SLuke Drummond     if (handler == rs_info_handlers.end())
27867f193d69SLuke Drummond       continue;
27877f193d69SLuke Drummond     // getAsInteger returns `true` on an error condition - we're only interested
27887f193d69SLuke Drummond     // in
27897f193d69SLuke Drummond     // numeric fields at the moment
27907f193d69SLuke Drummond     uint64_t n_lines;
27917f193d69SLuke Drummond     if (val.getAsInteger(10, n_lines)) {
27927f193d69SLuke Drummond       if (log)
27937f193d69SLuke Drummond         log->Debug("Failed to parse non-numeric '.rs.info' section %s",
27947f193d69SLuke Drummond                    line->str().c_str());
27957f193d69SLuke Drummond       continue;
27967f193d69SLuke Drummond     }
27977f193d69SLuke Drummond     if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
27987f193d69SLuke Drummond       return false;
27997f193d69SLuke Drummond 
28007f193d69SLuke Drummond     bool success = false;
28017f193d69SLuke Drummond     switch (handler->getValue()) {
28027f193d69SLuke Drummond     case eExportVar:
28037f193d69SLuke Drummond       success = ParseExportVarCount(line, n_lines);
28047f193d69SLuke Drummond       break;
28057f193d69SLuke Drummond     case eExportForEach:
28067f193d69SLuke Drummond       success = ParseExportForeachCount(line, n_lines);
28077f193d69SLuke Drummond       break;
28087f193d69SLuke Drummond     case eExportReduce:
28097f193d69SLuke Drummond       success = ParseExportReduceCount(line, n_lines);
28107f193d69SLuke Drummond       break;
28117f193d69SLuke Drummond     case ePragma:
28127f193d69SLuke Drummond       success = ParsePragmaCount(line, n_lines);
28137f193d69SLuke Drummond       break;
28147f193d69SLuke Drummond     default: {
28157f193d69SLuke Drummond       if (log)
28167f193d69SLuke Drummond         log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__,
28177f193d69SLuke Drummond                     line->str().c_str());
28187f193d69SLuke Drummond       continue;
28197f193d69SLuke Drummond     }
28207f193d69SLuke Drummond     }
28217f193d69SLuke Drummond     if (!success)
28227f193d69SLuke Drummond       return false;
28237f193d69SLuke Drummond     line += n_lines;
28247f193d69SLuke Drummond   }
28257f193d69SLuke Drummond   return info_lines.size() > 0;
28265ec532a9SColin Riley }
28275ec532a9SColin Riley 
2828b9c1b51eSKate Stone void RenderScriptRuntime::Status(Stream &strm) const {
2829b9c1b51eSKate Stone   if (m_libRS) {
28304640cde1SColin Riley     strm.Printf("Runtime Library discovered.");
28314640cde1SColin Riley     strm.EOL();
28324640cde1SColin Riley   }
2833b9c1b51eSKate Stone   if (m_libRSDriver) {
28344640cde1SColin Riley     strm.Printf("Runtime Driver discovered.");
28354640cde1SColin Riley     strm.EOL();
28364640cde1SColin Riley   }
2837b9c1b51eSKate Stone   if (m_libRSCpuRef) {
28384640cde1SColin Riley     strm.Printf("CPU Reference Implementation discovered.");
28394640cde1SColin Riley     strm.EOL();
28404640cde1SColin Riley   }
28414640cde1SColin Riley 
2842b9c1b51eSKate Stone   if (m_runtimeHooks.size()) {
28434640cde1SColin Riley     strm.Printf("Runtime functions hooked:");
28444640cde1SColin Riley     strm.EOL();
2845b9c1b51eSKate Stone     for (auto b : m_runtimeHooks) {
28464640cde1SColin Riley       strm.Indent(b.second->defn->name);
28474640cde1SColin Riley       strm.EOL();
28484640cde1SColin Riley     }
2849b9c1b51eSKate Stone   } else {
28504640cde1SColin Riley     strm.Printf("Runtime is not hooked.");
28514640cde1SColin Riley     strm.EOL();
28524640cde1SColin Riley   }
28534640cde1SColin Riley }
28544640cde1SColin Riley 
2855b9c1b51eSKate Stone void RenderScriptRuntime::DumpContexts(Stream &strm) const {
28564640cde1SColin Riley   strm.Printf("Inferred RenderScript Contexts:");
28574640cde1SColin Riley   strm.EOL();
28584640cde1SColin Riley   strm.IndentMore();
28594640cde1SColin Riley 
28604640cde1SColin Riley   std::map<addr_t, uint64_t> contextReferences;
28614640cde1SColin Riley 
286278f339d1SEwan Crawford   // Iterate over all of the currently discovered scripts.
2863b9c1b51eSKate Stone   // Note: We cant push or pop from m_scripts inside this loop or it may
2864b9c1b51eSKate Stone   // invalidate script.
2865b9c1b51eSKate Stone   for (const auto &script : m_scripts) {
286678f339d1SEwan Crawford     if (!script->context.isValid())
286778f339d1SEwan Crawford       continue;
286878f339d1SEwan Crawford     lldb::addr_t context = *script->context;
286978f339d1SEwan Crawford 
2870b9c1b51eSKate Stone     if (contextReferences.find(context) != contextReferences.end()) {
287178f339d1SEwan Crawford       contextReferences[context]++;
2872b9c1b51eSKate Stone     } else {
287378f339d1SEwan Crawford       contextReferences[context] = 1;
28744640cde1SColin Riley     }
28754640cde1SColin Riley   }
28764640cde1SColin Riley 
2877b9c1b51eSKate Stone   for (const auto &cRef : contextReferences) {
2878b9c1b51eSKate Stone     strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
2879b9c1b51eSKate Stone                 cRef.first, cRef.second);
28804640cde1SColin Riley     strm.EOL();
28814640cde1SColin Riley   }
28824640cde1SColin Riley   strm.IndentLess();
28834640cde1SColin Riley }
28844640cde1SColin Riley 
2885b9c1b51eSKate Stone void RenderScriptRuntime::DumpKernels(Stream &strm) const {
28864640cde1SColin Riley   strm.Printf("RenderScript Kernels:");
28874640cde1SColin Riley   strm.EOL();
28884640cde1SColin Riley   strm.IndentMore();
2889b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
28904640cde1SColin Riley     strm.Printf("Resource '%s':", module->m_resname.c_str());
28914640cde1SColin Riley     strm.EOL();
2892b9c1b51eSKate Stone     for (const auto &kernel : module->m_kernels) {
28934640cde1SColin Riley       strm.Indent(kernel.m_name.AsCString());
28944640cde1SColin Riley       strm.EOL();
28954640cde1SColin Riley     }
28964640cde1SColin Riley   }
28974640cde1SColin Riley   strm.IndentLess();
28984640cde1SColin Riley }
28994640cde1SColin Riley 
2900a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails *
2901b9c1b51eSKate Stone RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
2902a0f08674SEwan Crawford   AllocationDetails *alloc = nullptr;
2903a0f08674SEwan Crawford 
2904a0f08674SEwan Crawford   // See if we can find allocation using id as an index;
2905b9c1b51eSKate Stone   if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
2906b9c1b51eSKate Stone       m_allocations[alloc_id - 1]->id == alloc_id) {
2907a0f08674SEwan Crawford     alloc = m_allocations[alloc_id - 1].get();
2908a0f08674SEwan Crawford     return alloc;
2909a0f08674SEwan Crawford   }
2910a0f08674SEwan Crawford 
2911a0f08674SEwan Crawford   // Fallback to searching
2912b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
2913b9c1b51eSKate Stone     if (a->id == alloc_id) {
2914a0f08674SEwan Crawford       alloc = a.get();
2915a0f08674SEwan Crawford       break;
2916a0f08674SEwan Crawford     }
2917a0f08674SEwan Crawford   }
2918a0f08674SEwan Crawford 
2919b9c1b51eSKate Stone   if (alloc == nullptr) {
2920b9c1b51eSKate Stone     strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
2921b9c1b51eSKate Stone                 alloc_id);
2922a0f08674SEwan Crawford     strm.EOL();
2923a0f08674SEwan Crawford   }
2924a0f08674SEwan Crawford 
2925a0f08674SEwan Crawford   return alloc;
2926a0f08674SEwan Crawford }
2927a0f08674SEwan Crawford 
2928b9c1b51eSKate Stone // Prints the contents of an allocation to the output stream, which may be a
2929b9c1b51eSKate Stone // file
2930b9c1b51eSKate Stone bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
2931b9c1b51eSKate Stone                                          const uint32_t id) {
2932a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2933a0f08674SEwan Crawford 
2934a0f08674SEwan Crawford   // Check we can find the desired allocation
2935a0f08674SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, id);
2936a0f08674SEwan Crawford   if (!alloc)
2937a0f08674SEwan Crawford     return false; // FindAllocByID() will print error message for us here
2938a0f08674SEwan Crawford 
2939a0f08674SEwan Crawford   if (log)
2940b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2941b9c1b51eSKate Stone                 *alloc->address.get());
2942a0f08674SEwan Crawford 
2943a0f08674SEwan Crawford   // Check we have information about the allocation, if not calculate it
2944b9c1b51eSKate Stone   if (alloc->shouldRefresh()) {
2945a0f08674SEwan Crawford     if (log)
2946b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2947b9c1b51eSKate Stone                   __FUNCTION__);
2948a0f08674SEwan Crawford 
2949a0f08674SEwan Crawford     // JIT all the allocation information
2950b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
2951a0f08674SEwan Crawford       strm.Printf("Error: Couldn't JIT allocation details");
2952a0f08674SEwan Crawford       strm.EOL();
2953a0f08674SEwan Crawford       return false;
2954a0f08674SEwan Crawford     }
2955a0f08674SEwan Crawford   }
2956a0f08674SEwan Crawford 
2957a0f08674SEwan Crawford   // Establish format and size of each data element
2958b3f7f69dSAidan Dodds   const uint32_t vec_size = *alloc->element.type_vec_size.get();
29598b244e21SEwan Crawford   const Element::DataType type = *alloc->element.type.get();
2960a0f08674SEwan Crawford 
2961b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2962b9c1b51eSKate Stone          "Invalid allocation type");
2963a0f08674SEwan Crawford 
29642e920715SEwan Crawford   lldb::Format format;
29652e920715SEwan Crawford   if (type >= Element::RS_TYPE_ELEMENT)
29662e920715SEwan Crawford     format = eFormatHex;
29672e920715SEwan Crawford   else
2968b9c1b51eSKate Stone     format = vec_size == 1
2969b9c1b51eSKate Stone                  ? static_cast<lldb::Format>(
2970b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatSingle])
2971b9c1b51eSKate Stone                  : static_cast<lldb::Format>(
2972b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatVector]);
2973a0f08674SEwan Crawford 
2974b3f7f69dSAidan Dodds   const uint32_t data_size = *alloc->element.datum_size.get();
2975a0f08674SEwan Crawford 
2976a0f08674SEwan Crawford   if (log)
2977b9c1b51eSKate Stone     log->Printf("%s - element size %" PRIu32 " bytes, including padding",
2978b9c1b51eSKate Stone                 __FUNCTION__, data_size);
2979a0f08674SEwan Crawford 
298055232f09SEwan Crawford   // Allocate a buffer to copy data into
298155232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2982b9c1b51eSKate Stone   if (!buffer) {
29832e920715SEwan Crawford     strm.Printf("Error: Couldn't read allocation data");
298455232f09SEwan Crawford     strm.EOL();
298555232f09SEwan Crawford     return false;
298655232f09SEwan Crawford   }
298755232f09SEwan Crawford 
2988a0f08674SEwan Crawford   // Calculate stride between rows as there may be padding at end of rows since
2989a0f08674SEwan Crawford   // allocated memory is 16-byte aligned
2990b9c1b51eSKate Stone   if (!alloc->stride.isValid()) {
2991a0f08674SEwan Crawford     if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
2992a0f08674SEwan Crawford       alloc->stride = 0;
2993b9c1b51eSKate Stone     else if (!JITAllocationStride(alloc, frame_ptr)) {
2994a0f08674SEwan Crawford       strm.Printf("Error: Couldn't calculate allocation row stride");
2995a0f08674SEwan Crawford       strm.EOL();
2996a0f08674SEwan Crawford       return false;
2997a0f08674SEwan Crawford     }
2998a0f08674SEwan Crawford   }
2999b3f7f69dSAidan Dodds   const uint32_t stride = *alloc->stride.get();
3000b3f7f69dSAidan Dodds   const uint32_t size = *alloc->size.get(); // Size of whole allocation
3001b9c1b51eSKate Stone   const uint32_t padding =
3002b9c1b51eSKate Stone       alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3003a0f08674SEwan Crawford   if (log)
3004b9c1b51eSKate Stone     log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32
3005b9c1b51eSKate Stone                 " bytes, padding %" PRIu32,
3006b3f7f69dSAidan Dodds                 __FUNCTION__, stride, size, padding);
3007a0f08674SEwan Crawford 
3008a0f08674SEwan Crawford   // Find dimensions used to index loops, so need to be non-zero
3009b3f7f69dSAidan Dodds   uint32_t dim_x = alloc->dimension.get()->dim_1;
3010a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 1 : dim_x;
3011a0f08674SEwan Crawford 
3012b3f7f69dSAidan Dodds   uint32_t dim_y = alloc->dimension.get()->dim_2;
3013a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 1 : dim_y;
3014a0f08674SEwan Crawford 
3015b3f7f69dSAidan Dodds   uint32_t dim_z = alloc->dimension.get()->dim_3;
3016a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 1 : dim_z;
3017a0f08674SEwan Crawford 
301855232f09SEwan Crawford   // Use data extractor to format output
3019b9c1b51eSKate Stone   const uint32_t archByteSize =
3020b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3021b9c1b51eSKate Stone   DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
3022b9c1b51eSKate Stone                            archByteSize);
302355232f09SEwan Crawford 
3024b3f7f69dSAidan Dodds   uint32_t offset = 0;   // Offset in buffer to next element to be printed
3025b3f7f69dSAidan Dodds   uint32_t prev_row = 0; // Offset to the start of the previous row
3026a0f08674SEwan Crawford 
3027a0f08674SEwan Crawford   // Iterate over allocation dimensions, printing results to user
3028a0f08674SEwan Crawford   strm.Printf("Data (X, Y, Z):");
3029b9c1b51eSKate Stone   for (uint32_t z = 0; z < dim_z; ++z) {
3030b9c1b51eSKate Stone     for (uint32_t y = 0; y < dim_y; ++y) {
3031a0f08674SEwan Crawford       // Use stride to index start of next row.
3032a0f08674SEwan Crawford       if (!(y == 0 && z == 0))
3033a0f08674SEwan Crawford         offset = prev_row + stride;
3034a0f08674SEwan Crawford       prev_row = offset;
3035a0f08674SEwan Crawford 
3036a0f08674SEwan Crawford       // Print each element in the row individually
3037b9c1b51eSKate Stone       for (uint32_t x = 0; x < dim_x; ++x) {
3038b3f7f69dSAidan Dodds         strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3039b9c1b51eSKate Stone         if ((type == Element::RS_TYPE_NONE) &&
3040b9c1b51eSKate Stone             (alloc->element.children.size() > 0) &&
3041b9c1b51eSKate Stone             (alloc->element.type_name != Element::GetFallbackStructName())) {
30428b244e21SEwan Crawford           // Here we are dumping an Element of struct type.
3043b9c1b51eSKate Stone           // This is done using expression evaluation with the name of the
3044b9c1b51eSKate Stone           // struct type and pointer to element.
30458b244e21SEwan Crawford 
3046b9c1b51eSKate Stone           // Don't print the name of the resulting expression, since this will
3047b9c1b51eSKate Stone           // be '$[0-9]+'
30488b244e21SEwan Crawford           DumpValueObjectOptions expr_options;
30498b244e21SEwan Crawford           expr_options.SetHideName(true);
30508b244e21SEwan Crawford 
30518b244e21SEwan Crawford           // Setup expression as derefrencing a pointer cast to element address.
3052ea0636b5SEwan Crawford           char expr_char_buffer[jit_max_expr_size];
3053b9c1b51eSKate Stone           int chars_written =
3054b9c1b51eSKate Stone               snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3055b9c1b51eSKate Stone                        alloc->element.type_name.AsCString(),
3056b9c1b51eSKate Stone                        *alloc->data_ptr.get() + offset);
30578b244e21SEwan Crawford 
3058b9c1b51eSKate Stone           if (chars_written < 0 || chars_written >= jit_max_expr_size) {
30598b244e21SEwan Crawford             if (log)
3060b3f7f69dSAidan Dodds               log->Printf("%s - error in snprintf().", __FUNCTION__);
30618b244e21SEwan Crawford             continue;
30628b244e21SEwan Crawford           }
30638b244e21SEwan Crawford 
30648b244e21SEwan Crawford           // Evaluate expression
30658b244e21SEwan Crawford           ValueObjectSP expr_result;
3066b9c1b51eSKate Stone           GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3067b9c1b51eSKate Stone                                                        frame_ptr, expr_result);
30688b244e21SEwan Crawford 
30698b244e21SEwan Crawford           // Print the results to our stream.
30708b244e21SEwan Crawford           expr_result->Dump(strm, expr_options);
3071b9c1b51eSKate Stone         } else {
3072b9c1b51eSKate Stone           alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1,
3073b9c1b51eSKate Stone                           LLDB_INVALID_ADDRESS, 0, 0);
30748b244e21SEwan Crawford         }
30758b244e21SEwan Crawford         offset += data_size;
3076a0f08674SEwan Crawford       }
3077a0f08674SEwan Crawford     }
3078a0f08674SEwan Crawford   }
3079a0f08674SEwan Crawford   strm.EOL();
3080a0f08674SEwan Crawford 
3081a0f08674SEwan Crawford   return true;
3082a0f08674SEwan Crawford }
3083a0f08674SEwan Crawford 
3084b9c1b51eSKate Stone // Function recalculates all our cached information about allocations by jitting
3085b9c1b51eSKate Stone // the
30860d2bfcfbSEwan Crawford // RS runtime regarding each allocation we know about.
30870d2bfcfbSEwan Crawford // Returns true if all allocations could be recomputed, false otherwise.
3088b9c1b51eSKate Stone bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3089b9c1b51eSKate Stone                                                   StackFrame *frame_ptr) {
30900d2bfcfbSEwan Crawford   bool success = true;
3091b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
30920d2bfcfbSEwan Crawford     // JIT current allocation information
3093b9c1b51eSKate Stone     if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3094b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3095b9c1b51eSKate Stone                   "\n",
3096b9c1b51eSKate Stone                   alloc->id);
30970d2bfcfbSEwan Crawford       success = false;
30980d2bfcfbSEwan Crawford     }
30990d2bfcfbSEwan Crawford   }
31000d2bfcfbSEwan Crawford 
31010d2bfcfbSEwan Crawford   if (success)
31020d2bfcfbSEwan Crawford     strm.Printf("All allocations successfully recomputed");
31030d2bfcfbSEwan Crawford   strm.EOL();
31040d2bfcfbSEwan Crawford 
31050d2bfcfbSEwan Crawford   return success;
31060d2bfcfbSEwan Crawford }
31070d2bfcfbSEwan Crawford 
3108b649b005SEwan Crawford // Prints information regarding currently loaded allocations.
310915f2bd95SEwan Crawford // These details are gathered by jitting the runtime, which has as latency.
3110b9c1b51eSKate Stone // Index parameter specifies a single allocation ID to print, or a zero value to
3111b9c1b51eSKate Stone // print them all
3112b9c1b51eSKate Stone void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3113b9c1b51eSKate Stone                                           const uint32_t index) {
311415f2bd95SEwan Crawford   strm.Printf("RenderScript Allocations:");
311515f2bd95SEwan Crawford   strm.EOL();
311615f2bd95SEwan Crawford   strm.IndentMore();
311715f2bd95SEwan Crawford 
3118b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
3119b649b005SEwan Crawford     // index will only be zero if we want to print all allocations
3120b649b005SEwan Crawford     if (index != 0 && index != alloc->id)
3121b649b005SEwan Crawford       continue;
312215f2bd95SEwan Crawford 
312315f2bd95SEwan Crawford     // JIT current allocation information
3124b9c1b51eSKate Stone     if (alloc->shouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3125b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3126b9c1b51eSKate Stone                   alloc->id);
3127b3f7f69dSAidan Dodds       strm.EOL();
312815f2bd95SEwan Crawford       continue;
312915f2bd95SEwan Crawford     }
313015f2bd95SEwan Crawford 
3131b3f7f69dSAidan Dodds     strm.Printf("%" PRIu32 ":", alloc->id);
3132b3f7f69dSAidan Dodds     strm.EOL();
313315f2bd95SEwan Crawford     strm.IndentMore();
313415f2bd95SEwan Crawford 
313515f2bd95SEwan Crawford     strm.Indent("Context: ");
313615f2bd95SEwan Crawford     if (!alloc->context.isValid())
313715f2bd95SEwan Crawford       strm.Printf("unknown\n");
313815f2bd95SEwan Crawford     else
313915f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
314015f2bd95SEwan Crawford 
314115f2bd95SEwan Crawford     strm.Indent("Address: ");
314215f2bd95SEwan Crawford     if (!alloc->address.isValid())
314315f2bd95SEwan Crawford       strm.Printf("unknown\n");
314415f2bd95SEwan Crawford     else
314515f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
314615f2bd95SEwan Crawford 
314715f2bd95SEwan Crawford     strm.Indent("Data pointer: ");
314815f2bd95SEwan Crawford     if (!alloc->data_ptr.isValid())
314915f2bd95SEwan Crawford       strm.Printf("unknown\n");
315015f2bd95SEwan Crawford     else
315115f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
315215f2bd95SEwan Crawford 
315315f2bd95SEwan Crawford     strm.Indent("Dimensions: ");
315415f2bd95SEwan Crawford     if (!alloc->dimension.isValid())
315515f2bd95SEwan Crawford       strm.Printf("unknown\n");
315615f2bd95SEwan Crawford     else
3157b3f7f69dSAidan Dodds       strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3158b9c1b51eSKate Stone                   alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3159b9c1b51eSKate Stone                   alloc->dimension.get()->dim_3);
316015f2bd95SEwan Crawford 
316115f2bd95SEwan Crawford     strm.Indent("Data Type: ");
3162b9c1b51eSKate Stone     if (!alloc->element.type.isValid() ||
3163b9c1b51eSKate Stone         !alloc->element.type_vec_size.isValid())
316415f2bd95SEwan Crawford       strm.Printf("unknown\n");
3165b9c1b51eSKate Stone     else {
31668b244e21SEwan Crawford       const int vector_size = *alloc->element.type_vec_size.get();
31672e920715SEwan Crawford       Element::DataType type = *alloc->element.type.get();
316815f2bd95SEwan Crawford 
31698b244e21SEwan Crawford       if (!alloc->element.type_name.IsEmpty())
31708b244e21SEwan Crawford         strm.Printf("%s\n", alloc->element.type_name.AsCString());
3171b9c1b51eSKate Stone       else {
3172b9c1b51eSKate Stone         // Enum value isn't monotonous, so doesn't always index
3173b9c1b51eSKate Stone         // RsDataTypeToString array
31742e920715SEwan Crawford         if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3175b9c1b51eSKate Stone           type =
3176b9c1b51eSKate Stone               static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3177b3f7f69dSAidan Dodds                                              Element::RS_TYPE_MATRIX_2X2 + 1);
31782e920715SEwan Crawford 
3179b3f7f69dSAidan Dodds         if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3180b3f7f69dSAidan Dodds                      sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3181b3f7f69dSAidan Dodds             vector_size > 4 || vector_size < 1)
318215f2bd95SEwan Crawford           strm.Printf("invalid type\n");
318315f2bd95SEwan Crawford         else
3184b9c1b51eSKate Stone           strm.Printf(
3185b9c1b51eSKate Stone               "%s\n",
3186b9c1b51eSKate Stone               AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3187b3f7f69dSAidan Dodds                                                    [vector_size - 1]);
318815f2bd95SEwan Crawford       }
31892e920715SEwan Crawford     }
319015f2bd95SEwan Crawford 
319115f2bd95SEwan Crawford     strm.Indent("Data Kind: ");
31928b244e21SEwan Crawford     if (!alloc->element.type_kind.isValid())
319315f2bd95SEwan Crawford       strm.Printf("unknown\n");
3194b9c1b51eSKate Stone     else {
31958b244e21SEwan Crawford       const Element::DataKind kind = *alloc->element.type_kind.get();
31968b244e21SEwan Crawford       if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
319715f2bd95SEwan Crawford         strm.Printf("invalid kind\n");
319815f2bd95SEwan Crawford       else
3199b9c1b51eSKate Stone         strm.Printf(
3200b9c1b51eSKate Stone             "%s\n",
3201b9c1b51eSKate Stone             AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
320215f2bd95SEwan Crawford     }
320315f2bd95SEwan Crawford 
320415f2bd95SEwan Crawford     strm.EOL();
320515f2bd95SEwan Crawford     strm.IndentLess();
320615f2bd95SEwan Crawford   }
320715f2bd95SEwan Crawford   strm.IndentLess();
320815f2bd95SEwan Crawford }
320915f2bd95SEwan Crawford 
32107dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
3211b9c1b51eSKate Stone void RenderScriptRuntime::BreakOnModuleKernels(
3212b9c1b51eSKate Stone     const RSModuleDescriptorSP rsmodule_sp) {
3213b9c1b51eSKate Stone   for (const auto &kernel : rsmodule_sp->m_kernels) {
32147dc7771cSEwan Crawford     // Don't set breakpoint on 'root' kernel
32157dc7771cSEwan Crawford     if (strcmp(kernel.m_name.AsCString(), "root") == 0)
32167dc7771cSEwan Crawford       continue;
32177dc7771cSEwan Crawford 
32187dc7771cSEwan Crawford     CreateKernelBreakpoint(kernel.m_name);
32197dc7771cSEwan Crawford   }
32207dc7771cSEwan Crawford }
32217dc7771cSEwan Crawford 
32227dc7771cSEwan Crawford // Method is internally called by the 'kernel breakpoint all' command to
32237dc7771cSEwan Crawford // enable or disable breaking on all kernels.
32247dc7771cSEwan Crawford //
32257dc7771cSEwan Crawford // When do_break is true we want to enable this functionality.
32267dc7771cSEwan Crawford // When do_break is false we want to disable it.
3227b9c1b51eSKate Stone void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3228b9c1b51eSKate Stone   Log *log(
3229b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
32307dc7771cSEwan Crawford 
32317dc7771cSEwan Crawford   InitSearchFilter(target);
32327dc7771cSEwan Crawford 
32337dc7771cSEwan Crawford   // Set breakpoints on all the kernels
3234b9c1b51eSKate Stone   if (do_break && !m_breakAllKernels) {
32357dc7771cSEwan Crawford     m_breakAllKernels = true;
32367dc7771cSEwan Crawford 
32377dc7771cSEwan Crawford     for (const auto &module : m_rsmodules)
32387dc7771cSEwan Crawford       BreakOnModuleKernels(module);
32397dc7771cSEwan Crawford 
32407dc7771cSEwan Crawford     if (log)
3241b9c1b51eSKate Stone       log->Printf("%s(True) - breakpoints set on all currently loaded kernels.",
3242b9c1b51eSKate Stone                   __FUNCTION__);
3243b9c1b51eSKate Stone   } else if (!do_break &&
3244b9c1b51eSKate Stone              m_breakAllKernels) // Breakpoints won't be set on any new kernels.
32457dc7771cSEwan Crawford   {
32467dc7771cSEwan Crawford     m_breakAllKernels = false;
32477dc7771cSEwan Crawford 
32487dc7771cSEwan Crawford     if (log)
3249b9c1b51eSKate Stone       log->Printf("%s(False) - breakpoints no longer automatically set.",
3250b9c1b51eSKate Stone                   __FUNCTION__);
32517dc7771cSEwan Crawford   }
32527dc7771cSEwan Crawford }
32537dc7771cSEwan Crawford 
32547dc7771cSEwan Crawford // Given the name of a kernel this function creates a breakpoint using our
32557dc7771cSEwan Crawford // own breakpoint resolver, and returns the Breakpoint shared pointer.
32567dc7771cSEwan Crawford BreakpointSP
3257b9c1b51eSKate Stone RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) {
3258b9c1b51eSKate Stone   Log *log(
3259b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
32607dc7771cSEwan Crawford 
3261b9c1b51eSKate Stone   if (!m_filtersp) {
32627dc7771cSEwan Crawford     if (log)
3263b3f7f69dSAidan Dodds       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
32647dc7771cSEwan Crawford     return nullptr;
32657dc7771cSEwan Crawford   }
32667dc7771cSEwan Crawford 
32677dc7771cSEwan Crawford   BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3268b9c1b51eSKate Stone   BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
3269b9c1b51eSKate Stone       m_filtersp, resolver_sp, false, false, false);
32707dc7771cSEwan Crawford 
3271b9c1b51eSKate Stone   // Give RS breakpoints a specific name, so the user can manipulate them as a
3272b9c1b51eSKate Stone   // group.
327354782db7SEwan Crawford   Error err;
327454782db7SEwan Crawford   if (!bp->AddName("RenderScriptKernel", err) && log)
3275b9c1b51eSKate Stone     log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3276b9c1b51eSKate Stone                 err.AsCString());
327754782db7SEwan Crawford 
32787dc7771cSEwan Crawford   return bp;
32797dc7771cSEwan Crawford }
32807dc7771cSEwan Crawford 
3281b9c1b51eSKate Stone // Given an expression for a variable this function tries to calculate the
3282b9c1b51eSKate Stone // variable's value.
3283b9c1b51eSKate Stone // If this is possible it returns true and sets the uint64_t parameter to the
3284b9c1b51eSKate Stone // variables unsigned value.
3285018f5a7eSEwan Crawford // Otherwise function returns false.
3286b9c1b51eSKate Stone bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3287b9c1b51eSKate Stone                                                 const char *var_name,
3288b9c1b51eSKate Stone                                                 uint64_t &val) {
3289018f5a7eSEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3290018f5a7eSEwan Crawford   Error error;
3291018f5a7eSEwan Crawford   VariableSP var_sp;
3292018f5a7eSEwan Crawford 
3293018f5a7eSEwan Crawford   // Find variable in stack frame
3294b3f7f69dSAidan Dodds   ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3295b3f7f69dSAidan Dodds       var_name, eNoDynamicValues,
3296b9c1b51eSKate Stone       StackFrame::eExpressionPathOptionCheckPtrVsMember |
3297b9c1b51eSKate Stone           StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3298b3f7f69dSAidan Dodds       var_sp, error));
3299b9c1b51eSKate Stone   if (!error.Success()) {
3300018f5a7eSEwan Crawford     if (log)
3301b9c1b51eSKate Stone       log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__,
3302b9c1b51eSKate Stone                   var_name);
3303018f5a7eSEwan Crawford     return false;
3304018f5a7eSEwan Crawford   }
3305018f5a7eSEwan Crawford 
3306b3f7f69dSAidan Dodds   // Find the uint32_t value for the variable
3307018f5a7eSEwan Crawford   bool success = false;
3308018f5a7eSEwan Crawford   val = value_sp->GetValueAsUnsigned(0, &success);
3309b9c1b51eSKate Stone   if (!success) {
3310018f5a7eSEwan Crawford     if (log)
3311b9c1b51eSKate Stone       log->Printf("%s - error, couldn't parse '%s' as an uint32_t.",
3312b9c1b51eSKate Stone                   __FUNCTION__, var_name);
3313018f5a7eSEwan Crawford     return false;
3314018f5a7eSEwan Crawford   }
3315018f5a7eSEwan Crawford 
3316018f5a7eSEwan Crawford   return true;
3317018f5a7eSEwan Crawford }
3318018f5a7eSEwan Crawford 
3319b9c1b51eSKate Stone // Function attempts to find the current coordinate of a kernel invocation by
3320b9c1b51eSKate Stone // investigating the
3321b9c1b51eSKate Stone // values of frame variables in the .expand function. These coordinates are
3322b9c1b51eSKate Stone // returned via the coord
3323b9c1b51eSKate Stone // array reference parameter. Returns true if the coordinates could be found,
3324b9c1b51eSKate Stone // and false otherwise.
3325b9c1b51eSKate Stone bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3326b9c1b51eSKate Stone                                               Thread *thread_ptr) {
3327*00f56eebSLuke Drummond   static const char *const x_expr = "rsIndex";
3328*00f56eebSLuke Drummond   static const char *const y_expr = "p->current.y";
3329*00f56eebSLuke Drummond   static const char *const z_expr = "p->current.z";
33301e05c3bcSGreg Clayton 
33314f8817c2SEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
33324f8817c2SEwan Crawford 
3333b9c1b51eSKate Stone   if (!thread_ptr) {
33344f8817c2SEwan Crawford     if (log)
33354f8817c2SEwan Crawford       log->Printf("%s - Error, No thread pointer", __FUNCTION__);
33364f8817c2SEwan Crawford 
33374f8817c2SEwan Crawford     return false;
33384f8817c2SEwan Crawford   }
33394f8817c2SEwan Crawford 
3340b9c1b51eSKate Stone   // Walk the call stack looking for a function whose name has the suffix
3341b9c1b51eSKate Stone   // '.expand'
33424f8817c2SEwan Crawford   // and contains the variables we're looking for.
3343b9c1b51eSKate Stone   for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
33444f8817c2SEwan Crawford     if (!thread_ptr->SetSelectedFrameByIndex(i))
33454f8817c2SEwan Crawford       continue;
33464f8817c2SEwan Crawford 
33474f8817c2SEwan Crawford     StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
33484f8817c2SEwan Crawford     if (!frame_sp)
33494f8817c2SEwan Crawford       continue;
33504f8817c2SEwan Crawford 
33514f8817c2SEwan Crawford     // Find the function name
33524f8817c2SEwan Crawford     const SymbolContext sym_ctx = frame_sp->GetSymbolContext(false);
3353*00f56eebSLuke Drummond     const ConstString func_name = sym_ctx.GetFunctionName();
3354*00f56eebSLuke Drummond     if (!func_name)
33554f8817c2SEwan Crawford       continue;
33564f8817c2SEwan Crawford 
33574f8817c2SEwan Crawford     if (log)
3358b9c1b51eSKate Stone       log->Printf("%s - Inspecting function '%s'", __FUNCTION__,
3359*00f56eebSLuke Drummond                   func_name.GetCString());
33604f8817c2SEwan Crawford 
33614f8817c2SEwan Crawford     // Check if function name has .expand suffix
3362*00f56eebSLuke Drummond     if (!func_name.GetStringRef().endswith(".expand"))
33634f8817c2SEwan Crawford       continue;
33644f8817c2SEwan Crawford 
33654f8817c2SEwan Crawford     if (log)
3366b9c1b51eSKate Stone       log->Printf("%s - Found .expand function '%s'", __FUNCTION__,
3367*00f56eebSLuke Drummond                   func_name.GetCString());
33684f8817c2SEwan Crawford 
3369b9c1b51eSKate Stone     // Get values for variables in .expand frame that tell us the current kernel
3370b9c1b51eSKate Stone     // invocation
3371*00f56eebSLuke Drummond     uint64_t x, y, z;
3372*00f56eebSLuke Drummond     bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
3373*00f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
3374*00f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, z_expr, z);
33754f8817c2SEwan Crawford 
3376*00f56eebSLuke Drummond     if (found) {
3377*00f56eebSLuke Drummond       // The RenderScript runtime uses uint32_t for these vars. If they're not
3378*00f56eebSLuke Drummond       // within bounds, our frame parsing is garbage
3379*00f56eebSLuke Drummond       assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
3380*00f56eebSLuke Drummond       coord.x = (uint32_t)x;
3381*00f56eebSLuke Drummond       coord.y = (uint32_t)y;
3382*00f56eebSLuke Drummond       coord.z = (uint32_t)z;
33834f8817c2SEwan Crawford       return true;
33844f8817c2SEwan Crawford     }
3385*00f56eebSLuke Drummond   }
33864f8817c2SEwan Crawford   return false;
33874f8817c2SEwan Crawford }
33884f8817c2SEwan Crawford 
3389b9c1b51eSKate Stone // Callback when a kernel breakpoint hits and we're looking for a specific
3390b9c1b51eSKate Stone // coordinate.
3391b9c1b51eSKate Stone // Baton parameter contains a pointer to the target coordinate we want to break
3392b9c1b51eSKate Stone // on.
3393b9c1b51eSKate Stone // Function then checks the .expand frame for the current coordinate and breaks
3394b9c1b51eSKate Stone // to user if it matches.
3395018f5a7eSEwan Crawford // Parameter 'break_id' is the id of the Breakpoint which made the callback.
3396018f5a7eSEwan Crawford // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
3397018f5a7eSEwan Crawford // a single logical breakpoint can have multiple addresses.
3398b9c1b51eSKate Stone bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3399b9c1b51eSKate Stone                                               StoppointCallbackContext *ctx,
3400b9c1b51eSKate Stone                                               user_id_t break_id,
3401b9c1b51eSKate Stone                                               user_id_t break_loc_id) {
3402b9c1b51eSKate Stone   Log *log(
3403b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3404018f5a7eSEwan Crawford 
3405b9c1b51eSKate Stone   assert(baton &&
3406b9c1b51eSKate Stone          "Error: null baton in conditional kernel breakpoint callback");
3407018f5a7eSEwan Crawford 
3408018f5a7eSEwan Crawford   // Coordinate we want to stop on
3409*00f56eebSLuke Drummond   RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3410018f5a7eSEwan Crawford 
3411018f5a7eSEwan Crawford   if (log)
3412*00f56eebSLuke Drummond     log->Printf("%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__, break_id,
3413*00f56eebSLuke Drummond                 target_coord.x, target_coord.y, target_coord.z);
3414018f5a7eSEwan Crawford 
34154f8817c2SEwan Crawford   // Select current thread
3416018f5a7eSEwan Crawford   ExecutionContext context(ctx->exe_ctx_ref);
34174f8817c2SEwan Crawford   Thread *thread_ptr = context.GetThreadPtr();
34184f8817c2SEwan Crawford   assert(thread_ptr && "Null thread pointer");
34194f8817c2SEwan Crawford 
34204f8817c2SEwan Crawford   // Find current kernel invocation from .expand frame variables
3421*00f56eebSLuke Drummond   RSCoordinate current_coord{};
3422b9c1b51eSKate Stone   if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3423018f5a7eSEwan Crawford     if (log)
3424b9c1b51eSKate Stone       log->Printf("%s - Error, couldn't select .expand stack frame",
3425b9c1b51eSKate Stone                   __FUNCTION__);
3426018f5a7eSEwan Crawford     return false;
3427018f5a7eSEwan Crawford   }
3428018f5a7eSEwan Crawford 
3429018f5a7eSEwan Crawford   if (log)
3430*00f56eebSLuke Drummond     log->Printf("%s - " FMT_COORD, __FUNCTION__, current_coord.x,
3431*00f56eebSLuke Drummond                 current_coord.y, current_coord.z);
3432018f5a7eSEwan Crawford 
3433b9c1b51eSKate Stone   // Check if the current kernel invocation coordinate matches our target
3434b9c1b51eSKate Stone   // coordinate
3435*00f56eebSLuke Drummond   if (target_coord == current_coord) {
3436018f5a7eSEwan Crawford     if (log)
3437*00f56eebSLuke Drummond       log->Printf("%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
3438*00f56eebSLuke Drummond                   current_coord.y, current_coord.z);
3439018f5a7eSEwan Crawford 
3440b9c1b51eSKate Stone     BreakpointSP breakpoint_sp =
3441b9c1b51eSKate Stone         context.GetTargetPtr()->GetBreakpointByID(break_id);
3442b9c1b51eSKate Stone     assert(breakpoint_sp != nullptr &&
3443b9c1b51eSKate Stone            "Error: Couldn't find breakpoint matching break id for callback");
3444b9c1b51eSKate Stone     breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3445b9c1b51eSKate Stone                                       // should only be hit once.
3446018f5a7eSEwan Crawford     return true;
3447018f5a7eSEwan Crawford   }
3448018f5a7eSEwan Crawford 
3449018f5a7eSEwan Crawford   // No match on coordinate
3450018f5a7eSEwan Crawford   return false;
3451018f5a7eSEwan Crawford }
3452018f5a7eSEwan Crawford 
3453*00f56eebSLuke Drummond void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
3454*00f56eebSLuke Drummond                                          const RSCoordinate &coord) {
3455*00f56eebSLuke Drummond   messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
3456*00f56eebSLuke Drummond                   coord.x, coord.y, coord.z);
3457*00f56eebSLuke Drummond   messages.EOL();
3458*00f56eebSLuke Drummond 
3459*00f56eebSLuke Drummond   // Allocate memory for the baton, and copy over coordinate
3460*00f56eebSLuke Drummond   RSCoordinate *baton = new RSCoordinate(coord);
3461*00f56eebSLuke Drummond 
3462*00f56eebSLuke Drummond   // Create a callback that will be invoked every time the breakpoint is hit.
3463*00f56eebSLuke Drummond   // The baton object passed to the handler is the target coordinate we want to
3464*00f56eebSLuke Drummond   // break on.
3465*00f56eebSLuke Drummond   bp->SetCallback(KernelBreakpointHit, baton, true);
3466*00f56eebSLuke Drummond 
3467*00f56eebSLuke Drummond   // Store a shared pointer to the baton, so the memory will eventually be
3468*00f56eebSLuke Drummond   // cleaned up after destruction
3469*00f56eebSLuke Drummond   m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
3470*00f56eebSLuke Drummond }
3471*00f56eebSLuke Drummond 
3472b9c1b51eSKate Stone // Tries to set a breakpoint on the start of a kernel, resolved using the kernel
3473b9c1b51eSKate Stone // name.
3474b9c1b51eSKate Stone // Argument 'coords', represents a three dimensional coordinate which can be
3475b9c1b51eSKate Stone // used to specify
3476b9c1b51eSKate Stone // a single kernel instance to break on. If this is set then we add a callback
3477b9c1b51eSKate Stone // to the breakpoint.
3478*00f56eebSLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
3479*00f56eebSLuke Drummond                                                   Stream &messages,
3480*00f56eebSLuke Drummond                                                   const char *name,
3481*00f56eebSLuke Drummond                                                   const RSCoordinate *coord) {
3482*00f56eebSLuke Drummond   if (!name)
3483*00f56eebSLuke Drummond     return false;
34844640cde1SColin Riley 
34857dc7771cSEwan Crawford   InitSearchFilter(target);
348698156583SEwan Crawford 
34874640cde1SColin Riley   ConstString kernel_name(name);
34887dc7771cSEwan Crawford   BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
3489*00f56eebSLuke Drummond   if (!bp)
3490*00f56eebSLuke Drummond     return false;
3491018f5a7eSEwan Crawford 
3492018f5a7eSEwan Crawford   // We have a conditional breakpoint on a specific coordinate
3493*00f56eebSLuke Drummond   if (coord)
3494*00f56eebSLuke Drummond     SetConditional(bp, messages, *coord);
3495018f5a7eSEwan Crawford 
3496*00f56eebSLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3497018f5a7eSEwan Crawford 
3498*00f56eebSLuke Drummond   return true;
34994640cde1SColin Riley }
35004640cde1SColin Riley 
3501b9c1b51eSKate Stone void RenderScriptRuntime::DumpModules(Stream &strm) const {
35025ec532a9SColin Riley   strm.Printf("RenderScript Modules:");
35035ec532a9SColin Riley   strm.EOL();
35045ec532a9SColin Riley   strm.IndentMore();
3505b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
35064640cde1SColin Riley     module->Dump(strm);
35075ec532a9SColin Riley   }
35085ec532a9SColin Riley   strm.IndentLess();
35095ec532a9SColin Riley }
35105ec532a9SColin Riley 
351178f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails *
3512b9c1b51eSKate Stone RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3513b9c1b51eSKate Stone   for (const auto &s : m_scripts) {
351478f339d1SEwan Crawford     if (s->script.isValid())
351578f339d1SEwan Crawford       if (*s->script == address)
351678f339d1SEwan Crawford         return s.get();
351778f339d1SEwan Crawford   }
3518b9c1b51eSKate Stone   if (create) {
351978f339d1SEwan Crawford     std::unique_ptr<ScriptDetails> s(new ScriptDetails);
352078f339d1SEwan Crawford     s->script = address;
352178f339d1SEwan Crawford     m_scripts.push_back(std::move(s));
3522d10ca9deSEwan Crawford     return m_scripts.back().get();
352378f339d1SEwan Crawford   }
352478f339d1SEwan Crawford   return nullptr;
352578f339d1SEwan Crawford }
352678f339d1SEwan Crawford 
352778f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails *
3528b9c1b51eSKate Stone RenderScriptRuntime::LookUpAllocation(addr_t address) {
3529b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
353078f339d1SEwan Crawford     if (a->address.isValid())
353178f339d1SEwan Crawford       if (*a->address == address)
353278f339d1SEwan Crawford         return a.get();
353378f339d1SEwan Crawford   }
35345d057637SLuke Drummond   return nullptr;
35355d057637SLuke Drummond }
35365d057637SLuke Drummond 
35375d057637SLuke Drummond RenderScriptRuntime::AllocationDetails *
3538b9c1b51eSKate Stone RenderScriptRuntime::CreateAllocation(addr_t address) {
35395d057637SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
35405d057637SLuke Drummond 
35415d057637SLuke Drummond   // Remove any previous allocation which contains the same address
35425d057637SLuke Drummond   auto it = m_allocations.begin();
3543b9c1b51eSKate Stone   while (it != m_allocations.end()) {
3544b9c1b51eSKate Stone     if (*((*it)->address) == address) {
35455d057637SLuke Drummond       if (log)
3546b9c1b51eSKate Stone         log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64,
3547b9c1b51eSKate Stone                     __FUNCTION__, (*it)->id, address);
35485d057637SLuke Drummond 
35495d057637SLuke Drummond       it = m_allocations.erase(it);
3550b9c1b51eSKate Stone     } else {
35515d057637SLuke Drummond       it++;
35525d057637SLuke Drummond     }
35535d057637SLuke Drummond   }
35545d057637SLuke Drummond 
355578f339d1SEwan Crawford   std::unique_ptr<AllocationDetails> a(new AllocationDetails);
355678f339d1SEwan Crawford   a->address = address;
355778f339d1SEwan Crawford   m_allocations.push_back(std::move(a));
3558d10ca9deSEwan Crawford   return m_allocations.back().get();
355978f339d1SEwan Crawford }
356078f339d1SEwan Crawford 
3561b9c1b51eSKate Stone void RSModuleDescriptor::Dump(Stream &strm) const {
35627f193d69SLuke Drummond   int indent = strm.GetIndentLevel();
35637f193d69SLuke Drummond 
35645ec532a9SColin Riley   strm.Indent();
35655ec532a9SColin Riley   m_module->GetFileSpec().Dump(&strm);
35667f193d69SLuke Drummond   strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
35677f193d69SLuke Drummond                                              : "Debug info does not exist.");
35685ec532a9SColin Riley   strm.EOL();
35695ec532a9SColin Riley   strm.IndentMore();
35707f193d69SLuke Drummond 
35715ec532a9SColin Riley   strm.Indent();
3572189598edSColin Riley   strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
35735ec532a9SColin Riley   strm.EOL();
35745ec532a9SColin Riley   strm.IndentMore();
3575b9c1b51eSKate Stone   for (const auto &global : m_globals) {
35765ec532a9SColin Riley     global.Dump(strm);
35775ec532a9SColin Riley   }
35785ec532a9SColin Riley   strm.IndentLess();
35797f193d69SLuke Drummond 
35805ec532a9SColin Riley   strm.Indent();
3581189598edSColin Riley   strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
35825ec532a9SColin Riley   strm.EOL();
35835ec532a9SColin Riley   strm.IndentMore();
3584b9c1b51eSKate Stone   for (const auto &kernel : m_kernels) {
35855ec532a9SColin Riley     kernel.Dump(strm);
35865ec532a9SColin Riley   }
35877f193d69SLuke Drummond   strm.IndentLess();
35887f193d69SLuke Drummond 
35897f193d69SLuke Drummond   strm.Indent();
35904640cde1SColin Riley   strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
35914640cde1SColin Riley   strm.EOL();
35924640cde1SColin Riley   strm.IndentMore();
3593b9c1b51eSKate Stone   for (const auto &key_val : m_pragmas) {
35947f193d69SLuke Drummond     strm.Indent();
35954640cde1SColin Riley     strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
35964640cde1SColin Riley     strm.EOL();
35974640cde1SColin Riley   }
35987f193d69SLuke Drummond   strm.IndentLess();
35997f193d69SLuke Drummond 
36007f193d69SLuke Drummond   strm.Indent();
36017f193d69SLuke Drummond   strm.Printf("Reductions: %" PRIu64,
36027f193d69SLuke Drummond               static_cast<uint64_t>(m_reductions.size()));
36037f193d69SLuke Drummond   strm.EOL();
36047f193d69SLuke Drummond   strm.IndentMore();
36057f193d69SLuke Drummond   for (const auto &reduction : m_reductions) {
36067f193d69SLuke Drummond     reduction.Dump(strm);
36077f193d69SLuke Drummond   }
36087f193d69SLuke Drummond 
36097f193d69SLuke Drummond   strm.SetIndentLevel(indent);
36105ec532a9SColin Riley }
36115ec532a9SColin Riley 
3612b9c1b51eSKate Stone void RSGlobalDescriptor::Dump(Stream &strm) const {
36135ec532a9SColin Riley   strm.Indent(m_name.AsCString());
36144640cde1SColin Riley   VariableList var_list;
36154640cde1SColin Riley   m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
3616b9c1b51eSKate Stone   if (var_list.GetSize() == 1) {
36174640cde1SColin Riley     auto var = var_list.GetVariableAtIndex(0);
36184640cde1SColin Riley     auto type = var->GetType();
3619b9c1b51eSKate Stone     if (type) {
36204640cde1SColin Riley       strm.Printf(" - ");
36214640cde1SColin Riley       type->DumpTypeName(&strm);
3622b9c1b51eSKate Stone     } else {
36234640cde1SColin Riley       strm.Printf(" - Unknown Type");
36244640cde1SColin Riley     }
3625b9c1b51eSKate Stone   } else {
36264640cde1SColin Riley     strm.Printf(" - variable identified, but not found in binary");
3627b9c1b51eSKate Stone     const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
3628b9c1b51eSKate Stone         m_name, eSymbolTypeData);
3629b9c1b51eSKate Stone     if (s) {
36304640cde1SColin Riley       strm.Printf(" (symbol exists) ");
36314640cde1SColin Riley     }
36324640cde1SColin Riley   }
36334640cde1SColin Riley 
36345ec532a9SColin Riley   strm.EOL();
36355ec532a9SColin Riley }
36365ec532a9SColin Riley 
3637b9c1b51eSKate Stone void RSKernelDescriptor::Dump(Stream &strm) const {
36385ec532a9SColin Riley   strm.Indent(m_name.AsCString());
36395ec532a9SColin Riley   strm.EOL();
36405ec532a9SColin Riley }
36415ec532a9SColin Riley 
36427f193d69SLuke Drummond void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
36437f193d69SLuke Drummond   stream.Indent(m_reduce_name.AsCString());
36447f193d69SLuke Drummond   stream.IndentMore();
36457f193d69SLuke Drummond   stream.EOL();
36467f193d69SLuke Drummond   stream.Indent();
36477f193d69SLuke Drummond   stream.Printf("accumulator: %s", m_accum_name.AsCString());
36487f193d69SLuke Drummond   stream.EOL();
36497f193d69SLuke Drummond   stream.Indent();
36507f193d69SLuke Drummond   stream.Printf("initializer: %s", m_init_name.AsCString());
36517f193d69SLuke Drummond   stream.EOL();
36527f193d69SLuke Drummond   stream.Indent();
36537f193d69SLuke Drummond   stream.Printf("combiner: %s", m_comb_name.AsCString());
36547f193d69SLuke Drummond   stream.EOL();
36557f193d69SLuke Drummond   stream.Indent();
36567f193d69SLuke Drummond   stream.Printf("outconverter: %s", m_outc_name.AsCString());
36577f193d69SLuke Drummond   stream.EOL();
36587f193d69SLuke Drummond   // XXX This is currently unspecified by RenderScript, and unused
36597f193d69SLuke Drummond   // stream.Indent();
36607f193d69SLuke Drummond   // stream.Printf("halter: '%s'", m_init_name.AsCString());
36617f193d69SLuke Drummond   // stream.EOL();
36627f193d69SLuke Drummond   stream.IndentLess();
36637f193d69SLuke Drummond }
36647f193d69SLuke Drummond 
3665b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
36665ec532a9SColin Riley public:
36675ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
3668b9c1b51eSKate Stone       : CommandObjectParsed(
3669b9c1b51eSKate Stone             interpreter, "renderscript module dump",
3670b9c1b51eSKate Stone             "Dumps renderscript specific information for all modules.",
3671b9c1b51eSKate Stone             "renderscript module dump",
3672b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
36735ec532a9SColin Riley 
3674222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
36755ec532a9SColin Riley 
3676b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
36775ec532a9SColin Riley     RenderScriptRuntime *runtime =
3678b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
3679b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
36805ec532a9SColin Riley     runtime->DumpModules(result.GetOutputStream());
36815ec532a9SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
36825ec532a9SColin Riley     return true;
36835ec532a9SColin Riley   }
36845ec532a9SColin Riley };
36855ec532a9SColin Riley 
3686b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
36875ec532a9SColin Riley public:
36885ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
3689b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript module",
3690b9c1b51eSKate Stone                                "Commands that deal with RenderScript modules.",
3691b9c1b51eSKate Stone                                nullptr) {
3692b9c1b51eSKate Stone     LoadSubCommand(
3693b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
3694b9c1b51eSKate Stone                     interpreter)));
36955ec532a9SColin Riley   }
36965ec532a9SColin Riley 
3697222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModule() override = default;
36985ec532a9SColin Riley };
36995ec532a9SColin Riley 
3700b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
37014640cde1SColin Riley public:
37024640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
3703b9c1b51eSKate Stone       : CommandObjectParsed(
3704b9c1b51eSKate Stone             interpreter, "renderscript kernel list",
3705b3f7f69dSAidan Dodds             "Lists renderscript kernel names and associated script resources.",
3706b9c1b51eSKate Stone             "renderscript kernel list",
3707b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
37084640cde1SColin Riley 
3709222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelList() override = default;
37104640cde1SColin Riley 
3711b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
37124640cde1SColin Riley     RenderScriptRuntime *runtime =
3713b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
3714b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
37154640cde1SColin Riley     runtime->DumpKernels(result.GetOutputStream());
37164640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
37174640cde1SColin Riley     return true;
37184640cde1SColin Riley   }
37194640cde1SColin Riley };
37204640cde1SColin Riley 
37211f0f5b5bSZachary Turner static OptionDefinition g_renderscript_kernel_bp_set_options[] = {
37221f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
37231f0f5b5bSZachary Turner      nullptr, nullptr, 0, eArgTypeValue,
37241f0f5b5bSZachary Turner      "Set a breakpoint on a single invocation of the kernel with specified "
37251f0f5b5bSZachary Turner      "coordinate.\n"
37261f0f5b5bSZachary Turner      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
37271f0f5b5bSZachary Turner      "integers representing kernel dimensions. "
37281f0f5b5bSZachary Turner      "Any unset dimensions will be defaulted to zero."}};
37291f0f5b5bSZachary Turner 
3730b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointSet
3731b9c1b51eSKate Stone     : public CommandObjectParsed {
37324640cde1SColin Riley public:
3733b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointSet(
3734b9c1b51eSKate Stone       CommandInterpreter &interpreter)
3735b9c1b51eSKate Stone       : CommandObjectParsed(
3736b9c1b51eSKate Stone             interpreter, "renderscript kernel breakpoint set",
3737b3f7f69dSAidan Dodds             "Sets a breakpoint on a renderscript kernel.",
3738b3f7f69dSAidan Dodds             "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
3739b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
3740b9c1b51eSKate Stone                 eCommandProcessMustBePaused),
3741b9c1b51eSKate Stone         m_options() {}
37424640cde1SColin Riley 
3743222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
3744222b937cSEugene Zelenko 
3745b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
3746018f5a7eSEwan Crawford 
3747b9c1b51eSKate Stone   class CommandOptions : public Options {
3748018f5a7eSEwan Crawford   public:
3749e1cfbc79STodd Fiala     CommandOptions() : Options() {}
3750018f5a7eSEwan Crawford 
3751222b937cSEugene Zelenko     ~CommandOptions() override = default;
3752018f5a7eSEwan Crawford 
3753b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
3754b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
3755018f5a7eSEwan Crawford       Error error;
3756018f5a7eSEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
3757018f5a7eSEwan Crawford 
3758b9c1b51eSKate Stone       switch (short_option) {
3759*00f56eebSLuke Drummond       case 'c': {
3760*00f56eebSLuke Drummond         auto coord = RSCoordinate{};
3761*00f56eebSLuke Drummond         if (!ParseCoordinate(option_arg, coord))
3762b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
3763b9c1b51eSKate Stone               "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
3764b3f7f69dSAidan Dodds               option_arg);
3765*00f56eebSLuke Drummond         else {
3766*00f56eebSLuke Drummond           m_have_coord = true;
3767*00f56eebSLuke Drummond           m_coord = coord;
3768*00f56eebSLuke Drummond         }
3769018f5a7eSEwan Crawford         break;
3770*00f56eebSLuke Drummond       }
3771018f5a7eSEwan Crawford       default:
3772b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
3773b9c1b51eSKate Stone                                        short_option);
3774018f5a7eSEwan Crawford         break;
3775018f5a7eSEwan Crawford       }
3776018f5a7eSEwan Crawford       return error;
3777018f5a7eSEwan Crawford     }
3778018f5a7eSEwan Crawford 
3779b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
3780*00f56eebSLuke Drummond       m_have_coord = false;
3781018f5a7eSEwan Crawford     }
3782018f5a7eSEwan Crawford 
37831f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
378470602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
37851f0f5b5bSZachary Turner     }
3786018f5a7eSEwan Crawford 
3787*00f56eebSLuke Drummond     RSCoordinate m_coord;
3788*00f56eebSLuke Drummond     bool m_have_coord;
3789018f5a7eSEwan Crawford   };
3790018f5a7eSEwan Crawford 
3791b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
37924640cde1SColin Riley     const size_t argc = command.GetArgumentCount();
3793b9c1b51eSKate Stone     if (argc < 1) {
3794b9c1b51eSKate Stone       result.AppendErrorWithFormat(
3795b9c1b51eSKate Stone           "'%s' takes 1 argument of kernel name, and an optional coordinate.",
3796b3f7f69dSAidan Dodds           m_cmd_name.c_str());
3797018f5a7eSEwan Crawford       result.SetStatus(eReturnStatusFailed);
3798018f5a7eSEwan Crawford       return false;
3799018f5a7eSEwan Crawford     }
3800018f5a7eSEwan Crawford 
38014640cde1SColin Riley     RenderScriptRuntime *runtime =
3802b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
3803b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
38044640cde1SColin Riley 
3805*00f56eebSLuke Drummond     auto &outstream = result.GetOutputStream();
3806*00f56eebSLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
3807*00f56eebSLuke Drummond     auto name = command.GetArgumentAtIndex(0);
3808*00f56eebSLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
3809*00f56eebSLuke Drummond     if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
3810*00f56eebSLuke Drummond       result.SetStatus(eReturnStatusFailed);
3811*00f56eebSLuke Drummond       result.AppendErrorWithFormat(
3812*00f56eebSLuke Drummond           "Error: unable to set breakpoint on kernel '%s'", name);
3813*00f56eebSLuke Drummond       return false;
3814*00f56eebSLuke Drummond     }
38154640cde1SColin Riley 
38164640cde1SColin Riley     result.AppendMessage("Breakpoint(s) created");
38174640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
38184640cde1SColin Riley     return true;
38194640cde1SColin Riley   }
38204640cde1SColin Riley 
3821018f5a7eSEwan Crawford private:
3822018f5a7eSEwan Crawford   CommandOptions m_options;
38234640cde1SColin Riley };
38244640cde1SColin Riley 
3825b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointAll
3826b9c1b51eSKate Stone     : public CommandObjectParsed {
38277dc7771cSEwan Crawford public:
3828b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointAll(
3829b9c1b51eSKate Stone       CommandInterpreter &interpreter)
3830b3f7f69dSAidan Dodds       : CommandObjectParsed(
3831b3f7f69dSAidan Dodds             interpreter, "renderscript kernel breakpoint all",
3832b9c1b51eSKate Stone             "Automatically sets a breakpoint on all renderscript kernels that "
3833b9c1b51eSKate Stone             "are or will be loaded.\n"
3834b9c1b51eSKate Stone             "Disabling option means breakpoints will no longer be set on any "
3835b9c1b51eSKate Stone             "kernels loaded in the future, "
38367dc7771cSEwan Crawford             "but does not remove currently set breakpoints.",
38377dc7771cSEwan Crawford             "renderscript kernel breakpoint all <enable/disable>",
3838b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
3839b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
38407dc7771cSEwan Crawford 
3841222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
38427dc7771cSEwan Crawford 
3843b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
38447dc7771cSEwan Crawford     const size_t argc = command.GetArgumentCount();
3845b9c1b51eSKate Stone     if (argc != 1) {
3846b9c1b51eSKate Stone       result.AppendErrorWithFormat(
3847b9c1b51eSKate Stone           "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
38487dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
38497dc7771cSEwan Crawford       return false;
38507dc7771cSEwan Crawford     }
38517dc7771cSEwan Crawford 
3852b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
3853b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
3854b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
38557dc7771cSEwan Crawford 
38567dc7771cSEwan Crawford     bool do_break = false;
38577dc7771cSEwan Crawford     const char *argument = command.GetArgumentAtIndex(0);
3858b9c1b51eSKate Stone     if (strcmp(argument, "enable") == 0) {
38597dc7771cSEwan Crawford       do_break = true;
38607dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will be set on all kernels.");
3861b9c1b51eSKate Stone     } else if (strcmp(argument, "disable") == 0) {
38627dc7771cSEwan Crawford       do_break = false;
38637dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will not be set on any new kernels.");
3864b9c1b51eSKate Stone     } else {
3865b9c1b51eSKate Stone       result.AppendErrorWithFormat(
3866b9c1b51eSKate Stone           "Argument must be either 'enable' or 'disable'");
38677dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
38687dc7771cSEwan Crawford       return false;
38697dc7771cSEwan Crawford     }
38707dc7771cSEwan Crawford 
38717dc7771cSEwan Crawford     runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
38727dc7771cSEwan Crawford 
38737dc7771cSEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
38747dc7771cSEwan Crawford     return true;
38757dc7771cSEwan Crawford   }
38767dc7771cSEwan Crawford };
38777dc7771cSEwan Crawford 
3878b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelCoordinate
3879b9c1b51eSKate Stone     : public CommandObjectParsed {
38804f8817c2SEwan Crawford public:
3881b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelCoordinate(
3882b9c1b51eSKate Stone       CommandInterpreter &interpreter)
3883b9c1b51eSKate Stone       : CommandObjectParsed(
3884b9c1b51eSKate Stone             interpreter, "renderscript kernel coordinate",
38854f8817c2SEwan Crawford             "Shows the (x,y,z) coordinate of the current kernel invocation.",
38864f8817c2SEwan Crawford             "renderscript kernel coordinate",
3887b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
3888b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
38894f8817c2SEwan Crawford 
38904f8817c2SEwan Crawford   ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
38914f8817c2SEwan Crawford 
3892b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
3893*00f56eebSLuke Drummond     RSCoordinate coord{};
3894b9c1b51eSKate Stone     bool success = RenderScriptRuntime::GetKernelCoordinate(
3895b9c1b51eSKate Stone         coord, m_exe_ctx.GetThreadPtr());
38964f8817c2SEwan Crawford     Stream &stream = result.GetOutputStream();
38974f8817c2SEwan Crawford 
3898b9c1b51eSKate Stone     if (success) {
3899*00f56eebSLuke Drummond       stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
39004f8817c2SEwan Crawford       stream.EOL();
39014f8817c2SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
3902b9c1b51eSKate Stone     } else {
39034f8817c2SEwan Crawford       stream.Printf("Error: Coordinate could not be found.");
39044f8817c2SEwan Crawford       stream.EOL();
39054f8817c2SEwan Crawford       result.SetStatus(eReturnStatusFailed);
39064f8817c2SEwan Crawford     }
39074f8817c2SEwan Crawford     return true;
39084f8817c2SEwan Crawford   }
39094f8817c2SEwan Crawford };
39104f8817c2SEwan Crawford 
3911b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpoint
3912b9c1b51eSKate Stone     : public CommandObjectMultiword {
39137dc7771cSEwan Crawford public:
3914b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpoint(
3915b9c1b51eSKate Stone       CommandInterpreter &interpreter)
3916b9c1b51eSKate Stone       : CommandObjectMultiword(
3917b9c1b51eSKate Stone             interpreter, "renderscript kernel",
3918b9c1b51eSKate Stone             "Commands that generate breakpoints on renderscript kernels.",
3919b9c1b51eSKate Stone             nullptr) {
3920b9c1b51eSKate Stone     LoadSubCommand(
3921b9c1b51eSKate Stone         "set",
3922b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
3923b9c1b51eSKate Stone             interpreter)));
3924b9c1b51eSKate Stone     LoadSubCommand(
3925b9c1b51eSKate Stone         "all",
3926b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
3927b9c1b51eSKate Stone             interpreter)));
39287dc7771cSEwan Crawford   }
39297dc7771cSEwan Crawford 
3930222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
39317dc7771cSEwan Crawford };
39327dc7771cSEwan Crawford 
3933b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
39344640cde1SColin Riley public:
39354640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
3936b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript kernel",
3937b9c1b51eSKate Stone                                "Commands that deal with RenderScript kernels.",
3938b9c1b51eSKate Stone                                nullptr) {
3939b9c1b51eSKate Stone     LoadSubCommand(
3940b9c1b51eSKate Stone         "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
3941b9c1b51eSKate Stone                     interpreter)));
3942b9c1b51eSKate Stone     LoadSubCommand(
3943b9c1b51eSKate Stone         "coordinate",
3944b9c1b51eSKate Stone         CommandObjectSP(
3945b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
3946b9c1b51eSKate Stone     LoadSubCommand(
3947b9c1b51eSKate Stone         "breakpoint",
3948b9c1b51eSKate Stone         CommandObjectSP(
3949b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
39504640cde1SColin Riley   }
39514640cde1SColin Riley 
3952222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernel() override = default;
39534640cde1SColin Riley };
39544640cde1SColin Riley 
3955b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
39564640cde1SColin Riley public:
39574640cde1SColin Riley   CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
3958b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript context dump",
3959b9c1b51eSKate Stone                             "Dumps renderscript context information.",
3960b9c1b51eSKate Stone                             "renderscript context dump",
3961b9c1b51eSKate Stone                             eCommandRequiresProcess |
3962b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
39634640cde1SColin Riley 
3964222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContextDump() override = default;
39654640cde1SColin Riley 
3966b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
39674640cde1SColin Riley     RenderScriptRuntime *runtime =
3968b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
3969b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
39704640cde1SColin Riley     runtime->DumpContexts(result.GetOutputStream());
39714640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
39724640cde1SColin Riley     return true;
39734640cde1SColin Riley   }
39744640cde1SColin Riley };
39754640cde1SColin Riley 
39761f0f5b5bSZachary Turner static OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
39771f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
39781f0f5b5bSZachary Turner      nullptr, nullptr, 0, eArgTypeFilename,
39791f0f5b5bSZachary Turner      "Print results to specified file instead of command line."}};
39801f0f5b5bSZachary Turner 
3981b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
39824640cde1SColin Riley public:
39834640cde1SColin Riley   CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
3984b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript context",
3985b9c1b51eSKate Stone                                "Commands that deal with RenderScript contexts.",
3986b9c1b51eSKate Stone                                nullptr) {
3987b9c1b51eSKate Stone     LoadSubCommand(
3988b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
3989b9c1b51eSKate Stone                     interpreter)));
39904640cde1SColin Riley   }
39914640cde1SColin Riley 
3992222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContext() override = default;
39934640cde1SColin Riley };
39944640cde1SColin Riley 
3995b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationDump
3996b9c1b51eSKate Stone     : public CommandObjectParsed {
3997a0f08674SEwan Crawford public:
3998b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationDump(
3999b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4000a0f08674SEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation dump",
4001b9c1b51eSKate Stone                             "Displays the contents of a particular allocation",
4002b9c1b51eSKate Stone                             "renderscript allocation dump <ID>",
4003b9c1b51eSKate Stone                             eCommandRequiresProcess |
4004b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched),
4005b9c1b51eSKate Stone         m_options() {}
4006a0f08674SEwan Crawford 
4007222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4008222b937cSEugene Zelenko 
4009b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
4010a0f08674SEwan Crawford 
4011b9c1b51eSKate Stone   class CommandOptions : public Options {
4012a0f08674SEwan Crawford   public:
4013e1cfbc79STodd Fiala     CommandOptions() : Options() {}
4014a0f08674SEwan Crawford 
4015222b937cSEugene Zelenko     ~CommandOptions() override = default;
4016a0f08674SEwan Crawford 
4017b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
4018b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
4019a0f08674SEwan Crawford       Error error;
4020a0f08674SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
4021a0f08674SEwan Crawford 
4022b9c1b51eSKate Stone       switch (short_option) {
4023a0f08674SEwan Crawford       case 'f':
4024a0f08674SEwan Crawford         m_outfile.SetFile(option_arg, true);
4025b9c1b51eSKate Stone         if (m_outfile.Exists()) {
4026a0f08674SEwan Crawford           m_outfile.Clear();
4027b9c1b51eSKate Stone           error.SetErrorStringWithFormat("file already exists: '%s'",
4028b9c1b51eSKate Stone                                          option_arg);
4029a0f08674SEwan Crawford         }
4030a0f08674SEwan Crawford         break;
4031a0f08674SEwan Crawford       default:
4032b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
4033b9c1b51eSKate Stone                                        short_option);
4034a0f08674SEwan Crawford         break;
4035a0f08674SEwan Crawford       }
4036a0f08674SEwan Crawford       return error;
4037a0f08674SEwan Crawford     }
4038a0f08674SEwan Crawford 
4039b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
4040a0f08674SEwan Crawford       m_outfile.Clear();
4041a0f08674SEwan Crawford     }
4042a0f08674SEwan Crawford 
40431f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
404470602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
40451f0f5b5bSZachary Turner     }
4046a0f08674SEwan Crawford 
4047a0f08674SEwan Crawford     FileSpec m_outfile;
4048a0f08674SEwan Crawford   };
4049a0f08674SEwan Crawford 
4050b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4051a0f08674SEwan Crawford     const size_t argc = command.GetArgumentCount();
4052b9c1b51eSKate Stone     if (argc < 1) {
4053b9c1b51eSKate Stone       result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4054b9c1b51eSKate Stone                                    "As well as an optional -f argument",
4055a0f08674SEwan Crawford                                    m_cmd_name.c_str());
4056a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4057a0f08674SEwan Crawford       return false;
4058a0f08674SEwan Crawford     }
4059a0f08674SEwan Crawford 
4060b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4061b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4062b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4063a0f08674SEwan Crawford 
4064a0f08674SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
4065a0f08674SEwan Crawford     bool convert_complete = false;
4066b9c1b51eSKate Stone     const uint32_t id =
4067b9c1b51eSKate Stone         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
4068b9c1b51eSKate Stone     if (!convert_complete) {
4069b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4070b9c1b51eSKate Stone                                    id_cstr);
4071a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4072a0f08674SEwan Crawford       return false;
4073a0f08674SEwan Crawford     }
4074a0f08674SEwan Crawford 
4075a0f08674SEwan Crawford     Stream *output_strm = nullptr;
4076a0f08674SEwan Crawford     StreamFile outfile_stream;
4077b9c1b51eSKate Stone     const FileSpec &outfile_spec =
4078b9c1b51eSKate Stone         m_options.m_outfile; // Dump allocation to file instead
4079b9c1b51eSKate Stone     if (outfile_spec) {
4080a0f08674SEwan Crawford       // Open output file
4081a0f08674SEwan Crawford       char path[256];
4082a0f08674SEwan Crawford       outfile_spec.GetPath(path, sizeof(path));
4083b9c1b51eSKate Stone       if (outfile_stream.GetFile()
4084b9c1b51eSKate Stone               .Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate)
4085b9c1b51eSKate Stone               .Success()) {
4086a0f08674SEwan Crawford         output_strm = &outfile_stream;
4087a0f08674SEwan Crawford         result.GetOutputStream().Printf("Results written to '%s'", path);
4088a0f08674SEwan Crawford         result.GetOutputStream().EOL();
4089b9c1b51eSKate Stone       } else {
4090a0f08674SEwan Crawford         result.AppendErrorWithFormat("Couldn't open file '%s'", path);
4091a0f08674SEwan Crawford         result.SetStatus(eReturnStatusFailed);
4092a0f08674SEwan Crawford         return false;
4093a0f08674SEwan Crawford       }
4094b9c1b51eSKate Stone     } else
4095a0f08674SEwan Crawford       output_strm = &result.GetOutputStream();
4096a0f08674SEwan Crawford 
4097a0f08674SEwan Crawford     assert(output_strm != nullptr);
4098b9c1b51eSKate Stone     bool success =
4099b9c1b51eSKate Stone         runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4100a0f08674SEwan Crawford 
4101a0f08674SEwan Crawford     if (success)
4102a0f08674SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4103a0f08674SEwan Crawford     else
4104a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4105a0f08674SEwan Crawford 
4106a0f08674SEwan Crawford     return true;
4107a0f08674SEwan Crawford   }
4108a0f08674SEwan Crawford 
4109a0f08674SEwan Crawford private:
4110a0f08674SEwan Crawford   CommandOptions m_options;
4111a0f08674SEwan Crawford };
4112a0f08674SEwan Crawford 
41131f0f5b5bSZachary Turner static OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
41141f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
41151f0f5b5bSZachary Turner      nullptr, 0, eArgTypeIndex,
41161f0f5b5bSZachary Turner      "Only show details of a single allocation with specified id."}};
4117a0f08674SEwan Crawford 
4118b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationList
4119b9c1b51eSKate Stone     : public CommandObjectParsed {
412015f2bd95SEwan Crawford public:
4121b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationList(
4122b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4123b9c1b51eSKate Stone       : CommandObjectParsed(
4124b9c1b51eSKate Stone             interpreter, "renderscript allocation list",
4125b9c1b51eSKate Stone             "List renderscript allocations and their information.",
4126b9c1b51eSKate Stone             "renderscript allocation list",
4127b3f7f69dSAidan Dodds             eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4128b9c1b51eSKate Stone         m_options() {}
412915f2bd95SEwan Crawford 
4130222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4131222b937cSEugene Zelenko 
4132b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
413315f2bd95SEwan Crawford 
4134b9c1b51eSKate Stone   class CommandOptions : public Options {
413515f2bd95SEwan Crawford   public:
4136e1cfbc79STodd Fiala     CommandOptions() : Options(), m_id(0) {}
413715f2bd95SEwan Crawford 
4138222b937cSEugene Zelenko     ~CommandOptions() override = default;
413915f2bd95SEwan Crawford 
4140b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
4141b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
414215f2bd95SEwan Crawford       Error error;
414315f2bd95SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
414415f2bd95SEwan Crawford 
4145b9c1b51eSKate Stone       switch (short_option) {
4146b649b005SEwan Crawford       case 'i':
4147b649b005SEwan Crawford         bool success;
4148b649b005SEwan Crawford         m_id = StringConvert::ToUInt32(option_arg, 0, 0, &success);
4149b649b005SEwan Crawford         if (!success)
4150b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
4151b9c1b51eSKate Stone               "invalid integer value for option '%c'", short_option);
415215f2bd95SEwan Crawford         break;
415315f2bd95SEwan Crawford       default:
4154b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
4155b9c1b51eSKate Stone                                        short_option);
415615f2bd95SEwan Crawford         break;
415715f2bd95SEwan Crawford       }
415815f2bd95SEwan Crawford       return error;
415915f2bd95SEwan Crawford     }
416015f2bd95SEwan Crawford 
4161b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
4162b649b005SEwan Crawford       m_id = 0;
416315f2bd95SEwan Crawford     }
416415f2bd95SEwan Crawford 
41651f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
416670602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
41671f0f5b5bSZachary Turner     }
416815f2bd95SEwan Crawford 
4169b649b005SEwan Crawford     uint32_t m_id;
417015f2bd95SEwan Crawford   };
417115f2bd95SEwan Crawford 
4172b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4173b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4174b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4175b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4176b9c1b51eSKate Stone     runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4177b9c1b51eSKate Stone                              m_options.m_id);
417815f2bd95SEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
417915f2bd95SEwan Crawford     return true;
418015f2bd95SEwan Crawford   }
418115f2bd95SEwan Crawford 
418215f2bd95SEwan Crawford private:
418315f2bd95SEwan Crawford   CommandOptions m_options;
418415f2bd95SEwan Crawford };
418515f2bd95SEwan Crawford 
4186b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationLoad
4187b9c1b51eSKate Stone     : public CommandObjectParsed {
418855232f09SEwan Crawford public:
4189b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationLoad(
4190b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4191b3f7f69dSAidan Dodds       : CommandObjectParsed(
4192b9c1b51eSKate Stone             interpreter, "renderscript allocation load",
4193b9c1b51eSKate Stone             "Loads renderscript allocation contents from a file.",
4194b9c1b51eSKate Stone             "renderscript allocation load <ID> <filename>",
4195b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
419655232f09SEwan Crawford 
4197222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
419855232f09SEwan Crawford 
4199b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
420055232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4201b9c1b51eSKate Stone     if (argc != 2) {
4202b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4203b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4204b3f7f69dSAidan Dodds           m_cmd_name.c_str());
420555232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
420655232f09SEwan Crawford       return false;
420755232f09SEwan Crawford     }
420855232f09SEwan Crawford 
4209b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4210b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4211b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
421255232f09SEwan Crawford 
421355232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
421455232f09SEwan Crawford     bool convert_complete = false;
4215b9c1b51eSKate Stone     const uint32_t id =
4216b9c1b51eSKate Stone         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
4217b9c1b51eSKate Stone     if (!convert_complete) {
4218b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4219b9c1b51eSKate Stone                                    id_cstr);
422055232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
422155232f09SEwan Crawford       return false;
422255232f09SEwan Crawford     }
422355232f09SEwan Crawford 
422455232f09SEwan Crawford     const char *filename = command.GetArgumentAtIndex(1);
4225b9c1b51eSKate Stone     bool success = runtime->LoadAllocation(result.GetOutputStream(), id,
4226b9c1b51eSKate Stone                                            filename, m_exe_ctx.GetFramePtr());
422755232f09SEwan Crawford 
422855232f09SEwan Crawford     if (success)
422955232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
423055232f09SEwan Crawford     else
423155232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
423255232f09SEwan Crawford 
423355232f09SEwan Crawford     return true;
423455232f09SEwan Crawford   }
423555232f09SEwan Crawford };
423655232f09SEwan Crawford 
4237b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationSave
4238b9c1b51eSKate Stone     : public CommandObjectParsed {
423955232f09SEwan Crawford public:
4240b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationSave(
4241b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4242b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript allocation save",
4243b9c1b51eSKate Stone                             "Write renderscript allocation contents to a file.",
4244b9c1b51eSKate Stone                             "renderscript allocation save <ID> <filename>",
4245b9c1b51eSKate Stone                             eCommandRequiresProcess |
4246b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
424755232f09SEwan Crawford 
4248222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
424955232f09SEwan Crawford 
4250b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
425155232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4252b9c1b51eSKate Stone     if (argc != 2) {
4253b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4254b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4255b3f7f69dSAidan Dodds           m_cmd_name.c_str());
425655232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
425755232f09SEwan Crawford       return false;
425855232f09SEwan Crawford     }
425955232f09SEwan Crawford 
4260b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4261b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4262b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
426355232f09SEwan Crawford 
426455232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
426555232f09SEwan Crawford     bool convert_complete = false;
4266b9c1b51eSKate Stone     const uint32_t id =
4267b9c1b51eSKate Stone         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
4268b9c1b51eSKate Stone     if (!convert_complete) {
4269b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4270b9c1b51eSKate Stone                                    id_cstr);
427155232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
427255232f09SEwan Crawford       return false;
427355232f09SEwan Crawford     }
427455232f09SEwan Crawford 
427555232f09SEwan Crawford     const char *filename = command.GetArgumentAtIndex(1);
4276b9c1b51eSKate Stone     bool success = runtime->SaveAllocation(result.GetOutputStream(), id,
4277b9c1b51eSKate Stone                                            filename, m_exe_ctx.GetFramePtr());
427855232f09SEwan Crawford 
427955232f09SEwan Crawford     if (success)
428055232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
428155232f09SEwan Crawford     else
428255232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
428355232f09SEwan Crawford 
428455232f09SEwan Crawford     return true;
428555232f09SEwan Crawford   }
428655232f09SEwan Crawford };
428755232f09SEwan Crawford 
4288b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationRefresh
4289b9c1b51eSKate Stone     : public CommandObjectParsed {
42900d2bfcfbSEwan Crawford public:
4291b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationRefresh(
4292b9c1b51eSKate Stone       CommandInterpreter &interpreter)
42930d2bfcfbSEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4294b9c1b51eSKate Stone                             "Recomputes the details of all allocations.",
4295b9c1b51eSKate Stone                             "renderscript allocation refresh",
4296b9c1b51eSKate Stone                             eCommandRequiresProcess |
4297b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
42980d2bfcfbSEwan Crawford 
42990d2bfcfbSEwan Crawford   ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
43000d2bfcfbSEwan Crawford 
4301b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
43020d2bfcfbSEwan Crawford     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4303b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4304b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
43050d2bfcfbSEwan Crawford 
4306b9c1b51eSKate Stone     bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4307b9c1b51eSKate Stone                                                     m_exe_ctx.GetFramePtr());
43080d2bfcfbSEwan Crawford 
4309b9c1b51eSKate Stone     if (success) {
43100d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
43110d2bfcfbSEwan Crawford       return true;
4312b9c1b51eSKate Stone     } else {
43130d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusFailed);
43140d2bfcfbSEwan Crawford       return false;
43150d2bfcfbSEwan Crawford     }
43160d2bfcfbSEwan Crawford   }
43170d2bfcfbSEwan Crawford };
43180d2bfcfbSEwan Crawford 
4319b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocation
4320b9c1b51eSKate Stone     : public CommandObjectMultiword {
432115f2bd95SEwan Crawford public:
432215f2bd95SEwan Crawford   CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4323b9c1b51eSKate Stone       : CommandObjectMultiword(
4324b9c1b51eSKate Stone             interpreter, "renderscript allocation",
4325b9c1b51eSKate Stone             "Commands that deal with RenderScript allocations.", nullptr) {
4326b9c1b51eSKate Stone     LoadSubCommand(
4327b9c1b51eSKate Stone         "list",
4328b9c1b51eSKate Stone         CommandObjectSP(
4329b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4330b9c1b51eSKate Stone     LoadSubCommand(
4331b9c1b51eSKate Stone         "dump",
4332b9c1b51eSKate Stone         CommandObjectSP(
4333b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4334b9c1b51eSKate Stone     LoadSubCommand(
4335b9c1b51eSKate Stone         "save",
4336b9c1b51eSKate Stone         CommandObjectSP(
4337b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4338b9c1b51eSKate Stone     LoadSubCommand(
4339b9c1b51eSKate Stone         "load",
4340b9c1b51eSKate Stone         CommandObjectSP(
4341b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4342b9c1b51eSKate Stone     LoadSubCommand(
4343b9c1b51eSKate Stone         "refresh",
4344b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4345b9c1b51eSKate Stone             interpreter)));
434615f2bd95SEwan Crawford   }
434715f2bd95SEwan Crawford 
4348222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocation() override = default;
434915f2bd95SEwan Crawford };
435015f2bd95SEwan Crawford 
4351b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
43524640cde1SColin Riley public:
43534640cde1SColin Riley   CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4354b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript status",
4355b9c1b51eSKate Stone                             "Displays current RenderScript runtime status.",
4356b9c1b51eSKate Stone                             "renderscript status",
4357b9c1b51eSKate Stone                             eCommandRequiresProcess |
4358b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
43594640cde1SColin Riley 
4360222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeStatus() override = default;
43614640cde1SColin Riley 
4362b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
43634640cde1SColin Riley     RenderScriptRuntime *runtime =
4364b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4365b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
43664640cde1SColin Riley     runtime->Status(result.GetOutputStream());
43674640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
43684640cde1SColin Riley     return true;
43694640cde1SColin Riley   }
43704640cde1SColin Riley };
43714640cde1SColin Riley 
4372b9c1b51eSKate Stone class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
43735ec532a9SColin Riley public:
43745ec532a9SColin Riley   CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
4375b9c1b51eSKate Stone       : CommandObjectMultiword(
4376b9c1b51eSKate Stone             interpreter, "renderscript",
4377b9c1b51eSKate Stone             "Commands for operating on the RenderScript runtime.",
4378b9c1b51eSKate Stone             "renderscript <subcommand> [<subcommand-options>]") {
4379b9c1b51eSKate Stone     LoadSubCommand(
4380b9c1b51eSKate Stone         "module", CommandObjectSP(
4381b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeModule(interpreter)));
4382b9c1b51eSKate Stone     LoadSubCommand(
4383b9c1b51eSKate Stone         "status", CommandObjectSP(
4384b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeStatus(interpreter)));
4385b9c1b51eSKate Stone     LoadSubCommand(
4386b9c1b51eSKate Stone         "kernel", CommandObjectSP(
4387b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeKernel(interpreter)));
4388b9c1b51eSKate Stone     LoadSubCommand("context",
4389b9c1b51eSKate Stone                    CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
4390b9c1b51eSKate Stone                        interpreter)));
4391b9c1b51eSKate Stone     LoadSubCommand(
4392b9c1b51eSKate Stone         "allocation",
4393b9c1b51eSKate Stone         CommandObjectSP(
4394b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
43955ec532a9SColin Riley   }
43965ec532a9SColin Riley 
4397222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntime() override = default;
43985ec532a9SColin Riley };
4399ef20b08fSColin Riley 
4400b9c1b51eSKate Stone void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
4401ef20b08fSColin Riley 
4402ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
4403b9c1b51eSKate Stone     : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
4404b9c1b51eSKate Stone       m_debuggerPresentFlagged(false), m_breakAllKernels(false),
4405b9c1b51eSKate Stone       m_ir_passes(nullptr) {
44064640cde1SColin Riley   ModulesDidLoad(process->GetTarget().GetImages());
4407ef20b08fSColin Riley }
44084640cde1SColin Riley 
4409b9c1b51eSKate Stone lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
4410b9c1b51eSKate Stone     lldb_private::CommandInterpreter &interpreter) {
44110a66e2f1SEnrico Granata   return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
44124640cde1SColin Riley }
44134640cde1SColin Riley 
441478f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
4415