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
13b3bbcb12SLuke Drummond #include "llvm/ADT/StringSwitch.h"
147f193d69SLuke Drummond 
15222b937cSEugene Zelenko // Project includes
165ec532a9SColin Riley #include "RenderScriptRuntime.h"
1721fed052SAidan Dodds #include "RenderScriptScriptGroup.h"
185ec532a9SColin Riley 
19b3f7f69dSAidan Dodds #include "lldb/Breakpoint/StoppointCallbackContext.h"
205ec532a9SColin Riley #include "lldb/Core/Debugger.h"
2129cb868aSZachary Turner #include "lldb/Core/DumpDataExtractor.h"
225ec532a9SColin Riley #include "lldb/Core/PluginManager.h"
23b3f7f69dSAidan Dodds #include "lldb/Core/ValueObjectVariable.h"
248b244e21SEwan Crawford #include "lldb/DataFormatters/DumpValueObjectOptions.h"
25b3f7f69dSAidan Dodds #include "lldb/Expression/UserExpression.h"
26a0f08674SEwan Crawford #include "lldb/Host/StringConvert.h"
27b3f7f69dSAidan Dodds #include "lldb/Interpreter/Args.h"
28b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandInterpreter.h"
29b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandObjectMultiword.h"
30b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandReturnObject.h"
31b3f7f69dSAidan Dodds #include "lldb/Interpreter/Options.h"
3221fed052SAidan Dodds #include "lldb/Symbol/Function.h"
335ec532a9SColin Riley #include "lldb/Symbol/Symbol.h"
344640cde1SColin Riley #include "lldb/Symbol/Type.h"
35b3f7f69dSAidan Dodds #include "lldb/Symbol/VariableList.h"
365ec532a9SColin Riley #include "lldb/Target/Process.h"
37b3f7f69dSAidan Dodds #include "lldb/Target/RegisterContext.h"
3821fed052SAidan Dodds #include "lldb/Target/SectionLoadList.h"
395ec532a9SColin Riley #include "lldb/Target/Target.h"
40018f5a7eSEwan Crawford #include "lldb/Target/Thread.h"
41bf9a7730SZachary Turner #include "lldb/Utility/ConstString.h"
42*7f6a7a37SZachary Turner #include "lldb/Utility/DataBufferLLVM.h"
43bf9a7730SZachary Turner #include "lldb/Utility/Error.h"
446f9e6901SZachary Turner #include "lldb/Utility/Log.h"
45bf9a7730SZachary Turner #include "lldb/Utility/RegularExpression.h"
465ec532a9SColin Riley 
475ec532a9SColin Riley using namespace lldb;
485ec532a9SColin Riley using namespace lldb_private;
4998156583SEwan Crawford using namespace lldb_renderscript;
505ec532a9SColin Riley 
5100f56eebSLuke Drummond #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")"
5200f56eebSLuke Drummond 
53b9c1b51eSKate Stone namespace {
5478f339d1SEwan Crawford 
5578f339d1SEwan Crawford // The empirical_type adds a basic level of validation to arbitrary data
5680af0b9eSLuke Drummond // allowing us to track if data has been discovered and stored or not. An
5780af0b9eSLuke Drummond // empirical_type will be marked as valid only if it has been explicitly
58b9c1b51eSKate Stone // assigned to.
59b9c1b51eSKate Stone template <typename type_t> class empirical_type {
6078f339d1SEwan Crawford public:
6178f339d1SEwan Crawford   // Ctor. Contents is invalid when constructed.
62b3f7f69dSAidan Dodds   empirical_type() : valid(false) {}
6378f339d1SEwan Crawford 
6478f339d1SEwan Crawford   // Return true and copy contents to out if valid, else return false.
65b9c1b51eSKate Stone   bool get(type_t &out) const {
6678f339d1SEwan Crawford     if (valid)
6778f339d1SEwan Crawford       out = data;
6878f339d1SEwan Crawford     return valid;
6978f339d1SEwan Crawford   }
7078f339d1SEwan Crawford 
7178f339d1SEwan Crawford   // Return a pointer to the contents or nullptr if it was not valid.
72b9c1b51eSKate Stone   const type_t *get() const { return valid ? &data : nullptr; }
7378f339d1SEwan Crawford 
7478f339d1SEwan Crawford   // Assign data explicitly.
75b9c1b51eSKate Stone   void set(const type_t in) {
7678f339d1SEwan Crawford     data = in;
7778f339d1SEwan Crawford     valid = true;
7878f339d1SEwan Crawford   }
7978f339d1SEwan Crawford 
8078f339d1SEwan Crawford   // Mark contents as invalid.
81b9c1b51eSKate Stone   void invalidate() { valid = false; }
8278f339d1SEwan Crawford 
8378f339d1SEwan Crawford   // Returns true if this type contains valid data.
84b9c1b51eSKate Stone   bool isValid() const { return valid; }
8578f339d1SEwan Crawford 
8678f339d1SEwan Crawford   // Assignment operator.
87b9c1b51eSKate Stone   empirical_type<type_t> &operator=(const type_t in) {
8878f339d1SEwan Crawford     set(in);
8978f339d1SEwan Crawford     return *this;
9078f339d1SEwan Crawford   }
9178f339d1SEwan Crawford 
9278f339d1SEwan Crawford   // Dereference operator returns contents.
9378f339d1SEwan Crawford   // Warning: Will assert if not valid so use only when you know data is valid.
94b9c1b51eSKate Stone   const type_t &operator*() const {
9578f339d1SEwan Crawford     assert(valid);
9678f339d1SEwan Crawford     return data;
9778f339d1SEwan Crawford   }
9878f339d1SEwan Crawford 
9978f339d1SEwan Crawford protected:
10078f339d1SEwan Crawford   bool valid;
10178f339d1SEwan Crawford   type_t data;
10278f339d1SEwan Crawford };
10378f339d1SEwan Crawford 
104b9c1b51eSKate Stone // ArgItem is used by the GetArgs() function when reading function arguments
105b9c1b51eSKate Stone // from the target.
106b9c1b51eSKate Stone struct ArgItem {
107b9c1b51eSKate Stone   enum { ePointer, eInt32, eInt64, eLong, eBool } type;
108f4786785SAidan Dodds 
109f4786785SAidan Dodds   uint64_t value;
110f4786785SAidan Dodds 
111f4786785SAidan Dodds   explicit operator uint64_t() const { return value; }
112f4786785SAidan Dodds };
113f4786785SAidan Dodds 
114b9c1b51eSKate Stone // Context structure to be passed into GetArgsXXX(), argument reading functions
115b9c1b51eSKate Stone // below.
116b9c1b51eSKate Stone struct GetArgsCtx {
117f4786785SAidan Dodds   RegisterContext *reg_ctx;
118f4786785SAidan Dodds   Process *process;
119f4786785SAidan Dodds };
120f4786785SAidan Dodds 
121b9c1b51eSKate Stone bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
122f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
123f4786785SAidan Dodds 
12480af0b9eSLuke Drummond   Error err;
12567dc3e15SAidan Dodds 
126f4786785SAidan Dodds   // get the current stack pointer
127f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
128f4786785SAidan Dodds 
129b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
130f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
131f4786785SAidan Dodds     // advance up the stack by one argument
132f4786785SAidan Dodds     sp += sizeof(uint32_t);
133f4786785SAidan Dodds     // get the argument type size
134f4786785SAidan Dodds     size_t arg_size = sizeof(uint32_t);
135f4786785SAidan Dodds     // read the argument from memory
136f4786785SAidan Dodds     arg.value = 0;
13780af0b9eSLuke Drummond     Error err;
138b9c1b51eSKate Stone     size_t read =
13980af0b9eSLuke Drummond         ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
14080af0b9eSLuke Drummond     if (read != arg_size || !err.Success()) {
141f4786785SAidan Dodds       if (log)
142b9c1b51eSKate Stone         log->Printf("%s - error reading argument: %" PRIu64 " '%s'",
14380af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString());
144f4786785SAidan Dodds       return false;
145f4786785SAidan Dodds     }
146f4786785SAidan Dodds   }
147f4786785SAidan Dodds   return true;
148f4786785SAidan Dodds }
149f4786785SAidan Dodds 
150b9c1b51eSKate Stone bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
151f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
152f4786785SAidan Dodds 
153f4786785SAidan Dodds   // number of arguments passed in registers
15480af0b9eSLuke Drummond   static const uint32_t args_in_reg = 6;
155f4786785SAidan Dodds   // register passing order
15680af0b9eSLuke Drummond   static const std::array<const char *, args_in_reg> reg_names{
157b9c1b51eSKate Stone       {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
158f4786785SAidan Dodds   // argument type to size mapping
1591ee07253SSaleem Abdulrasool   static const std::array<size_t, 5> arg_size{{
160f4786785SAidan Dodds       8, // ePointer,
161f4786785SAidan Dodds       4, // eInt32,
162f4786785SAidan Dodds       8, // eInt64,
163f4786785SAidan Dodds       8, // eLong,
164f4786785SAidan Dodds       4, // eBool,
1651ee07253SSaleem Abdulrasool   }};
166f4786785SAidan Dodds 
16780af0b9eSLuke Drummond   Error err;
16817e07c0aSAidan Dodds 
169f4786785SAidan Dodds   // get the current stack pointer
170f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
171f4786785SAidan Dodds   // step over the return address
172f4786785SAidan Dodds   sp += sizeof(uint64_t);
173f4786785SAidan Dodds 
174f4786785SAidan Dodds   // check the stack alignment was correct (16 byte aligned)
175b9c1b51eSKate Stone   if ((sp & 0xf) != 0x0) {
176f4786785SAidan Dodds     if (log)
177f4786785SAidan Dodds       log->Printf("%s - stack misaligned", __FUNCTION__);
178f4786785SAidan Dodds     return false;
179f4786785SAidan Dodds   }
180f4786785SAidan Dodds 
181f4786785SAidan Dodds   // find the start of arguments on the stack
182f4786785SAidan Dodds   uint64_t sp_offset = 0;
18380af0b9eSLuke Drummond   for (uint32_t i = args_in_reg; i < num_args; ++i) {
184f4786785SAidan Dodds     sp_offset += arg_size[arg_list[i].type];
185f4786785SAidan Dodds   }
186f4786785SAidan Dodds   // round up to multiple of 16
187f4786785SAidan Dodds   sp_offset = (sp_offset + 0xf) & 0xf;
188f4786785SAidan Dodds   sp += sp_offset;
189f4786785SAidan Dodds 
190b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
191f4786785SAidan Dodds     bool success = false;
192f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
193f4786785SAidan Dodds     // arguments passed in registers
19480af0b9eSLuke Drummond     if (i < args_in_reg) {
19580af0b9eSLuke Drummond       const RegisterInfo *reg =
19680af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoByName(reg_names[i]);
19780af0b9eSLuke Drummond       RegisterValue reg_val;
19880af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
19980af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
200f4786785SAidan Dodds     }
201f4786785SAidan Dodds     // arguments passed on the stack
202b9c1b51eSKate Stone     else {
203f4786785SAidan Dodds       // get the argument type size
204f4786785SAidan Dodds       const size_t size = arg_size[arg_list[i].type];
205f4786785SAidan Dodds       // read the argument from memory
206f4786785SAidan Dodds       arg.value = 0;
207b9c1b51eSKate Stone       // note: due to little endian layout reading 4 or 8 bytes will give the
208b9c1b51eSKate Stone       // correct value.
20980af0b9eSLuke Drummond       size_t read = ctx.process->ReadMemory(sp, &arg.value, size, err);
21080af0b9eSLuke Drummond       success = (err.Success() && read == size);
211f4786785SAidan Dodds       // advance past this argument
212f4786785SAidan Dodds       sp -= size;
213f4786785SAidan Dodds     }
214f4786785SAidan Dodds     // fail if we couldn't read this argument
215b9c1b51eSKate Stone     if (!success) {
216f4786785SAidan Dodds       if (log)
21717e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
21880af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
219f4786785SAidan Dodds       return false;
220f4786785SAidan Dodds     }
221f4786785SAidan Dodds   }
222f4786785SAidan Dodds   return true;
223f4786785SAidan Dodds }
224f4786785SAidan Dodds 
225b9c1b51eSKate Stone bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
226f4786785SAidan Dodds   // number of arguments passed in registers
22780af0b9eSLuke Drummond   static const uint32_t args_in_reg = 4;
228f4786785SAidan Dodds 
229f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
230f4786785SAidan Dodds 
23180af0b9eSLuke Drummond   Error err;
23217e07c0aSAidan Dodds 
233f4786785SAidan Dodds   // get the current stack pointer
234f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
235f4786785SAidan Dodds 
236b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
237f4786785SAidan Dodds     bool success = false;
238f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
239f4786785SAidan Dodds     // arguments passed in registers
24080af0b9eSLuke Drummond     if (i < args_in_reg) {
24180af0b9eSLuke Drummond       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
24280af0b9eSLuke Drummond       RegisterValue reg_val;
24380af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
24480af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt32(0, &success);
245f4786785SAidan Dodds     }
246f4786785SAidan Dodds     // arguments passed on the stack
247b9c1b51eSKate Stone     else {
248f4786785SAidan Dodds       // get the argument type size
249f4786785SAidan Dodds       const size_t arg_size = sizeof(uint32_t);
250f4786785SAidan Dodds       // clear all 64bits
251f4786785SAidan Dodds       arg.value = 0;
252f4786785SAidan Dodds       // read this argument from memory
253b9c1b51eSKate Stone       size_t bytes_read =
25480af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
25580af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
256f4786785SAidan Dodds       // advance the stack pointer
257f4786785SAidan Dodds       sp += sizeof(uint32_t);
258f4786785SAidan Dodds     }
259f4786785SAidan Dodds     // fail if we couldn't read this argument
260b9c1b51eSKate Stone     if (!success) {
261f4786785SAidan Dodds       if (log)
26217e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
26380af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
264f4786785SAidan Dodds       return false;
265f4786785SAidan Dodds     }
266f4786785SAidan Dodds   }
267f4786785SAidan Dodds   return true;
268f4786785SAidan Dodds }
269f4786785SAidan Dodds 
270b9c1b51eSKate Stone bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
271f4786785SAidan Dodds   // number of arguments passed in registers
27280af0b9eSLuke Drummond   static const uint32_t args_in_reg = 8;
273f4786785SAidan Dodds 
274f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
275f4786785SAidan Dodds 
276b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
277f4786785SAidan Dodds     bool success = false;
278f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
279f4786785SAidan Dodds     // arguments passed in registers
28080af0b9eSLuke Drummond     if (i < args_in_reg) {
28180af0b9eSLuke Drummond       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
28280af0b9eSLuke Drummond       RegisterValue reg_val;
28380af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
28480af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
285f4786785SAidan Dodds     }
286f4786785SAidan Dodds     // arguments passed on the stack
287b9c1b51eSKate Stone     else {
288f4786785SAidan Dodds       if (log)
289b9c1b51eSKate Stone         log->Printf("%s - reading arguments spilled to stack not implemented",
290b9c1b51eSKate Stone                     __FUNCTION__);
291f4786785SAidan Dodds     }
292f4786785SAidan Dodds     // fail if we couldn't read this argument
293b9c1b51eSKate Stone     if (!success) {
294f4786785SAidan Dodds       if (log)
295f4786785SAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__,
296f4786785SAidan Dodds                     uint64_t(i));
297f4786785SAidan Dodds       return false;
298f4786785SAidan Dodds     }
299f4786785SAidan Dodds   }
300f4786785SAidan Dodds   return true;
301f4786785SAidan Dodds }
302f4786785SAidan Dodds 
303b9c1b51eSKate Stone bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
304f4786785SAidan Dodds   // number of arguments passed in registers
30580af0b9eSLuke Drummond   static const uint32_t args_in_reg = 4;
306f4786785SAidan Dodds   // register file offset to first argument
30780af0b9eSLuke Drummond   static const uint32_t reg_offset = 4;
308f4786785SAidan Dodds 
309f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
310f4786785SAidan Dodds 
31180af0b9eSLuke Drummond   Error err;
31217e07c0aSAidan Dodds 
31317e07c0aSAidan Dodds   // find offset to arguments on the stack (+16 to skip over a0-a3 shadow space)
31417e07c0aSAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP() + 16;
31517e07c0aSAidan Dodds 
316b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
317f4786785SAidan Dodds     bool success = false;
318f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
319f4786785SAidan Dodds     // arguments passed in registers
32080af0b9eSLuke Drummond     if (i < args_in_reg) {
32180af0b9eSLuke Drummond       const RegisterInfo *reg =
32280af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
32380af0b9eSLuke Drummond       RegisterValue reg_val;
32480af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
32580af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
326f4786785SAidan Dodds     }
327f4786785SAidan Dodds     // arguments passed on the stack
328b9c1b51eSKate Stone     else {
3296dd4b579SAidan Dodds       const size_t arg_size = sizeof(uint32_t);
3306dd4b579SAidan Dodds       arg.value = 0;
331b9c1b51eSKate Stone       size_t bytes_read =
33280af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
33380af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
33467dc3e15SAidan Dodds       // advance the stack pointer
33567dc3e15SAidan Dodds       sp += arg_size;
336f4786785SAidan Dodds     }
337f4786785SAidan Dodds     // fail if we couldn't read this argument
338b9c1b51eSKate Stone     if (!success) {
339f4786785SAidan Dodds       if (log)
34067dc3e15SAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
34180af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
342f4786785SAidan Dodds       return false;
343f4786785SAidan Dodds     }
344f4786785SAidan Dodds   }
345f4786785SAidan Dodds   return true;
346f4786785SAidan Dodds }
347f4786785SAidan Dodds 
348b9c1b51eSKate Stone bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
349f4786785SAidan Dodds   // number of arguments passed in registers
35080af0b9eSLuke Drummond   static const uint32_t args_in_reg = 8;
351f4786785SAidan Dodds   // register file offset to first argument
35280af0b9eSLuke Drummond   static const uint32_t reg_offset = 4;
353f4786785SAidan Dodds 
354f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
355f4786785SAidan Dodds 
35680af0b9eSLuke Drummond   Error err;
35717e07c0aSAidan Dodds 
358f4786785SAidan Dodds   // get the current stack pointer
359f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
360f4786785SAidan Dodds 
361b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
362f4786785SAidan Dodds     bool success = false;
363f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
364f4786785SAidan Dodds     // arguments passed in registers
36580af0b9eSLuke Drummond     if (i < args_in_reg) {
36680af0b9eSLuke Drummond       const RegisterInfo *reg =
36780af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
36880af0b9eSLuke Drummond       RegisterValue reg_val;
36980af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
37080af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
371f4786785SAidan Dodds     }
372f4786785SAidan Dodds     // arguments passed on the stack
373b9c1b51eSKate Stone     else {
374f4786785SAidan Dodds       // get the argument type size
375f4786785SAidan Dodds       const size_t arg_size = sizeof(uint64_t);
376f4786785SAidan Dodds       // clear all 64bits
377f4786785SAidan Dodds       arg.value = 0;
378f4786785SAidan Dodds       // read this argument from memory
379b9c1b51eSKate Stone       size_t bytes_read =
38080af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
38180af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
382f4786785SAidan Dodds       // advance the stack pointer
383f4786785SAidan Dodds       sp += arg_size;
384f4786785SAidan Dodds     }
385f4786785SAidan Dodds     // fail if we couldn't read this argument
386b9c1b51eSKate Stone     if (!success) {
387f4786785SAidan Dodds       if (log)
38817e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
38980af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
390f4786785SAidan Dodds       return false;
391f4786785SAidan Dodds     }
392f4786785SAidan Dodds   }
393f4786785SAidan Dodds   return true;
394f4786785SAidan Dodds }
395f4786785SAidan Dodds 
39680af0b9eSLuke Drummond bool GetArgs(ExecutionContext &exe_ctx, ArgItem *arg_list, size_t num_args) {
397f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
398f4786785SAidan Dodds 
399f4786785SAidan Dodds   // verify that we have a target
40080af0b9eSLuke Drummond   if (!exe_ctx.GetTargetPtr()) {
401f4786785SAidan Dodds     if (log)
402f4786785SAidan Dodds       log->Printf("%s - invalid target", __FUNCTION__);
403f4786785SAidan Dodds     return false;
404f4786785SAidan Dodds   }
405f4786785SAidan Dodds 
40680af0b9eSLuke Drummond   GetArgsCtx ctx = {exe_ctx.GetRegisterContext(), exe_ctx.GetProcessPtr()};
407f4786785SAidan Dodds   assert(ctx.reg_ctx && ctx.process);
408f4786785SAidan Dodds 
409f4786785SAidan Dodds   // dispatch based on architecture
41080af0b9eSLuke Drummond   switch (exe_ctx.GetTargetPtr()->GetArchitecture().GetMachine()) {
411f4786785SAidan Dodds   case llvm::Triple::ArchType::x86:
412f4786785SAidan Dodds     return GetArgsX86(ctx, arg_list, num_args);
413f4786785SAidan Dodds 
414f4786785SAidan Dodds   case llvm::Triple::ArchType::x86_64:
415f4786785SAidan Dodds     return GetArgsX86_64(ctx, arg_list, num_args);
416f4786785SAidan Dodds 
417f4786785SAidan Dodds   case llvm::Triple::ArchType::arm:
418f4786785SAidan Dodds     return GetArgsArm(ctx, arg_list, num_args);
419f4786785SAidan Dodds 
420f4786785SAidan Dodds   case llvm::Triple::ArchType::aarch64:
421f4786785SAidan Dodds     return GetArgsAarch64(ctx, arg_list, num_args);
422f4786785SAidan Dodds 
423f4786785SAidan Dodds   case llvm::Triple::ArchType::mipsel:
424f4786785SAidan Dodds     return GetArgsMipsel(ctx, arg_list, num_args);
425f4786785SAidan Dodds 
426f4786785SAidan Dodds   case llvm::Triple::ArchType::mips64el:
427f4786785SAidan Dodds     return GetArgsMips64el(ctx, arg_list, num_args);
428f4786785SAidan Dodds 
429f4786785SAidan Dodds   default:
430f4786785SAidan Dodds     // unsupported architecture
431b9c1b51eSKate Stone     if (log) {
432b9c1b51eSKate Stone       log->Printf(
433b9c1b51eSKate Stone           "%s - architecture not supported: '%s'", __FUNCTION__,
43480af0b9eSLuke Drummond           exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
435f4786785SAidan Dodds     }
436f4786785SAidan Dodds     return false;
437f4786785SAidan Dodds   }
438f4786785SAidan Dodds }
43900f56eebSLuke Drummond 
440b3bbcb12SLuke Drummond bool IsRenderScriptScriptModule(ModuleSP module) {
441b3bbcb12SLuke Drummond   if (!module)
442b3bbcb12SLuke Drummond     return false;
443b3bbcb12SLuke Drummond   return module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
444b3bbcb12SLuke Drummond                                                 eSymbolTypeData) != nullptr;
445b3bbcb12SLuke Drummond }
446b3bbcb12SLuke Drummond 
44700f56eebSLuke Drummond bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
44800f56eebSLuke Drummond   // takes an argument of the form 'num[,num][,num]'.
44900f56eebSLuke Drummond   // Where 'coord_s' is a comma separated 1,2 or 3-dimensional coordinate
45000f56eebSLuke Drummond   // with the whitespace trimmed.
45100f56eebSLuke Drummond   // Missing coordinates are defaulted to zero.
45200f56eebSLuke Drummond   // If parsing of any elements fails the contents of &coord are undefined
45300f56eebSLuke Drummond   // and `false` is returned, `true` otherwise
45400f56eebSLuke Drummond 
45500f56eebSLuke Drummond   RegularExpression regex;
45600f56eebSLuke Drummond   RegularExpression::Match regex_match(3);
45700f56eebSLuke Drummond 
45800f56eebSLuke Drummond   bool matched = false;
45900f56eebSLuke Drummond   if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+),([0-9]+)$")) &&
46000f56eebSLuke Drummond       regex.Execute(coord_s, &regex_match))
46100f56eebSLuke Drummond     matched = true;
46200f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+)$")) &&
46300f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
46400f56eebSLuke Drummond     matched = true;
46500f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([0-9]+)$")) &&
46600f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
46700f56eebSLuke Drummond     matched = true;
46800f56eebSLuke Drummond 
46900f56eebSLuke Drummond   if (!matched)
47000f56eebSLuke Drummond     return false;
47100f56eebSLuke Drummond 
47200f56eebSLuke Drummond   auto get_index = [&](int idx, uint32_t &i) -> bool {
47300f56eebSLuke Drummond     std::string group;
47400f56eebSLuke Drummond     errno = 0;
47500f56eebSLuke Drummond     if (regex_match.GetMatchAtIndex(coord_s.str().c_str(), idx + 1, group))
47600f56eebSLuke Drummond       return !llvm::StringRef(group).getAsInteger<uint32_t>(10, i);
47700f56eebSLuke Drummond     return true;
47800f56eebSLuke Drummond   };
47900f56eebSLuke Drummond 
48000f56eebSLuke Drummond   return get_index(0, coord.x) && get_index(1, coord.y) &&
48100f56eebSLuke Drummond          get_index(2, coord.z);
48200f56eebSLuke Drummond }
48321fed052SAidan Dodds 
48421fed052SAidan Dodds bool SkipPrologue(lldb::ModuleSP &module, Address &addr) {
48521fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
48621fed052SAidan Dodds   SymbolContext sc;
48721fed052SAidan Dodds   uint32_t resolved_flags =
48821fed052SAidan Dodds       module->ResolveSymbolContextForAddress(addr, eSymbolContextFunction, sc);
48921fed052SAidan Dodds   if (resolved_flags & eSymbolContextFunction) {
49021fed052SAidan Dodds     if (sc.function) {
49121fed052SAidan Dodds       const uint32_t offset = sc.function->GetPrologueByteSize();
49221fed052SAidan Dodds       ConstString name = sc.GetFunctionName();
49321fed052SAidan Dodds       if (offset)
49421fed052SAidan Dodds         addr.Slide(offset);
49521fed052SAidan Dodds       if (log)
49621fed052SAidan Dodds         log->Printf("%s: Prologue offset for %s is %" PRIu32, __FUNCTION__,
49721fed052SAidan Dodds                     name.AsCString(), offset);
49821fed052SAidan Dodds     }
49921fed052SAidan Dodds     return true;
50021fed052SAidan Dodds   } else
50121fed052SAidan Dodds     return false;
50221fed052SAidan Dodds }
503222b937cSEugene Zelenko } // anonymous namespace
50478f339d1SEwan Crawford 
505b9c1b51eSKate Stone // The ScriptDetails class collects data associated with a single script
506b9c1b51eSKate Stone // instance.
507b9c1b51eSKate Stone struct RenderScriptRuntime::ScriptDetails {
508222b937cSEugene Zelenko   ~ScriptDetails() = default;
50978f339d1SEwan Crawford 
510b9c1b51eSKate Stone   enum ScriptType { eScript, eScriptC };
51178f339d1SEwan Crawford 
51278f339d1SEwan Crawford   // The derived type of the script.
51378f339d1SEwan Crawford   empirical_type<ScriptType> type;
51478f339d1SEwan Crawford   // The name of the original source file.
51580af0b9eSLuke Drummond   empirical_type<std::string> res_name;
51678f339d1SEwan Crawford   // Path to script .so file on the device.
51780af0b9eSLuke Drummond   empirical_type<std::string> shared_lib;
51878f339d1SEwan Crawford   // Directory where kernel objects are cached on device.
51980af0b9eSLuke Drummond   empirical_type<std::string> cache_dir;
52078f339d1SEwan Crawford   // Pointer to the context which owns this script.
52178f339d1SEwan Crawford   empirical_type<lldb::addr_t> context;
52278f339d1SEwan Crawford   // Pointer to the script object itself.
52378f339d1SEwan Crawford   empirical_type<lldb::addr_t> script;
52478f339d1SEwan Crawford };
52578f339d1SEwan Crawford 
52680af0b9eSLuke Drummond // This Element class represents the Element object in RS, defining the type
52780af0b9eSLuke Drummond // associated with an Allocation.
528b9c1b51eSKate Stone struct RenderScriptRuntime::Element {
52915f2bd95SEwan Crawford   // Taken from rsDefines.h
530b9c1b51eSKate Stone   enum DataKind {
53115f2bd95SEwan Crawford     RS_KIND_USER,
53215f2bd95SEwan Crawford     RS_KIND_PIXEL_L = 7,
53315f2bd95SEwan Crawford     RS_KIND_PIXEL_A,
53415f2bd95SEwan Crawford     RS_KIND_PIXEL_LA,
53515f2bd95SEwan Crawford     RS_KIND_PIXEL_RGB,
53615f2bd95SEwan Crawford     RS_KIND_PIXEL_RGBA,
53715f2bd95SEwan Crawford     RS_KIND_PIXEL_DEPTH,
53815f2bd95SEwan Crawford     RS_KIND_PIXEL_YUV,
53915f2bd95SEwan Crawford     RS_KIND_INVALID = 100
54015f2bd95SEwan Crawford   };
54178f339d1SEwan Crawford 
54215f2bd95SEwan Crawford   // Taken from rsDefines.h
543b9c1b51eSKate Stone   enum DataType {
54415f2bd95SEwan Crawford     RS_TYPE_NONE = 0,
54515f2bd95SEwan Crawford     RS_TYPE_FLOAT_16,
54615f2bd95SEwan Crawford     RS_TYPE_FLOAT_32,
54715f2bd95SEwan Crawford     RS_TYPE_FLOAT_64,
54815f2bd95SEwan Crawford     RS_TYPE_SIGNED_8,
54915f2bd95SEwan Crawford     RS_TYPE_SIGNED_16,
55015f2bd95SEwan Crawford     RS_TYPE_SIGNED_32,
55115f2bd95SEwan Crawford     RS_TYPE_SIGNED_64,
55215f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_8,
55315f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_16,
55415f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_32,
55515f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_64,
5562e920715SEwan Crawford     RS_TYPE_BOOLEAN,
5572e920715SEwan Crawford 
5582e920715SEwan Crawford     RS_TYPE_UNSIGNED_5_6_5,
5592e920715SEwan Crawford     RS_TYPE_UNSIGNED_5_5_5_1,
5602e920715SEwan Crawford     RS_TYPE_UNSIGNED_4_4_4_4,
5612e920715SEwan Crawford 
5622e920715SEwan Crawford     RS_TYPE_MATRIX_4X4,
5632e920715SEwan Crawford     RS_TYPE_MATRIX_3X3,
5642e920715SEwan Crawford     RS_TYPE_MATRIX_2X2,
5652e920715SEwan Crawford 
5662e920715SEwan Crawford     RS_TYPE_ELEMENT = 1000,
5672e920715SEwan Crawford     RS_TYPE_TYPE,
5682e920715SEwan Crawford     RS_TYPE_ALLOCATION,
5692e920715SEwan Crawford     RS_TYPE_SAMPLER,
5702e920715SEwan Crawford     RS_TYPE_SCRIPT,
5712e920715SEwan Crawford     RS_TYPE_MESH,
5722e920715SEwan Crawford     RS_TYPE_PROGRAM_FRAGMENT,
5732e920715SEwan Crawford     RS_TYPE_PROGRAM_VERTEX,
5742e920715SEwan Crawford     RS_TYPE_PROGRAM_RASTER,
5752e920715SEwan Crawford     RS_TYPE_PROGRAM_STORE,
5762e920715SEwan Crawford     RS_TYPE_FONT,
5772e920715SEwan Crawford 
5782e920715SEwan Crawford     RS_TYPE_INVALID = 10000
57978f339d1SEwan Crawford   };
58078f339d1SEwan Crawford 
5818b244e21SEwan Crawford   std::vector<Element> children; // Child Element fields for structs
582b9c1b51eSKate Stone   empirical_type<lldb::addr_t>
583b9c1b51eSKate Stone       element_ptr; // Pointer to the RS Element of the Type
584b9c1b51eSKate Stone   empirical_type<DataType>
585b9c1b51eSKate Stone       type; // Type of each data pointer stored by the allocation
586b9c1b51eSKate Stone   empirical_type<DataKind>
587b9c1b51eSKate Stone       type_kind; // Defines pixel type if Allocation is created from an image
588b9c1b51eSKate Stone   empirical_type<uint32_t>
589b9c1b51eSKate Stone       type_vec_size; // Vector size of each data point, e.g '4' for uchar4
5908b244e21SEwan Crawford   empirical_type<uint32_t> field_count; // Number of Subelements
5918b244e21SEwan Crawford   empirical_type<uint32_t> datum_size;  // Size of a single Element with padding
5928b244e21SEwan Crawford   empirical_type<uint32_t> padding;     // Number of padding bytes
593b9c1b51eSKate Stone   empirical_type<uint32_t>
594b9c1b51eSKate Stone       array_size;        // Number of items in array, only needed for strucrs
5958b244e21SEwan Crawford   ConstString type_name; // Name of type, only needed for structs
5968b244e21SEwan Crawford 
597b3f7f69dSAidan Dodds   static const ConstString &
598b3f7f69dSAidan Dodds   GetFallbackStructName(); // Print this as the type name of a struct Element
5998b244e21SEwan Crawford                            // If we can't resolve the actual struct name
6008b59062aSEwan Crawford 
60180af0b9eSLuke Drummond   bool ShouldRefresh() const {
6028b59062aSEwan Crawford     const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
603b9c1b51eSKate Stone     const bool valid_type =
604b9c1b51eSKate Stone         type.isValid() && type_vec_size.isValid() && type_kind.isValid();
6058b59062aSEwan Crawford     return !valid_ptr || !valid_type || !datum_size.isValid();
6068b59062aSEwan Crawford   }
6078b244e21SEwan Crawford };
6088b244e21SEwan Crawford 
6098b244e21SEwan Crawford // This AllocationDetails class collects data associated with a single
6108b244e21SEwan Crawford // allocation instance.
611b9c1b51eSKate Stone struct RenderScriptRuntime::AllocationDetails {
612b9c1b51eSKate Stone   struct Dimension {
61315f2bd95SEwan Crawford     uint32_t dim_1;
61415f2bd95SEwan Crawford     uint32_t dim_2;
61515f2bd95SEwan Crawford     uint32_t dim_3;
61680af0b9eSLuke Drummond     uint32_t cube_map;
61715f2bd95SEwan Crawford 
618b9c1b51eSKate Stone     Dimension() {
61915f2bd95SEwan Crawford       dim_1 = 0;
62015f2bd95SEwan Crawford       dim_2 = 0;
62115f2bd95SEwan Crawford       dim_3 = 0;
62280af0b9eSLuke Drummond       cube_map = 0;
62315f2bd95SEwan Crawford     }
62478f339d1SEwan Crawford   };
62578f339d1SEwan Crawford 
626b9c1b51eSKate Stone   // The FileHeader struct specifies the header we use for writing allocations
62780af0b9eSLuke Drummond   // to a binary file. Our format begins with the ASCII characters "RSAD",
62880af0b9eSLuke Drummond   // identifying the file as an allocation dump. Member variables dims and
62980af0b9eSLuke Drummond   // hdr_size are then written consecutively, immediately followed by an
63080af0b9eSLuke Drummond   // instance of the ElementHeader struct. Because Elements can contain
63180af0b9eSLuke Drummond   // subelements, there may be more than one instance of the ElementHeader
63280af0b9eSLuke Drummond   // struct. With this first instance being the root element, and the other
63380af0b9eSLuke Drummond   // instances being the root's descendants. To identify which instances are an
63480af0b9eSLuke Drummond   // ElementHeader's children, each struct is immediately followed by a sequence
63580af0b9eSLuke Drummond   // of consecutive offsets to the start of its child structs. These offsets are
63680af0b9eSLuke Drummond   // 4 bytes in size, and the 0 offset signifies no more children.
637b9c1b51eSKate Stone   struct FileHeader {
63855232f09SEwan Crawford     uint8_t ident[4];  // ASCII 'RSAD' identifying the file
63926e52a70SEwan Crawford     uint32_t dims[3];  // Dimensions
64026e52a70SEwan Crawford     uint16_t hdr_size; // Header size in bytes, including all element headers
64126e52a70SEwan Crawford   };
64226e52a70SEwan Crawford 
643b9c1b51eSKate Stone   struct ElementHeader {
64455232f09SEwan Crawford     uint16_t type;         // DataType enum
64555232f09SEwan Crawford     uint32_t kind;         // DataKind enum
64655232f09SEwan Crawford     uint32_t element_size; // Size of a single element, including padding
64726e52a70SEwan Crawford     uint16_t vector_size;  // Vector width
64826e52a70SEwan Crawford     uint32_t array_size;   // Number of elements in array
64955232f09SEwan Crawford   };
65055232f09SEwan Crawford 
65115f2bd95SEwan Crawford   // Monotonically increasing from 1
652b3f7f69dSAidan Dodds   static uint32_t ID;
65315f2bd95SEwan Crawford 
65415f2bd95SEwan Crawford   // Maps Allocation DataType enum and vector size to printable strings
65515f2bd95SEwan Crawford   // using mapping from RenderScript numerical types summary documentation
65615f2bd95SEwan Crawford   static const char *RsDataTypeToString[][4];
65715f2bd95SEwan Crawford 
65815f2bd95SEwan Crawford   // Maps Allocation DataKind enum to printable strings
65915f2bd95SEwan Crawford   static const char *RsDataKindToString[];
66015f2bd95SEwan Crawford 
661a0f08674SEwan Crawford   // Maps allocation types to format sizes for printing.
662b3f7f69dSAidan Dodds   static const uint32_t RSTypeToFormat[][3];
663a0f08674SEwan Crawford 
66415f2bd95SEwan Crawford   // Give each allocation an ID as a way
66515f2bd95SEwan Crawford   // for commands to reference it.
666b3f7f69dSAidan Dodds   const uint32_t id;
66715f2bd95SEwan Crawford 
66880af0b9eSLuke Drummond   // Allocation Element type
66980af0b9eSLuke Drummond   RenderScriptRuntime::Element element;
67080af0b9eSLuke Drummond   // Dimensions of the Allocation
67180af0b9eSLuke Drummond   empirical_type<Dimension> dimension;
67280af0b9eSLuke Drummond   // Pointer to address of the RS Allocation
67380af0b9eSLuke Drummond   empirical_type<lldb::addr_t> address;
67480af0b9eSLuke Drummond   // Pointer to the data held by the Allocation
67580af0b9eSLuke Drummond   empirical_type<lldb::addr_t> data_ptr;
67680af0b9eSLuke Drummond   // Pointer to the RS Type of the Allocation
67780af0b9eSLuke Drummond   empirical_type<lldb::addr_t> type_ptr;
67880af0b9eSLuke Drummond   // Pointer to the RS Context of the Allocation
67980af0b9eSLuke Drummond   empirical_type<lldb::addr_t> context;
68080af0b9eSLuke Drummond   // Size of the allocation
68180af0b9eSLuke Drummond   empirical_type<uint32_t> size;
68280af0b9eSLuke Drummond   // Stride between rows of the allocation
68380af0b9eSLuke Drummond   empirical_type<uint32_t> stride;
68415f2bd95SEwan Crawford 
68515f2bd95SEwan Crawford   // Give each allocation an id, so we can reference it in user commands.
686b3f7f69dSAidan Dodds   AllocationDetails() : id(ID++) {}
6878b59062aSEwan Crawford 
68880af0b9eSLuke Drummond   bool ShouldRefresh() const {
6898b59062aSEwan Crawford     bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
6908b59062aSEwan Crawford     valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
691b9c1b51eSKate Stone     return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
69280af0b9eSLuke Drummond            element.ShouldRefresh();
6938b59062aSEwan Crawford   }
69415f2bd95SEwan Crawford };
69515f2bd95SEwan Crawford 
696b9c1b51eSKate Stone const ConstString &RenderScriptRuntime::Element::GetFallbackStructName() {
697fe06b5adSAdrian McCarthy   static const ConstString FallbackStructName("struct");
698fe06b5adSAdrian McCarthy   return FallbackStructName;
699fe06b5adSAdrian McCarthy }
7008b244e21SEwan Crawford 
701b3f7f69dSAidan Dodds uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
70215f2bd95SEwan Crawford 
703b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
704b9c1b51eSKate Stone     "User",       "Undefined",   "Undefined", "Undefined",
705b9c1b51eSKate Stone     "Undefined",  "Undefined",   "Undefined", // Enum jumps from 0 to 7
706b3f7f69dSAidan Dodds     "L Pixel",    "A Pixel",     "LA Pixel",  "RGB Pixel",
707b3f7f69dSAidan Dodds     "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
70815f2bd95SEwan Crawford 
709b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
71015f2bd95SEwan Crawford     {"None", "None", "None", "None"},
71115f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
71215f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
71315f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
71415f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
71515f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
71615f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
71715f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
71815f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
71915f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
72015f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
72115f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
7222e920715SEwan Crawford     {"bool", "bool2", "bool3", "bool4"},
7232e920715SEwan Crawford     {"packed_565", "packed_565", "packed_565", "packed_565"},
7242e920715SEwan Crawford     {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
7252e920715SEwan Crawford     {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
7262e920715SEwan Crawford     {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
7272e920715SEwan Crawford     {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
7282e920715SEwan Crawford     {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
7292e920715SEwan Crawford 
7302e920715SEwan Crawford     // Handlers
7312e920715SEwan Crawford     {"RS Element", "RS Element", "RS Element", "RS Element"},
7322e920715SEwan Crawford     {"RS Type", "RS Type", "RS Type", "RS Type"},
7332e920715SEwan Crawford     {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
7342e920715SEwan Crawford     {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
7352e920715SEwan Crawford     {"RS Script", "RS Script", "RS Script", "RS Script"},
7362e920715SEwan Crawford 
7372e920715SEwan Crawford     // Deprecated
7382e920715SEwan Crawford     {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
739b9c1b51eSKate Stone     {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
740b9c1b51eSKate Stone      "RS Program Fragment"},
741b9c1b51eSKate Stone     {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
742b9c1b51eSKate Stone      "RS Program Vertex"},
743b9c1b51eSKate Stone     {"RS Program Raster", "RS Program Raster", "RS Program Raster",
744b9c1b51eSKate Stone      "RS Program Raster"},
745b9c1b51eSKate Stone     {"RS Program Store", "RS Program Store", "RS Program Store",
746b9c1b51eSKate Stone      "RS Program Store"},
747b3f7f69dSAidan Dodds     {"RS Font", "RS Font", "RS Font", "RS Font"}};
74878f339d1SEwan Crawford 
749a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
750b9c1b51eSKate Stone enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
751a0f08674SEwan Crawford 
752b9c1b51eSKate Stone // { format enum of single element, format enum of element vector, size of
753b9c1b51eSKate Stone // element}
754b3f7f69dSAidan Dodds const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
75580af0b9eSLuke Drummond     // RS_TYPE_NONE
75680af0b9eSLuke Drummond     {eFormatHex, eFormatHex, 1},
75780af0b9eSLuke Drummond     // RS_TYPE_FLOAT_16
75880af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat16, 2},
75980af0b9eSLuke Drummond     // RS_TYPE_FLOAT_32
76080af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
76180af0b9eSLuke Drummond     // RS_TYPE_FLOAT_64
76280af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
76380af0b9eSLuke Drummond     // RS_TYPE_SIGNED_8
76480af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
76580af0b9eSLuke Drummond     // RS_TYPE_SIGNED_16
76680af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
76780af0b9eSLuke Drummond     // RS_TYPE_SIGNED_32
76880af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
76980af0b9eSLuke Drummond     // RS_TYPE_SIGNED_64
77080af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
77180af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_8
77280af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
77380af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_16
77480af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
77580af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_32
77680af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
77780af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_64
77880af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
77980af0b9eSLuke Drummond     // RS_TYPE_BOOL
78080af0b9eSLuke Drummond     {eFormatBoolean, eFormatBoolean, 1},
78180af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_5_6_5
78280af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
78380af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_5_5_5_1
78480af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
78580af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_4_4_4_4
78680af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
78780af0b9eSLuke Drummond     // RS_TYPE_MATRIX_4X4
78880af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
78980af0b9eSLuke Drummond     // RS_TYPE_MATRIX_3X3
79080af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
79180af0b9eSLuke Drummond     // RS_TYPE_MATRIX_2X2
79280af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
793a0f08674SEwan Crawford 
7945ec532a9SColin Riley //------------------------------------------------------------------
7955ec532a9SColin Riley // Static Functions
7965ec532a9SColin Riley //------------------------------------------------------------------
7975ec532a9SColin Riley LanguageRuntime *
798b9c1b51eSKate Stone RenderScriptRuntime::CreateInstance(Process *process,
799b9c1b51eSKate Stone                                     lldb::LanguageType language) {
8005ec532a9SColin Riley 
8015ec532a9SColin Riley   if (language == eLanguageTypeExtRenderScript)
8025ec532a9SColin Riley     return new RenderScriptRuntime(process);
8035ec532a9SColin Riley   else
804b3f7f69dSAidan Dodds     return nullptr;
8055ec532a9SColin Riley }
8065ec532a9SColin Riley 
80780af0b9eSLuke Drummond // Callback with a module to search for matching symbols. We first check that
80880af0b9eSLuke Drummond // the module contains RS kernels. Then look for a symbol which matches our
80980af0b9eSLuke Drummond // kernel name. The breakpoint address is finally set using the address of this
81080af0b9eSLuke Drummond // symbol.
81198156583SEwan Crawford Searcher::CallbackReturn
812b9c1b51eSKate Stone RSBreakpointResolver::SearchCallback(SearchFilter &filter,
813b9c1b51eSKate Stone                                      SymbolContext &context, Address *, bool) {
81498156583SEwan Crawford   ModuleSP module = context.module_sp;
81598156583SEwan Crawford 
816b3bbcb12SLuke Drummond   if (!module || !IsRenderScriptScriptModule(module))
81798156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
81898156583SEwan Crawford 
819b9c1b51eSKate Stone   // Attempt to set a breakpoint on the kernel name symbol within the module
82080af0b9eSLuke Drummond   // library. If it's not found, it's likely debug info is unavailable - try to
82180af0b9eSLuke Drummond   // set a breakpoint on <name>.expand.
822b9c1b51eSKate Stone   const Symbol *kernel_sym =
823b9c1b51eSKate Stone       module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
824b9c1b51eSKate Stone   if (!kernel_sym) {
82598156583SEwan Crawford     std::string kernel_name_expanded(m_kernel_name.AsCString());
82698156583SEwan Crawford     kernel_name_expanded.append(".expand");
827b9c1b51eSKate Stone     kernel_sym = module->FindFirstSymbolWithNameAndType(
828b9c1b51eSKate Stone         ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
82998156583SEwan Crawford   }
83098156583SEwan Crawford 
831b9c1b51eSKate Stone   if (kernel_sym) {
83298156583SEwan Crawford     Address bp_addr = kernel_sym->GetAddress();
83398156583SEwan Crawford     if (filter.AddressPasses(bp_addr))
83498156583SEwan Crawford       m_breakpoint->AddLocation(bp_addr);
83598156583SEwan Crawford   }
83698156583SEwan Crawford 
83798156583SEwan Crawford   return Searcher::eCallbackReturnContinue;
83898156583SEwan Crawford }
83998156583SEwan Crawford 
840b3bbcb12SLuke Drummond Searcher::CallbackReturn
841b3bbcb12SLuke Drummond RSReduceBreakpointResolver::SearchCallback(lldb_private::SearchFilter &filter,
842b3bbcb12SLuke Drummond                                            lldb_private::SymbolContext &context,
843b3bbcb12SLuke Drummond                                            Address *, bool) {
844b3bbcb12SLuke Drummond   // We need to have access to the list of reductions currently parsed, as
845b3bbcb12SLuke Drummond   // reduce names don't actually exist as
846b3bbcb12SLuke Drummond   // symbols in a module. They are only identifiable by parsing the .rs.info
847b3bbcb12SLuke Drummond   // packet, or finding the expand symbol. We
848b3bbcb12SLuke Drummond   // therefore need access to the list of parsed rs modules to properly resolve
849b3bbcb12SLuke Drummond   // reduction names.
850b3bbcb12SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
851b3bbcb12SLuke Drummond   ModuleSP module = context.module_sp;
852b3bbcb12SLuke Drummond 
853b3bbcb12SLuke Drummond   if (!module || !IsRenderScriptScriptModule(module))
854b3bbcb12SLuke Drummond     return Searcher::eCallbackReturnContinue;
855b3bbcb12SLuke Drummond 
856b3bbcb12SLuke Drummond   if (!m_rsmodules)
857b3bbcb12SLuke Drummond     return Searcher::eCallbackReturnContinue;
858b3bbcb12SLuke Drummond 
859b3bbcb12SLuke Drummond   for (const auto &module_desc : *m_rsmodules) {
860b3bbcb12SLuke Drummond     if (module_desc->m_module != module)
861b3bbcb12SLuke Drummond       continue;
862b3bbcb12SLuke Drummond 
863b3bbcb12SLuke Drummond     for (const auto &reduction : module_desc->m_reductions) {
864b3bbcb12SLuke Drummond       if (reduction.m_reduce_name != m_reduce_name)
865b3bbcb12SLuke Drummond         continue;
866b3bbcb12SLuke Drummond 
867b3bbcb12SLuke Drummond       std::array<std::pair<ConstString, int>, 5> funcs{
868b3bbcb12SLuke Drummond           {{reduction.m_init_name, eKernelTypeInit},
869b3bbcb12SLuke Drummond            {reduction.m_accum_name, eKernelTypeAccum},
870b3bbcb12SLuke Drummond            {reduction.m_comb_name, eKernelTypeComb},
871b3bbcb12SLuke Drummond            {reduction.m_outc_name, eKernelTypeOutC},
872b3bbcb12SLuke Drummond            {reduction.m_halter_name, eKernelTypeHalter}}};
873b3bbcb12SLuke Drummond 
874b3bbcb12SLuke Drummond       for (const auto &kernel : funcs) {
875b3bbcb12SLuke Drummond         // Skip constituent functions that don't match our spec
876b3bbcb12SLuke Drummond         if (!(m_kernel_types & kernel.second))
877b3bbcb12SLuke Drummond           continue;
878b3bbcb12SLuke Drummond 
879b3bbcb12SLuke Drummond         const auto kernel_name = kernel.first;
880b3bbcb12SLuke Drummond         const auto symbol = module->FindFirstSymbolWithNameAndType(
881b3bbcb12SLuke Drummond             kernel_name, eSymbolTypeCode);
882b3bbcb12SLuke Drummond         if (!symbol)
883b3bbcb12SLuke Drummond           continue;
884b3bbcb12SLuke Drummond 
885b3bbcb12SLuke Drummond         auto address = symbol->GetAddress();
886b3bbcb12SLuke Drummond         if (filter.AddressPasses(address)) {
887b3bbcb12SLuke Drummond           bool new_bp;
88881fc84faSLuke Drummond           if (!SkipPrologue(module, address)) {
88981fc84faSLuke Drummond             if (log)
89081fc84faSLuke Drummond               log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
89181fc84faSLuke Drummond           }
892b3bbcb12SLuke Drummond           m_breakpoint->AddLocation(address, &new_bp);
893b3bbcb12SLuke Drummond           if (log)
894b3bbcb12SLuke Drummond             log->Printf("%s: %s reduction breakpoint on %s in %s", __FUNCTION__,
895b3bbcb12SLuke Drummond                         new_bp ? "new" : "existing", kernel_name.GetCString(),
896b3bbcb12SLuke Drummond                         address.GetModule()->GetFileSpec().GetCString());
897b3bbcb12SLuke Drummond         }
898b3bbcb12SLuke Drummond       }
899b3bbcb12SLuke Drummond     }
900b3bbcb12SLuke Drummond   }
901b3bbcb12SLuke Drummond   return eCallbackReturnContinue;
902b3bbcb12SLuke Drummond }
903b3bbcb12SLuke Drummond 
90421fed052SAidan Dodds Searcher::CallbackReturn RSScriptGroupBreakpointResolver::SearchCallback(
90521fed052SAidan Dodds     SearchFilter &filter, SymbolContext &context, Address *addr,
90621fed052SAidan Dodds     bool containing) {
90721fed052SAidan Dodds 
90821fed052SAidan Dodds   if (!m_breakpoint)
90921fed052SAidan Dodds     return eCallbackReturnContinue;
91021fed052SAidan Dodds 
91121fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
91221fed052SAidan Dodds   ModuleSP &module = context.module_sp;
91321fed052SAidan Dodds 
91421fed052SAidan Dodds   if (!module || !IsRenderScriptScriptModule(module))
91521fed052SAidan Dodds     return Searcher::eCallbackReturnContinue;
91621fed052SAidan Dodds 
91721fed052SAidan Dodds   std::vector<std::string> names;
91821fed052SAidan Dodds   m_breakpoint->GetNames(names);
91921fed052SAidan Dodds   if (names.empty())
92021fed052SAidan Dodds     return eCallbackReturnContinue;
92121fed052SAidan Dodds 
92221fed052SAidan Dodds   for (auto &name : names) {
92321fed052SAidan Dodds     const RSScriptGroupDescriptorSP sg = FindScriptGroup(ConstString(name));
92421fed052SAidan Dodds     if (!sg) {
92521fed052SAidan Dodds       if (log)
92621fed052SAidan Dodds         log->Printf("%s: could not find script group for %s", __FUNCTION__,
92721fed052SAidan Dodds                     name.c_str());
92821fed052SAidan Dodds       continue;
92921fed052SAidan Dodds     }
93021fed052SAidan Dodds 
93121fed052SAidan Dodds     if (log)
93221fed052SAidan Dodds       log->Printf("%s: Found ScriptGroup for %s", __FUNCTION__, name.c_str());
93321fed052SAidan Dodds 
93421fed052SAidan Dodds     for (const RSScriptGroupDescriptor::Kernel &k : sg->m_kernels) {
93521fed052SAidan Dodds       if (log) {
93621fed052SAidan Dodds         log->Printf("%s: Adding breakpoint for %s", __FUNCTION__,
93721fed052SAidan Dodds                     k.m_name.AsCString());
93821fed052SAidan Dodds         log->Printf("%s: Kernel address 0x%" PRIx64, __FUNCTION__, k.m_addr);
93921fed052SAidan Dodds       }
94021fed052SAidan Dodds 
94121fed052SAidan Dodds       const lldb_private::Symbol *sym =
94221fed052SAidan Dodds           module->FindFirstSymbolWithNameAndType(k.m_name, eSymbolTypeCode);
94321fed052SAidan Dodds       if (!sym) {
94421fed052SAidan Dodds         if (log)
94521fed052SAidan Dodds           log->Printf("%s: Unable to find symbol for %s", __FUNCTION__,
94621fed052SAidan Dodds                       k.m_name.AsCString());
94721fed052SAidan Dodds         continue;
94821fed052SAidan Dodds       }
94921fed052SAidan Dodds 
95021fed052SAidan Dodds       if (log) {
95121fed052SAidan Dodds         log->Printf("%s: Found symbol name is %s", __FUNCTION__,
95221fed052SAidan Dodds                     sym->GetName().AsCString());
95321fed052SAidan Dodds       }
95421fed052SAidan Dodds 
95521fed052SAidan Dodds       auto address = sym->GetAddress();
95621fed052SAidan Dodds       if (!SkipPrologue(module, address)) {
95721fed052SAidan Dodds         if (log)
95821fed052SAidan Dodds           log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
95921fed052SAidan Dodds       }
96021fed052SAidan Dodds 
96121fed052SAidan Dodds       bool new_bp;
96221fed052SAidan Dodds       m_breakpoint->AddLocation(address, &new_bp);
96321fed052SAidan Dodds 
96421fed052SAidan Dodds       if (log)
96521fed052SAidan Dodds         log->Printf("%s: Placed %sbreakpoint on %s", __FUNCTION__,
96621fed052SAidan Dodds                     new_bp ? "new " : "", k.m_name.AsCString());
96721fed052SAidan Dodds 
96821fed052SAidan Dodds       // exit after placing the first breakpoint if we do not intend to stop
96921fed052SAidan Dodds       // on all kernels making up this script group
97021fed052SAidan Dodds       if (!m_stop_on_all)
97121fed052SAidan Dodds         break;
97221fed052SAidan Dodds     }
97321fed052SAidan Dodds   }
97421fed052SAidan Dodds 
97521fed052SAidan Dodds   return eCallbackReturnContinue;
97621fed052SAidan Dodds }
97721fed052SAidan Dodds 
978b9c1b51eSKate Stone void RenderScriptRuntime::Initialize() {
979b9c1b51eSKate Stone   PluginManager::RegisterPlugin(GetPluginNameStatic(),
980b9c1b51eSKate Stone                                 "RenderScript language support", CreateInstance,
981b3f7f69dSAidan Dodds                                 GetCommandObject);
9825ec532a9SColin Riley }
9835ec532a9SColin Riley 
984b9c1b51eSKate Stone void RenderScriptRuntime::Terminate() {
9855ec532a9SColin Riley   PluginManager::UnregisterPlugin(CreateInstance);
9865ec532a9SColin Riley }
9875ec532a9SColin Riley 
988b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginNameStatic() {
98980af0b9eSLuke Drummond   static ConstString plugin_name("renderscript");
99080af0b9eSLuke Drummond   return plugin_name;
9915ec532a9SColin Riley }
9925ec532a9SColin Riley 
993ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
994b9c1b51eSKate Stone RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
995b9c1b51eSKate Stone   if (module_sp) {
996b3bbcb12SLuke Drummond     if (IsRenderScriptScriptModule(module_sp))
997ef20b08fSColin Riley       return eModuleKindKernelObj;
9984640cde1SColin Riley 
9994640cde1SColin Riley     // Is this the main RS runtime library
10004640cde1SColin Riley     const ConstString rs_lib("libRS.so");
1001b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
10024640cde1SColin Riley       return eModuleKindLibRS;
10034640cde1SColin Riley     }
10044640cde1SColin Riley 
10054640cde1SColin Riley     const ConstString rs_driverlib("libRSDriver.so");
1006b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
10074640cde1SColin Riley       return eModuleKindDriver;
10084640cde1SColin Riley     }
10094640cde1SColin Riley 
101015f2bd95SEwan Crawford     const ConstString rs_cpureflib("libRSCpuRef.so");
1011b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
10124640cde1SColin Riley       return eModuleKindImpl;
10134640cde1SColin Riley     }
1014ef20b08fSColin Riley   }
1015ef20b08fSColin Riley   return eModuleKindIgnored;
1016ef20b08fSColin Riley }
1017ef20b08fSColin Riley 
1018b9c1b51eSKate Stone bool RenderScriptRuntime::IsRenderScriptModule(
1019b9c1b51eSKate Stone     const lldb::ModuleSP &module_sp) {
1020ef20b08fSColin Riley   return GetModuleKind(module_sp) != eModuleKindIgnored;
1021ef20b08fSColin Riley }
1022ef20b08fSColin Riley 
1023b9c1b51eSKate Stone void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
1024bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1025ef20b08fSColin Riley 
1026ef20b08fSColin Riley   size_t num_modules = module_list.GetSize();
1027b9c1b51eSKate Stone   for (size_t i = 0; i < num_modules; i++) {
1028ef20b08fSColin Riley     auto mod = module_list.GetModuleAtIndex(i);
1029b9c1b51eSKate Stone     if (IsRenderScriptModule(mod)) {
1030ef20b08fSColin Riley       LoadModule(mod);
1031ef20b08fSColin Riley     }
1032ef20b08fSColin Riley   }
1033ef20b08fSColin Riley }
1034ef20b08fSColin Riley 
10355ec532a9SColin Riley //------------------------------------------------------------------
10365ec532a9SColin Riley // PluginInterface protocol
10375ec532a9SColin Riley //------------------------------------------------------------------
1038b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginName() {
10395ec532a9SColin Riley   return GetPluginNameStatic();
10405ec532a9SColin Riley }
10415ec532a9SColin Riley 
1042b9c1b51eSKate Stone uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; }
10435ec532a9SColin Riley 
1044b9c1b51eSKate Stone bool RenderScriptRuntime::IsVTableName(const char *name) { return false; }
10455ec532a9SColin Riley 
1046b9c1b51eSKate Stone bool RenderScriptRuntime::GetDynamicTypeAndAddress(
1047b9c1b51eSKate Stone     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
10485f57b6eeSEnrico Granata     TypeAndOrName &class_type_or_name, Address &address,
1049b9c1b51eSKate Stone     Value::ValueType &value_type) {
10505ec532a9SColin Riley   return false;
10515ec532a9SColin Riley }
10525ec532a9SColin Riley 
1053c74275bcSEnrico Granata TypeAndOrName
1054b9c1b51eSKate Stone RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
1055b9c1b51eSKate Stone                                       ValueObject &static_value) {
1056c74275bcSEnrico Granata   return type_and_or_name;
1057c74275bcSEnrico Granata }
1058c74275bcSEnrico Granata 
1059b9c1b51eSKate Stone bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
10605ec532a9SColin Riley   return false;
10615ec532a9SColin Riley }
10625ec532a9SColin Riley 
10635ec532a9SColin Riley lldb::BreakpointResolverSP
106480af0b9eSLuke Drummond RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bp, bool catch_bp,
1065b9c1b51eSKate Stone                                              bool throw_bp) {
10665ec532a9SColin Riley   BreakpointResolverSP resolver_sp;
10675ec532a9SColin Riley   return resolver_sp;
10685ec532a9SColin Riley }
10695ec532a9SColin Riley 
1070b9c1b51eSKate Stone const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
1071b9c1b51eSKate Stone     {
10724640cde1SColin Riley         // rsdScript
1073b9c1b51eSKate Stone         {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
1074b9c1b51eSKate Stone                           "NS0_7ScriptCEPKcS7_PKhjj",
1075b9c1b51eSKate Stone          "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
1076b9c1b51eSKate Stone          "7ScriptCEPKcS7_PKhmj",
1077b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1078b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInit},
1079b9c1b51eSKate Stone         {"rsdScriptInvokeForEachMulti",
1080b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1081b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
1082b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1083b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
1084b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1085b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
1086b9c1b51eSKate Stone         {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
1087b9c1b51eSKate Stone                                   "script7ContextEPKNS0_6ScriptEjPvj",
1088b9c1b51eSKate Stone          "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
1089b9c1b51eSKate Stone          "6ScriptEjPvm",
1090b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1091b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
10924640cde1SColin Riley 
10934640cde1SColin Riley         // rsdAllocation
1094b9c1b51eSKate Stone         {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
1095b9c1b51eSKate Stone                               "ontextEPNS0_10AllocationEb",
1096b9c1b51eSKate Stone          "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
1097b9c1b51eSKate Stone          "10AllocationEb",
1098b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1099b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
1100b9c1b51eSKate Stone         {"rsdAllocationRead2D",
1101b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1102b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1103b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1104b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1105b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1106b9c1b51eSKate Stone         {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1107b9c1b51eSKate Stone                                  "ript7ContextEPNS0_10AllocationE",
1108b9c1b51eSKate Stone          "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1109b9c1b51eSKate Stone          "10AllocationE",
1110b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1111b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
111221fed052SAidan Dodds 
111321fed052SAidan Dodds         // renderscript script groups
111421fed052SAidan Dodds         {"rsdDebugHintScriptGroup2", "_ZN7android12renderscript21debugHintScrip"
111521fed052SAidan Dodds                                      "tGroup2EPKcjPKPFvPK24RsExpandKernelDriver"
111621fed052SAidan Dodds                                      "InfojjjEj",
111721fed052SAidan Dodds          "_ZN7android12renderscript21debugHintScriptGroup2EPKcjPKPFvPK24RsExpan"
111821fed052SAidan Dodds          "dKernelDriverInfojjjEj",
111921fed052SAidan Dodds          0, RenderScriptRuntime::eModuleKindImpl,
112021fed052SAidan Dodds          &lldb_private::RenderScriptRuntime::CaptureDebugHintScriptGroup2}};
11214640cde1SColin Riley 
1122b9c1b51eSKate Stone const size_t RenderScriptRuntime::s_runtimeHookCount =
1123b9c1b51eSKate Stone     sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
11244640cde1SColin Riley 
1125b9c1b51eSKate Stone bool RenderScriptRuntime::HookCallback(void *baton,
1126b9c1b51eSKate Stone                                        StoppointCallbackContext *ctx,
1127b9c1b51eSKate Stone                                        lldb::user_id_t break_id,
1128b9c1b51eSKate Stone                                        lldb::user_id_t break_loc_id) {
112980af0b9eSLuke Drummond   RuntimeHook *hook = (RuntimeHook *)baton;
113080af0b9eSLuke Drummond   ExecutionContext exe_ctx(ctx->exe_ctx_ref);
11314640cde1SColin Riley 
1132b3f7f69dSAidan Dodds   RenderScriptRuntime *lang_rt =
113380af0b9eSLuke Drummond       (RenderScriptRuntime *)exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1134b9c1b51eSKate Stone           eLanguageTypeExtRenderScript);
11354640cde1SColin Riley 
113680af0b9eSLuke Drummond   lang_rt->HookCallback(hook, exe_ctx);
11374640cde1SColin Riley 
11384640cde1SColin Riley   return false;
11394640cde1SColin Riley }
11404640cde1SColin Riley 
114180af0b9eSLuke Drummond void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
114280af0b9eSLuke Drummond                                        ExecutionContext &exe_ctx) {
11434640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11444640cde1SColin Riley 
11454640cde1SColin Riley   if (log)
114680af0b9eSLuke Drummond     log->Printf("%s - '%s'", __FUNCTION__, hook->defn->name);
11474640cde1SColin Riley 
114880af0b9eSLuke Drummond   if (hook->defn->grabber) {
114980af0b9eSLuke Drummond     (this->*(hook->defn->grabber))(hook, exe_ctx);
11504640cde1SColin Riley   }
11514640cde1SColin Riley }
11524640cde1SColin Riley 
115321fed052SAidan Dodds void RenderScriptRuntime::CaptureDebugHintScriptGroup2(
115421fed052SAidan Dodds     RuntimeHook *hook_info, ExecutionContext &context) {
115521fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
115621fed052SAidan Dodds 
115721fed052SAidan Dodds   enum {
115821fed052SAidan Dodds     eGroupName = 0,
115921fed052SAidan Dodds     eGroupNameSize,
116021fed052SAidan Dodds     eKernel,
116121fed052SAidan Dodds     eKernelCount,
116221fed052SAidan Dodds   };
116321fed052SAidan Dodds 
116421fed052SAidan Dodds   std::array<ArgItem, 4> args{{
116521fed052SAidan Dodds       {ArgItem::ePointer, 0}, // const char         *groupName
116621fed052SAidan Dodds       {ArgItem::eInt32, 0},   // const uint32_t      groupNameSize
116721fed052SAidan Dodds       {ArgItem::ePointer, 0}, // const ExpandFuncTy *kernel
116821fed052SAidan Dodds       {ArgItem::eInt32, 0},   // const uint32_t      kernelCount
116921fed052SAidan Dodds   }};
117021fed052SAidan Dodds 
117121fed052SAidan Dodds   if (!GetArgs(context, args.data(), args.size())) {
117221fed052SAidan Dodds     if (log)
117321fed052SAidan Dodds       log->Printf("%s - Error while reading the function parameters",
117421fed052SAidan Dodds                   __FUNCTION__);
117521fed052SAidan Dodds     return;
117621fed052SAidan Dodds   } else if (log) {
117721fed052SAidan Dodds     log->Printf("%s - groupName    : 0x%" PRIx64, __FUNCTION__,
117821fed052SAidan Dodds                 addr_t(args[eGroupName]));
117921fed052SAidan Dodds     log->Printf("%s - groupNameSize: %" PRIu64, __FUNCTION__,
118021fed052SAidan Dodds                 uint64_t(args[eGroupNameSize]));
118121fed052SAidan Dodds     log->Printf("%s - kernel       : 0x%" PRIx64, __FUNCTION__,
118221fed052SAidan Dodds                 addr_t(args[eKernel]));
118321fed052SAidan Dodds     log->Printf("%s - kernelCount  : %" PRIu64, __FUNCTION__,
118421fed052SAidan Dodds                 uint64_t(args[eKernelCount]));
118521fed052SAidan Dodds   }
118621fed052SAidan Dodds 
118721fed052SAidan Dodds   // parse script group name
118821fed052SAidan Dodds   ConstString group_name;
118921fed052SAidan Dodds   {
119021fed052SAidan Dodds     Error err;
119121fed052SAidan Dodds     const uint64_t len = uint64_t(args[eGroupNameSize]);
119221fed052SAidan Dodds     std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]);
119321fed052SAidan Dodds     m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err);
119421fed052SAidan Dodds     buffer.get()[len] = '\0';
119521fed052SAidan Dodds     if (!err.Success()) {
119621fed052SAidan Dodds       if (log)
119721fed052SAidan Dodds         log->Printf("Error reading scriptgroup name from target");
119821fed052SAidan Dodds       return;
119921fed052SAidan Dodds     } else {
120021fed052SAidan Dodds       if (log)
120121fed052SAidan Dodds         log->Printf("Extracted scriptgroup name %s", buffer.get());
120221fed052SAidan Dodds     }
120321fed052SAidan Dodds     // write back the script group name
120421fed052SAidan Dodds     group_name.SetCString(buffer.get());
120521fed052SAidan Dodds   }
120621fed052SAidan Dodds 
120721fed052SAidan Dodds   // create or access existing script group
120821fed052SAidan Dodds   RSScriptGroupDescriptorSP group;
120921fed052SAidan Dodds   {
121021fed052SAidan Dodds     // search for existing script group
121121fed052SAidan Dodds     for (auto sg : m_scriptGroups) {
121221fed052SAidan Dodds       if (sg->m_name == group_name) {
121321fed052SAidan Dodds         group = sg;
121421fed052SAidan Dodds         break;
121521fed052SAidan Dodds       }
121621fed052SAidan Dodds     }
121721fed052SAidan Dodds     if (!group) {
121821fed052SAidan Dodds       group.reset(new RSScriptGroupDescriptor);
121921fed052SAidan Dodds       group->m_name = group_name;
122021fed052SAidan Dodds       m_scriptGroups.push_back(group);
122121fed052SAidan Dodds     } else {
122221fed052SAidan Dodds       // already have this script group
122321fed052SAidan Dodds       if (log)
122421fed052SAidan Dodds         log->Printf("Attempt to add duplicate script group %s",
122521fed052SAidan Dodds                     group_name.AsCString());
122621fed052SAidan Dodds       return;
122721fed052SAidan Dodds     }
122821fed052SAidan Dodds   }
122921fed052SAidan Dodds   assert(group);
123021fed052SAidan Dodds 
123121fed052SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
123221fed052SAidan Dodds   std::vector<addr_t> kernels;
123321fed052SAidan Dodds   // parse kernel addresses in script group
123421fed052SAidan Dodds   for (uint64_t i = 0; i < uint64_t(args[eKernelCount]); ++i) {
123521fed052SAidan Dodds     RSScriptGroupDescriptor::Kernel kernel;
123621fed052SAidan Dodds     // extract script group kernel addresses from the target
123721fed052SAidan Dodds     const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size;
123821fed052SAidan Dodds     uint64_t kernel_addr = 0;
123921fed052SAidan Dodds     Error err;
124021fed052SAidan Dodds     size_t read =
124121fed052SAidan Dodds         m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err);
124221fed052SAidan Dodds     if (!err.Success() || read != target_ptr_size) {
124321fed052SAidan Dodds       if (log)
124421fed052SAidan Dodds         log->Printf("Error parsing kernel address %" PRIu64 " in script group",
124521fed052SAidan Dodds                     i);
124621fed052SAidan Dodds       return;
124721fed052SAidan Dodds     }
124821fed052SAidan Dodds     if (log)
124921fed052SAidan Dodds       log->Printf("Extracted scriptgroup kernel address - 0x%" PRIx64,
125021fed052SAidan Dodds                   kernel_addr);
125121fed052SAidan Dodds     kernel.m_addr = kernel_addr;
125221fed052SAidan Dodds 
125321fed052SAidan Dodds     // try to resolve the associated kernel name
125421fed052SAidan Dodds     if (!ResolveKernelName(kernel.m_addr, kernel.m_name)) {
125521fed052SAidan Dodds       if (log)
125621fed052SAidan Dodds         log->Printf("Parsed scriptgroup kernel %" PRIu64 " - 0x%" PRIx64, i,
125721fed052SAidan Dodds                     kernel_addr);
125821fed052SAidan Dodds       return;
125921fed052SAidan Dodds     }
126021fed052SAidan Dodds 
126121fed052SAidan Dodds     // try to find the non '.expand' function
126221fed052SAidan Dodds     {
126321fed052SAidan Dodds       const llvm::StringRef expand(".expand");
126421fed052SAidan Dodds       const llvm::StringRef name_ref = kernel.m_name.GetStringRef();
126521fed052SAidan Dodds       if (name_ref.endswith(expand)) {
126621fed052SAidan Dodds         const ConstString base_kernel(name_ref.drop_back(expand.size()));
126721fed052SAidan Dodds         // verify this function is a valid kernel
126821fed052SAidan Dodds         if (IsKnownKernel(base_kernel)) {
126921fed052SAidan Dodds           kernel.m_name = base_kernel;
127021fed052SAidan Dodds           if (log)
127121fed052SAidan Dodds             log->Printf("%s - found non expand version '%s'", __FUNCTION__,
127221fed052SAidan Dodds                         base_kernel.GetCString());
127321fed052SAidan Dodds         }
127421fed052SAidan Dodds       }
127521fed052SAidan Dodds     }
127621fed052SAidan Dodds     // add to a list of script group kernels we know about
127721fed052SAidan Dodds     group->m_kernels.push_back(kernel);
127821fed052SAidan Dodds   }
127921fed052SAidan Dodds 
128021fed052SAidan Dodds   // Resolve any pending scriptgroup breakpoints
128121fed052SAidan Dodds   {
128221fed052SAidan Dodds     Target &target = m_process->GetTarget();
128321fed052SAidan Dodds     const BreakpointList &list = target.GetBreakpointList();
128421fed052SAidan Dodds     const size_t num_breakpoints = list.GetSize();
128521fed052SAidan Dodds     if (log)
128621fed052SAidan Dodds       log->Printf("Resolving %zu breakpoints", num_breakpoints);
128721fed052SAidan Dodds     for (size_t i = 0; i < num_breakpoints; ++i) {
128821fed052SAidan Dodds       const BreakpointSP bp = list.GetBreakpointAtIndex(i);
128921fed052SAidan Dodds       if (bp) {
129021fed052SAidan Dodds         if (bp->MatchesName(group_name.AsCString())) {
129121fed052SAidan Dodds           if (log)
129221fed052SAidan Dodds             log->Printf("Found breakpoint with name %s",
129321fed052SAidan Dodds                         group_name.AsCString());
129421fed052SAidan Dodds           bp->ResolveBreakpoint();
129521fed052SAidan Dodds         }
129621fed052SAidan Dodds       }
129721fed052SAidan Dodds     }
129821fed052SAidan Dodds   }
129921fed052SAidan Dodds }
130021fed052SAidan Dodds 
1301b9c1b51eSKate Stone void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
130280af0b9eSLuke Drummond     RuntimeHook *hook, ExecutionContext &exe_ctx) {
1303e09c44b6SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1304e09c44b6SAidan Dodds 
1305b9c1b51eSKate Stone   enum {
1306f4786785SAidan Dodds     eRsContext = 0,
1307f4786785SAidan Dodds     eRsScript,
1308f4786785SAidan Dodds     eRsSlot,
1309f4786785SAidan Dodds     eRsAIns,
1310f4786785SAidan Dodds     eRsInLen,
1311f4786785SAidan Dodds     eRsAOut,
1312f4786785SAidan Dodds     eRsUsr,
1313f4786785SAidan Dodds     eRsUsrLen,
1314f4786785SAidan Dodds     eRsSc,
1315f4786785SAidan Dodds   };
1316e09c44b6SAidan Dodds 
13171ee07253SSaleem Abdulrasool   std::array<ArgItem, 9> args{{
1318f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Context       *rsc
1319f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Script              *s
1320f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // uint32_t             slot
1321f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Allocation   **aIns
1322f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               inLen
1323f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Allocation          *aout
1324f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const void          *usr
1325f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               usrLen
1326f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall  *sc
13271ee07253SSaleem Abdulrasool   }};
1328e09c44b6SAidan Dodds 
132980af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1330b9c1b51eSKate Stone   if (!success) {
1331e09c44b6SAidan Dodds     if (log)
1332b9c1b51eSKate Stone       log->Printf("%s - Error while reading the function parameters",
1333b9c1b51eSKate Stone                   __FUNCTION__);
1334e09c44b6SAidan Dodds     return;
1335e09c44b6SAidan Dodds   }
1336e09c44b6SAidan Dodds 
1337e09c44b6SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
133880af0b9eSLuke Drummond   Error err;
1339e09c44b6SAidan Dodds   std::vector<uint64_t> allocs;
1340e09c44b6SAidan Dodds 
1341e09c44b6SAidan Dodds   // traverse allocation list
1342b9c1b51eSKate Stone   for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1343e09c44b6SAidan Dodds     // calculate offest to allocation pointer
1344f4786785SAidan Dodds     const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1345e09c44b6SAidan Dodds 
134680af0b9eSLuke Drummond     // Note: due to little endian layout, reading 32bits or 64bits into res
134780af0b9eSLuke Drummond     // will give the correct results.
134880af0b9eSLuke Drummond     uint64_t result = 0;
134980af0b9eSLuke Drummond     size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
135080af0b9eSLuke Drummond     if (read != target_ptr_size || !err.Success()) {
1351e09c44b6SAidan Dodds       if (log)
1352b9c1b51eSKate Stone         log->Printf(
1353b9c1b51eSKate Stone             "%s - Error while reading allocation list argument %" PRIu64,
1354b9c1b51eSKate Stone             __FUNCTION__, i);
1355b9c1b51eSKate Stone     } else {
135680af0b9eSLuke Drummond       allocs.push_back(result);
1357e09c44b6SAidan Dodds     }
1358e09c44b6SAidan Dodds   }
1359e09c44b6SAidan Dodds 
1360e09c44b6SAidan Dodds   // if there is an output allocation track it
136180af0b9eSLuke Drummond   if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
136280af0b9eSLuke Drummond     allocs.push_back(alloc_out);
1363e09c44b6SAidan Dodds   }
1364e09c44b6SAidan Dodds 
1365e09c44b6SAidan Dodds   // for all allocations we have found
1366b9c1b51eSKate Stone   for (const uint64_t alloc_addr : allocs) {
13675d057637SLuke Drummond     AllocationDetails *alloc = LookUpAllocation(alloc_addr);
13685d057637SLuke Drummond     if (!alloc)
13695d057637SLuke Drummond       alloc = CreateAllocation(alloc_addr);
13705d057637SLuke Drummond 
1371b9c1b51eSKate Stone     if (alloc) {
1372e09c44b6SAidan Dodds       // save the allocation address
1373b9c1b51eSKate Stone       if (alloc->address.isValid()) {
1374e09c44b6SAidan Dodds         // check the allocation address we already have matches
1375e09c44b6SAidan Dodds         assert(*alloc->address.get() == alloc_addr);
1376b9c1b51eSKate Stone       } else {
1377e09c44b6SAidan Dodds         alloc->address = alloc_addr;
1378e09c44b6SAidan Dodds       }
1379e09c44b6SAidan Dodds 
1380e09c44b6SAidan Dodds       // save the context
1381b9c1b51eSKate Stone       if (log) {
1382b9c1b51eSKate Stone         if (alloc->context.isValid() &&
1383b9c1b51eSKate Stone             *alloc->context.get() != addr_t(args[eRsContext]))
1384b9c1b51eSKate Stone           log->Printf("%s - Allocation used by multiple contexts",
1385b9c1b51eSKate Stone                       __FUNCTION__);
1386e09c44b6SAidan Dodds       }
1387f4786785SAidan Dodds       alloc->context = addr_t(args[eRsContext]);
1388e09c44b6SAidan Dodds     }
1389e09c44b6SAidan Dodds   }
1390e09c44b6SAidan Dodds 
1391e09c44b6SAidan Dodds   // make sure we track this script object
1392b9c1b51eSKate Stone   if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1393b9c1b51eSKate Stone           LookUpScript(addr_t(args[eRsScript]), true)) {
1394b9c1b51eSKate Stone     if (log) {
1395b9c1b51eSKate Stone       if (script->context.isValid() &&
1396b9c1b51eSKate Stone           *script->context.get() != addr_t(args[eRsContext]))
1397b3f7f69dSAidan Dodds         log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1398e09c44b6SAidan Dodds     }
1399f4786785SAidan Dodds     script->context = addr_t(args[eRsContext]);
1400e09c44b6SAidan Dodds   }
1401e09c44b6SAidan Dodds }
1402e09c44b6SAidan Dodds 
140380af0b9eSLuke Drummond void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1404b9c1b51eSKate Stone                                               ExecutionContext &context) {
14054640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14064640cde1SColin Riley 
1407b9c1b51eSKate Stone   enum {
1408f4786785SAidan Dodds     eRsContext,
1409f4786785SAidan Dodds     eRsScript,
1410f4786785SAidan Dodds     eRsId,
1411f4786785SAidan Dodds     eRsData,
1412f4786785SAidan Dodds     eRsLength,
1413f4786785SAidan Dodds   };
14144640cde1SColin Riley 
14151ee07253SSaleem Abdulrasool   std::array<ArgItem, 5> args{{
1416f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1417f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsScript
1418f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsId
1419f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsData
1420f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsLength
14211ee07253SSaleem Abdulrasool   }};
14224640cde1SColin Riley 
1423f4786785SAidan Dodds   bool success = GetArgs(context, &args[0], args.size());
1424b9c1b51eSKate Stone   if (!success) {
142582780287SAidan Dodds     if (log)
1426b3f7f69dSAidan Dodds       log->Printf("%s - error reading the function parameters.", __FUNCTION__);
142782780287SAidan Dodds     return;
142882780287SAidan Dodds   }
14294640cde1SColin Riley 
1430b9c1b51eSKate Stone   if (log) {
1431b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1432b9c1b51eSKate Stone                 ":%" PRIu64 "bytes.",
1433b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1434b9c1b51eSKate Stone                 uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1435f4786785SAidan Dodds                 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
14364640cde1SColin Riley 
1437f4786785SAidan Dodds     addr_t script_addr = addr_t(args[eRsScript]);
1438b9c1b51eSKate Stone     if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
14394640cde1SColin Riley       auto rsm = m_scriptMappings[script_addr];
1440b9c1b51eSKate Stone       if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1441f4786785SAidan Dodds         auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1442b9c1b51eSKate Stone         log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__,
1443b9c1b51eSKate Stone                     rsg.m_name.AsCString(),
1444f4786785SAidan Dodds                     rsm->m_module->GetFileSpec().GetFilename().AsCString());
14454640cde1SColin Riley       }
14464640cde1SColin Riley     }
14474640cde1SColin Riley   }
14484640cde1SColin Riley }
14494640cde1SColin Riley 
145080af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
145180af0b9eSLuke Drummond                                                 ExecutionContext &exe_ctx) {
14524640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14534640cde1SColin Riley 
1454b9c1b51eSKate Stone   enum { eRsContext, eRsAlloc, eRsForceZero };
14554640cde1SColin Riley 
14561ee07253SSaleem Abdulrasool   std::array<ArgItem, 3> args{{
1457f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1458f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1459f4786785SAidan Dodds       ArgItem{ArgItem::eBool, 0},    // eRsForceZero
14601ee07253SSaleem Abdulrasool   }};
14614640cde1SColin Riley 
146280af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
146380af0b9eSLuke Drummond   if (!success) {
146482780287SAidan Dodds     if (log)
1465b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters",
1466b9c1b51eSKate Stone                   __FUNCTION__);
146780af0b9eSLuke Drummond     return;
146882780287SAidan Dodds   }
14694640cde1SColin Riley 
14704640cde1SColin Riley   if (log)
1471b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1472b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1473f4786785SAidan Dodds                 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
147478f339d1SEwan Crawford 
14755d057637SLuke Drummond   AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
147678f339d1SEwan Crawford   if (alloc)
1477f4786785SAidan Dodds     alloc->context = uint64_t(args[eRsContext]);
14784640cde1SColin Riley }
14794640cde1SColin Riley 
148080af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
148180af0b9eSLuke Drummond                                                    ExecutionContext &exe_ctx) {
1482e69df382SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1483e69df382SEwan Crawford 
1484b9c1b51eSKate Stone   enum {
1485f4786785SAidan Dodds     eRsContext,
1486f4786785SAidan Dodds     eRsAlloc,
1487f4786785SAidan Dodds   };
1488e69df382SEwan Crawford 
14891ee07253SSaleem Abdulrasool   std::array<ArgItem, 2> args{{
1490f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1491f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
14921ee07253SSaleem Abdulrasool   }};
1493f4786785SAidan Dodds 
149480af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1495b9c1b51eSKate Stone   if (!success) {
1496e69df382SEwan Crawford     if (log)
1497b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1498b9c1b51eSKate Stone                   __FUNCTION__);
1499b3f7f69dSAidan Dodds     return;
1500e69df382SEwan Crawford   }
1501e69df382SEwan Crawford 
1502e69df382SEwan Crawford   if (log)
1503b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1504b9c1b51eSKate Stone                 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1505e69df382SEwan Crawford 
1506b9c1b51eSKate Stone   for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1507e69df382SEwan Crawford     auto &allocation_ap = *iter; // get the unique pointer
1508b9c1b51eSKate Stone     if (allocation_ap->address.isValid() &&
1509b9c1b51eSKate Stone         *allocation_ap->address.get() == addr_t(args[eRsAlloc])) {
1510e69df382SEwan Crawford       m_allocations.erase(iter);
1511e69df382SEwan Crawford       if (log)
1512b3f7f69dSAidan Dodds         log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1513e69df382SEwan Crawford       return;
1514e69df382SEwan Crawford     }
1515e69df382SEwan Crawford   }
1516e69df382SEwan Crawford 
1517e69df382SEwan Crawford   if (log)
1518b3f7f69dSAidan Dodds     log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1519e69df382SEwan Crawford }
1520e69df382SEwan Crawford 
152180af0b9eSLuke Drummond void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
152280af0b9eSLuke Drummond                                             ExecutionContext &exe_ctx) {
15234640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
15244640cde1SColin Riley 
152580af0b9eSLuke Drummond   Error err;
152680af0b9eSLuke Drummond   Process *process = exe_ctx.GetProcessPtr();
15274640cde1SColin Riley 
1528b9c1b51eSKate Stone   enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
15294640cde1SColin Riley 
1530b9c1b51eSKate Stone   std::array<ArgItem, 4> args{
1531b9c1b51eSKate Stone       {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
15321ee07253SSaleem Abdulrasool        ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
153380af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1534b9c1b51eSKate Stone   if (!success) {
153582780287SAidan Dodds     if (log)
1536b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1537b9c1b51eSKate Stone                   __FUNCTION__);
153882780287SAidan Dodds     return;
153982780287SAidan Dodds   }
154082780287SAidan Dodds 
154180af0b9eSLuke Drummond   std::string res_name;
154280af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
154380af0b9eSLuke Drummond   if (err.Fail()) {
15444640cde1SColin Riley     if (log)
154580af0b9eSLuke Drummond       log->Printf("%s - error reading res_name: %s.", __FUNCTION__,
154680af0b9eSLuke Drummond                   err.AsCString());
15474640cde1SColin Riley   }
15484640cde1SColin Riley 
154980af0b9eSLuke Drummond   std::string cache_dir;
155080af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
155180af0b9eSLuke Drummond   if (err.Fail()) {
15524640cde1SColin Riley     if (log)
155380af0b9eSLuke Drummond       log->Printf("%s - error reading cache_dir: %s.", __FUNCTION__,
155480af0b9eSLuke Drummond                   err.AsCString());
15554640cde1SColin Riley   }
15564640cde1SColin Riley 
15574640cde1SColin Riley   if (log)
1558b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1559b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
156080af0b9eSLuke Drummond                 uint64_t(args[eRsScript]), res_name.c_str(), cache_dir.c_str());
15614640cde1SColin Riley 
156280af0b9eSLuke Drummond   if (res_name.size() > 0) {
15634640cde1SColin Riley     StreamString strm;
156480af0b9eSLuke Drummond     strm.Printf("librs.%s.so", res_name.c_str());
15654640cde1SColin Riley 
1566f4786785SAidan Dodds     ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1567b9c1b51eSKate Stone     if (script) {
156878f339d1SEwan Crawford       script->type = ScriptDetails::eScriptC;
156980af0b9eSLuke Drummond       script->cache_dir = cache_dir;
157080af0b9eSLuke Drummond       script->res_name = res_name;
1571c156427dSZachary Turner       script->shared_lib = strm.GetString();
1572f4786785SAidan Dodds       script->context = addr_t(args[eRsContext]);
157378f339d1SEwan Crawford     }
15744640cde1SColin Riley 
15754640cde1SColin Riley     if (log)
1576b9c1b51eSKate Stone       log->Printf("%s - '%s' tagged with context 0x%" PRIx64
1577b9c1b51eSKate Stone                   " and script 0x%" PRIx64 ".",
1578b9c1b51eSKate Stone                   __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1579b9c1b51eSKate Stone                   uint64_t(args[eRsScript]));
1580b9c1b51eSKate Stone   } else if (log) {
1581b3f7f69dSAidan Dodds     log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
15824640cde1SColin Riley   }
15834640cde1SColin Riley }
15844640cde1SColin Riley 
1585b9c1b51eSKate Stone void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1586b9c1b51eSKate Stone                                            ModuleKind kind) {
15874640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
15884640cde1SColin Riley 
1589b9c1b51eSKate Stone   if (!module) {
15904640cde1SColin Riley     return;
15914640cde1SColin Riley   }
15924640cde1SColin Riley 
159382780287SAidan Dodds   Target &target = GetProcess()->GetTarget();
159421fed052SAidan Dodds   const llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
159582780287SAidan Dodds 
159680af0b9eSLuke Drummond   if (machine != llvm::Triple::ArchType::x86 &&
159780af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::arm &&
159880af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::aarch64 &&
159980af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mipsel &&
160080af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mips64el &&
160180af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::x86_64) {
16024640cde1SColin Riley     if (log)
1603b3f7f69dSAidan Dodds       log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
16044640cde1SColin Riley     return;
16054640cde1SColin Riley   }
16064640cde1SColin Riley 
160721fed052SAidan Dodds   const uint32_t target_ptr_size =
160821fed052SAidan Dodds       target.GetArchitecture().GetAddressByteSize();
160921fed052SAidan Dodds 
161021fed052SAidan Dodds   std::array<bool, s_runtimeHookCount> hook_placed;
161121fed052SAidan Dodds   hook_placed.fill(false);
16124640cde1SColin Riley 
1613b9c1b51eSKate Stone   for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
16144640cde1SColin Riley     const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1615b9c1b51eSKate Stone     if (hook_defn->kind != kind) {
16164640cde1SColin Riley       continue;
16174640cde1SColin Riley     }
16184640cde1SColin Riley 
161980af0b9eSLuke Drummond     const char *symbol_name = (target_ptr_size == 4)
162080af0b9eSLuke Drummond                                   ? hook_defn->symbol_name_m32
1621b9c1b51eSKate Stone                                   : hook_defn->symbol_name_m64;
162282780287SAidan Dodds 
1623b9c1b51eSKate Stone     const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1624b9c1b51eSKate Stone         ConstString(symbol_name), eSymbolTypeCode);
1625b9c1b51eSKate Stone     if (!sym) {
1626b9c1b51eSKate Stone       if (log) {
1627b3f7f69dSAidan Dodds         log->Printf("%s - symbol '%s' related to the function %s not found",
1628b3f7f69dSAidan Dodds                     __FUNCTION__, symbol_name, hook_defn->name);
162982780287SAidan Dodds       }
163082780287SAidan Dodds       continue;
163182780287SAidan Dodds     }
16324640cde1SColin Riley 
1633358cf1eaSGreg Clayton     addr_t addr = sym->GetLoadAddress(&target);
1634b9c1b51eSKate Stone     if (addr == LLDB_INVALID_ADDRESS) {
16354640cde1SColin Riley       if (log)
1636b9c1b51eSKate Stone         log->Printf("%s - unable to resolve the address of hook function '%s' "
1637b9c1b51eSKate Stone                     "with symbol '%s'.",
1638b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, symbol_name);
16394640cde1SColin Riley       continue;
1640b9c1b51eSKate Stone     } else {
164182780287SAidan Dodds       if (log)
1642b3f7f69dSAidan Dodds         log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1643b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, addr);
164482780287SAidan Dodds     }
16454640cde1SColin Riley 
16464640cde1SColin Riley     RuntimeHookSP hook(new RuntimeHook());
16474640cde1SColin Riley     hook->address = addr;
16484640cde1SColin Riley     hook->defn = hook_defn;
16494640cde1SColin Riley     hook->bp_sp = target.CreateBreakpoint(addr, true, false);
16504640cde1SColin Riley     hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
16514640cde1SColin Riley     m_runtimeHooks[addr] = hook;
1652b9c1b51eSKate Stone     if (log) {
1653b9c1b51eSKate Stone       log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64
1654b9c1b51eSKate Stone                   " at 0x%" PRIx64 ".",
1655b9c1b51eSKate Stone                   __FUNCTION__, hook_defn->name,
1656b9c1b51eSKate Stone                   module->GetFileSpec().GetFilename().AsCString(),
1657b3f7f69dSAidan Dodds                   (uint64_t)hook_defn->version, (uint64_t)addr);
16584640cde1SColin Riley     }
165921fed052SAidan Dodds     hook_placed[idx] = true;
166021fed052SAidan Dodds   }
166121fed052SAidan Dodds 
166221fed052SAidan Dodds   // log any unhooked function
166321fed052SAidan Dodds   if (log) {
166421fed052SAidan Dodds     for (size_t i = 0; i < hook_placed.size(); ++i) {
166521fed052SAidan Dodds       if (hook_placed[i])
166621fed052SAidan Dodds         continue;
166721fed052SAidan Dodds       const HookDefn &hook_defn = s_runtimeHookDefns[i];
166821fed052SAidan Dodds       if (hook_defn.kind != kind)
166921fed052SAidan Dodds         continue;
167021fed052SAidan Dodds       log->Printf("%s - function %s was not hooked", __FUNCTION__,
167121fed052SAidan Dodds                   hook_defn.name);
167221fed052SAidan Dodds     }
16734640cde1SColin Riley   }
16744640cde1SColin Riley }
16754640cde1SColin Riley 
1676b9c1b51eSKate Stone void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
16774640cde1SColin Riley   if (!rsmodule_sp)
16784640cde1SColin Riley     return;
16794640cde1SColin Riley 
16804640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
16814640cde1SColin Riley 
16824640cde1SColin Riley   const ModuleSP module = rsmodule_sp->m_module;
16834640cde1SColin Riley   const FileSpec &file = module->GetPlatformFileSpec();
16844640cde1SColin Riley 
168578f339d1SEwan Crawford   // Iterate over all of the scripts that we currently know of.
168678f339d1SEwan Crawford   // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
1687b9c1b51eSKate Stone   for (const auto &rs_script : m_scripts) {
168878f339d1SEwan Crawford     // Extract the expected .so file path for this script.
168980af0b9eSLuke Drummond     std::string shared_lib;
169080af0b9eSLuke Drummond     if (!rs_script->shared_lib.get(shared_lib))
169178f339d1SEwan Crawford       continue;
169278f339d1SEwan Crawford 
169378f339d1SEwan Crawford     // Only proceed if the module that has loaded corresponds to this script.
169480af0b9eSLuke Drummond     if (file.GetFilename() != ConstString(shared_lib.c_str()))
169578f339d1SEwan Crawford       continue;
169678f339d1SEwan Crawford 
169778f339d1SEwan Crawford     // Obtain the script address which we use as a key.
169878f339d1SEwan Crawford     lldb::addr_t script;
169978f339d1SEwan Crawford     if (!rs_script->script.get(script))
170078f339d1SEwan Crawford       continue;
170178f339d1SEwan Crawford 
170278f339d1SEwan Crawford     // If we have a script mapping for the current script.
1703b9c1b51eSKate Stone     if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
170478f339d1SEwan Crawford       // if the module we have stored is different to the one we just received.
1705b9c1b51eSKate Stone       if (m_scriptMappings[script] != rsmodule_sp) {
17064640cde1SColin Riley         if (log)
1707b9c1b51eSKate Stone           log->Printf(
1708b9c1b51eSKate Stone               "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1709b9c1b51eSKate Stone               __FUNCTION__, (uint64_t)script,
1710b9c1b51eSKate Stone               rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
17114640cde1SColin Riley       }
17124640cde1SColin Riley     }
171378f339d1SEwan Crawford     // We don't have a script mapping for the current script.
1714b9c1b51eSKate Stone     else {
171578f339d1SEwan Crawford       // Obtain the script resource name.
171680af0b9eSLuke Drummond       std::string res_name;
171780af0b9eSLuke Drummond       if (rs_script->res_name.get(res_name))
171878f339d1SEwan Crawford         // Set the modules resource name.
171980af0b9eSLuke Drummond         rsmodule_sp->m_resname = res_name;
172078f339d1SEwan Crawford       // Add Script/Module pair to map.
172178f339d1SEwan Crawford       m_scriptMappings[script] = rsmodule_sp;
17224640cde1SColin Riley       if (log)
1723b9c1b51eSKate Stone         log->Printf(
1724b9c1b51eSKate Stone             "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1725b9c1b51eSKate Stone             __FUNCTION__, (uint64_t)script,
1726b9c1b51eSKate Stone             rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
17274640cde1SColin Riley     }
17284640cde1SColin Riley   }
17294640cde1SColin Riley }
17304640cde1SColin Riley 
1731b9c1b51eSKate Stone // Uses the Target API to evaluate the expression passed as a parameter to the
173280af0b9eSLuke Drummond // function The result of that expression is returned an unsigned 64 bit int,
173380af0b9eSLuke Drummond // via the result* parameter. Function returns true on success, and false on
173480af0b9eSLuke Drummond // failure
173580af0b9eSLuke Drummond bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1736b9c1b51eSKate Stone                                            StackFrame *frame_ptr,
1737b9c1b51eSKate Stone                                            uint64_t *result) {
173815f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
173915f2bd95SEwan Crawford   if (log)
174080af0b9eSLuke Drummond     log->Printf("%s(%s)", __FUNCTION__, expr);
174115f2bd95SEwan Crawford 
174215f2bd95SEwan Crawford   ValueObjectSP expr_result;
17438433fdbeSAidan Dodds   EvaluateExpressionOptions options;
17448433fdbeSAidan Dodds   options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
174515f2bd95SEwan Crawford   // Perform the actual expression evaluation
174680af0b9eSLuke Drummond   auto &target = GetProcess()->GetTarget();
174780af0b9eSLuke Drummond   target.EvaluateExpression(expr, frame_ptr, expr_result, options);
174815f2bd95SEwan Crawford 
1749b9c1b51eSKate Stone   if (!expr_result) {
175015f2bd95SEwan Crawford     if (log)
1751b3f7f69dSAidan Dodds       log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
175215f2bd95SEwan Crawford     return false;
175315f2bd95SEwan Crawford   }
175415f2bd95SEwan Crawford 
175515f2bd95SEwan Crawford   // The result of the expression is invalid
1756b9c1b51eSKate Stone   if (!expr_result->GetError().Success()) {
175715f2bd95SEwan Crawford     Error err = expr_result->GetError();
175880af0b9eSLuke Drummond     // Expression returned is void, so this is actually a success
175980af0b9eSLuke Drummond     if (err.GetError() == UserExpression::kNoResult) {
176015f2bd95SEwan Crawford       if (log)
1761b3f7f69dSAidan Dodds         log->Printf("%s - expression returned void.", __FUNCTION__);
176215f2bd95SEwan Crawford 
176315f2bd95SEwan Crawford       result = nullptr;
176415f2bd95SEwan Crawford       return true;
176515f2bd95SEwan Crawford     }
176615f2bd95SEwan Crawford 
176715f2bd95SEwan Crawford     if (log)
1768b3f7f69dSAidan Dodds       log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1769b3f7f69dSAidan Dodds                   err.AsCString());
177015f2bd95SEwan Crawford     return false;
177115f2bd95SEwan Crawford   }
177215f2bd95SEwan Crawford 
177315f2bd95SEwan Crawford   bool success = false;
177480af0b9eSLuke Drummond   // We only read the result as an uint32_t.
177580af0b9eSLuke Drummond   *result = expr_result->GetValueAsUnsigned(0, &success);
177615f2bd95SEwan Crawford 
1777b9c1b51eSKate Stone   if (!success) {
177815f2bd95SEwan Crawford     if (log)
1779b9c1b51eSKate Stone       log->Printf("%s - couldn't convert expression result to uint32_t",
1780b9c1b51eSKate Stone                   __FUNCTION__);
178115f2bd95SEwan Crawford     return false;
178215f2bd95SEwan Crawford   }
178315f2bd95SEwan Crawford 
178415f2bd95SEwan Crawford   return true;
178515f2bd95SEwan Crawford }
178615f2bd95SEwan Crawford 
1787b9c1b51eSKate Stone namespace {
1788836d9651SEwan Crawford // Used to index expression format strings
1789b9c1b51eSKate Stone enum ExpressionStrings {
1790836d9651SEwan Crawford   eExprGetOffsetPtr = 0,
1791836d9651SEwan Crawford   eExprAllocGetType,
1792836d9651SEwan Crawford   eExprTypeDimX,
1793836d9651SEwan Crawford   eExprTypeDimY,
1794836d9651SEwan Crawford   eExprTypeDimZ,
1795836d9651SEwan Crawford   eExprTypeElemPtr,
1796836d9651SEwan Crawford   eExprElementType,
1797836d9651SEwan Crawford   eExprElementKind,
1798836d9651SEwan Crawford   eExprElementVec,
1799836d9651SEwan Crawford   eExprElementFieldCount,
1800836d9651SEwan Crawford   eExprSubelementsId,
1801836d9651SEwan Crawford   eExprSubelementsName,
1802ea0636b5SEwan Crawford   eExprSubelementsArrSize,
1803ea0636b5SEwan Crawford 
180480af0b9eSLuke Drummond   _eExprLast // keep at the end, implicit size of the array runtime_expressions
1805836d9651SEwan Crawford };
180615f2bd95SEwan Crawford 
1807ea0636b5SEwan Crawford // max length of an expanded expression
1808ea0636b5SEwan Crawford const int jit_max_expr_size = 512;
1809ea0636b5SEwan Crawford 
1810ea0636b5SEwan Crawford // Retrieve the string to JIT for the given expression
1811b9c1b51eSKate Stone const char *JITTemplate(ExpressionStrings e) {
1812ea0636b5SEwan Crawford   // Format strings containing the expressions we may need to evaluate.
181380af0b9eSLuke Drummond   static std::array<const char *, _eExprLast> runtime_expressions = {
1814b9c1b51eSKate Stone       {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1815b9c1b51eSKate Stone        "(int*)_"
1816b9c1b51eSKate Stone        "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1817b9c1b51eSKate Stone        "CubemapFace"
1818577570b4SAidan Dodds        "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)",
181915f2bd95SEwan Crawford 
182015f2bd95SEwan Crawford        // Type* rsaAllocationGetType(Context*, Allocation*)
1821577570b4SAidan Dodds        "(void*)rsaAllocationGetType(0x%" PRIx64 ", 0x%" PRIx64 ")",
182215f2bd95SEwan Crawford 
182380af0b9eSLuke Drummond        // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
182480af0b9eSLuke Drummond        // data in the following way mHal.state.dimX; mHal.state.dimY;
182580af0b9eSLuke Drummond        // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement; into
182680af0b9eSLuke Drummond        // typeData Need to specify 32 or 64 bit for uint_t since this differs
182780af0b9eSLuke Drummond        // between devices
1828b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1829b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[0]", // X dim
1830b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1831b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[1]", // Y dim
1832b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1833b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[2]", // Z dim
1834b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1835b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[5]", // Element ptr
183615f2bd95SEwan Crawford 
183715f2bd95SEwan Crawford        // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1838b9c1b51eSKate Stone        // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1839b9c1b51eSKate Stone        // elemData
1840b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1841b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[0]", // Type
1842b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1843b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[1]", // Kind
1844b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1845b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[3]", // Vector Size
1846b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1847b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[4]", // Field Count
18488b244e21SEwan Crawford 
1849b9c1b51eSKate Stone        // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
185080af0b9eSLuke Drummond        // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1851b9c1b51eSKate Stone        // Needed for Allocations of structs to gather details about
185280af0b9eSLuke Drummond        // fields/Subelements Element* of field
1853b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1854b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1855b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1856b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]",
18578b244e21SEwan Crawford 
1858577570b4SAidan Dodds        // Name of field
1859b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1860b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1861b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1862b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]",
18638b244e21SEwan Crawford 
1864577570b4SAidan Dodds        // Array size of field
1865b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1866b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1867b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1868b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}};
1869ea0636b5SEwan Crawford 
187080af0b9eSLuke Drummond   return runtime_expressions[e];
1871ea0636b5SEwan Crawford }
1872ea0636b5SEwan Crawford } // end of the anonymous namespace
1873ea0636b5SEwan Crawford 
187480af0b9eSLuke Drummond // JITs the RS runtime for the internal data pointer of an allocation. Is passed
187580af0b9eSLuke Drummond // x,y,z coordinates for the pointer to a specific element. Then sets the
187680af0b9eSLuke Drummond // data_ptr member in Allocation with the result. Returns true on success, false
187780af0b9eSLuke Drummond // otherwise
187880af0b9eSLuke Drummond bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1879b9c1b51eSKate Stone                                          StackFrame *frame_ptr, uint32_t x,
1880b9c1b51eSKate Stone                                          uint32_t y, uint32_t z) {
188115f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
188215f2bd95SEwan Crawford 
188380af0b9eSLuke Drummond   if (!alloc->address.isValid()) {
188415f2bd95SEwan Crawford     if (log)
1885b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
188615f2bd95SEwan Crawford     return false;
188715f2bd95SEwan Crawford   }
188815f2bd95SEwan Crawford 
188980af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
189080af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
189115f2bd95SEwan Crawford 
189280af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
189380af0b9eSLuke Drummond                          *alloc->address.get(), x, y, z);
189480af0b9eSLuke Drummond   if (written < 0) {
189515f2bd95SEwan Crawford     if (log)
1896b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
189715f2bd95SEwan Crawford     return false;
189880af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
189915f2bd95SEwan Crawford     if (log)
1900b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
190115f2bd95SEwan Crawford     return false;
190215f2bd95SEwan Crawford   }
190315f2bd95SEwan Crawford 
190415f2bd95SEwan Crawford   uint64_t result = 0;
190580af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
190615f2bd95SEwan Crawford     return false;
190715f2bd95SEwan Crawford 
190880af0b9eSLuke Drummond   addr_t data_ptr = static_cast<lldb::addr_t>(result);
190980af0b9eSLuke Drummond   alloc->data_ptr = data_ptr;
191015f2bd95SEwan Crawford 
191115f2bd95SEwan Crawford   return true;
191215f2bd95SEwan Crawford }
191315f2bd95SEwan Crawford 
191415f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
191580af0b9eSLuke Drummond // Then sets the type_ptr member in Allocation with the result. Returns true on
191680af0b9eSLuke Drummond // success, false otherwise
191780af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1918b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
191915f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
192015f2bd95SEwan Crawford 
192180af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->context.isValid()) {
192215f2bd95SEwan Crawford     if (log)
1923b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
192415f2bd95SEwan Crawford     return false;
192515f2bd95SEwan Crawford   }
192615f2bd95SEwan Crawford 
192780af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprAllocGetType);
192880af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
192915f2bd95SEwan Crawford 
193080af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
193180af0b9eSLuke Drummond                          *alloc->context.get(), *alloc->address.get());
193280af0b9eSLuke Drummond   if (written < 0) {
193315f2bd95SEwan Crawford     if (log)
1934b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
193515f2bd95SEwan Crawford     return false;
193680af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
193715f2bd95SEwan Crawford     if (log)
1938b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
193915f2bd95SEwan Crawford     return false;
194015f2bd95SEwan Crawford   }
194115f2bd95SEwan Crawford 
194215f2bd95SEwan Crawford   uint64_t result = 0;
194380af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
194415f2bd95SEwan Crawford     return false;
194515f2bd95SEwan Crawford 
194615f2bd95SEwan Crawford   addr_t type_ptr = static_cast<lldb::addr_t>(result);
194780af0b9eSLuke Drummond   alloc->type_ptr = type_ptr;
194815f2bd95SEwan Crawford 
194915f2bd95SEwan Crawford   return true;
195015f2bd95SEwan Crawford }
195115f2bd95SEwan Crawford 
1952b9c1b51eSKate Stone // JITs the RS runtime for information about the dimensions and type of an
195380af0b9eSLuke Drummond // allocation Then sets dimension and element_ptr members in Allocation with the
195480af0b9eSLuke Drummond // result. Returns true on success, false otherwise
195580af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1956b9c1b51eSKate Stone                                         StackFrame *frame_ptr) {
195715f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
195815f2bd95SEwan Crawford 
195980af0b9eSLuke Drummond   if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
196015f2bd95SEwan Crawford     if (log)
1961b3f7f69dSAidan Dodds       log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
196215f2bd95SEwan Crawford     return false;
196315f2bd95SEwan Crawford   }
196415f2bd95SEwan Crawford 
196515f2bd95SEwan Crawford   // Expression is different depending on if device is 32 or 64 bit
196680af0b9eSLuke Drummond   uint32_t target_ptr_size =
1967b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
196880af0b9eSLuke Drummond   const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
196915f2bd95SEwan Crawford 
197015f2bd95SEwan Crawford   // We want 4 elements from packed data
1971b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
1972b9c1b51eSKate Stone   assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) &&
1973b9c1b51eSKate Stone          "Invalid number of expressions");
197415f2bd95SEwan Crawford 
197580af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
197615f2bd95SEwan Crawford   uint64_t results[num_exprs];
197715f2bd95SEwan Crawford 
1978b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; ++i) {
197980af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
198080af0b9eSLuke Drummond     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, bits,
198180af0b9eSLuke Drummond                            *alloc->context.get(), *alloc->type_ptr.get());
198280af0b9eSLuke Drummond     if (written < 0) {
198315f2bd95SEwan Crawford       if (log)
1984b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
198515f2bd95SEwan Crawford       return false;
198680af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
198715f2bd95SEwan Crawford       if (log)
1988b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
198915f2bd95SEwan Crawford       return false;
199015f2bd95SEwan Crawford     }
199115f2bd95SEwan Crawford 
199215f2bd95SEwan Crawford     // Perform expression evaluation
199380af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
199415f2bd95SEwan Crawford       return false;
199515f2bd95SEwan Crawford   }
199615f2bd95SEwan Crawford 
199715f2bd95SEwan Crawford   // Assign results to allocation members
199815f2bd95SEwan Crawford   AllocationDetails::Dimension dims;
199915f2bd95SEwan Crawford   dims.dim_1 = static_cast<uint32_t>(results[0]);
200015f2bd95SEwan Crawford   dims.dim_2 = static_cast<uint32_t>(results[1]);
200115f2bd95SEwan Crawford   dims.dim_3 = static_cast<uint32_t>(results[2]);
200280af0b9eSLuke Drummond   alloc->dimension = dims;
200315f2bd95SEwan Crawford 
200480af0b9eSLuke Drummond   addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
200580af0b9eSLuke Drummond   alloc->element.element_ptr = element_ptr;
200615f2bd95SEwan Crawford 
200715f2bd95SEwan Crawford   if (log)
2008b9c1b51eSKate Stone     log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
2009b9c1b51eSKate Stone                 ") Element*: 0x%" PRIx64 ".",
201080af0b9eSLuke Drummond                 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
201115f2bd95SEwan Crawford 
201215f2bd95SEwan Crawford   return true;
201315f2bd95SEwan Crawford }
201415f2bd95SEwan Crawford 
201580af0b9eSLuke Drummond // JITs the RS runtime for information about the Element of an allocation Then
201680af0b9eSLuke Drummond // sets type, type_vec_size, field_count and type_kind members in Element with
201780af0b9eSLuke Drummond // the result. Returns true on success, false otherwise
2018b9c1b51eSKate Stone bool RenderScriptRuntime::JITElementPacked(Element &elem,
2019b9c1b51eSKate Stone                                            const lldb::addr_t context,
2020b9c1b51eSKate Stone                                            StackFrame *frame_ptr) {
202115f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
202215f2bd95SEwan Crawford 
2023b9c1b51eSKate Stone   if (!elem.element_ptr.isValid()) {
202415f2bd95SEwan Crawford     if (log)
2025b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
202615f2bd95SEwan Crawford     return false;
202715f2bd95SEwan Crawford   }
202815f2bd95SEwan Crawford 
20298b244e21SEwan Crawford   // We want 4 elements from packed data
2030b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
2031b9c1b51eSKate Stone   assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) &&
2032b9c1b51eSKate Stone          "Invalid number of expressions");
203315f2bd95SEwan Crawford 
203480af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
203515f2bd95SEwan Crawford   uint64_t results[num_exprs];
203615f2bd95SEwan Crawford 
2037b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; i++) {
203880af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
203980af0b9eSLuke Drummond     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
204080af0b9eSLuke Drummond                            *elem.element_ptr.get());
204180af0b9eSLuke Drummond     if (written < 0) {
204215f2bd95SEwan Crawford       if (log)
2043b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
204415f2bd95SEwan Crawford       return false;
204580af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
204615f2bd95SEwan Crawford       if (log)
2047b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
204815f2bd95SEwan Crawford       return false;
204915f2bd95SEwan Crawford     }
205015f2bd95SEwan Crawford 
205115f2bd95SEwan Crawford     // Perform expression evaluation
205280af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
205315f2bd95SEwan Crawford       return false;
205415f2bd95SEwan Crawford   }
205515f2bd95SEwan Crawford 
205615f2bd95SEwan Crawford   // Assign results to allocation members
20578b244e21SEwan Crawford   elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
2058b9c1b51eSKate Stone   elem.type_kind =
2059b9c1b51eSKate Stone       static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
20608b244e21SEwan Crawford   elem.type_vec_size = static_cast<uint32_t>(results[2]);
20618b244e21SEwan Crawford   elem.field_count = static_cast<uint32_t>(results[3]);
206215f2bd95SEwan Crawford 
206315f2bd95SEwan Crawford   if (log)
2064b9c1b51eSKate Stone     log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32
2065b9c1b51eSKate Stone                 ", vector size %" PRIu32 ", field count %" PRIu32,
2066b9c1b51eSKate Stone                 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
2067b9c1b51eSKate Stone                 *elem.type_vec_size.get(), *elem.field_count.get());
20688b244e21SEwan Crawford 
2069b9c1b51eSKate Stone   // If this Element has subelements then JIT rsaElementGetSubElements() for
2070b9c1b51eSKate Stone   // details about its fields
20718b244e21SEwan Crawford   if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
20728b244e21SEwan Crawford     return false;
20738b244e21SEwan Crawford 
20748b244e21SEwan Crawford   return true;
20758b244e21SEwan Crawford }
20768b244e21SEwan Crawford 
2077b9c1b51eSKate Stone // JITs the RS runtime for information about the subelements/fields of a struct
207880af0b9eSLuke Drummond // allocation This is necessary for infering the struct type so we can pretty
207980af0b9eSLuke Drummond // print the allocation's contents. Returns true on success, false otherwise
2080b9c1b51eSKate Stone bool RenderScriptRuntime::JITSubelements(Element &elem,
2081b9c1b51eSKate Stone                                          const lldb::addr_t context,
2082b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
20838b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
20848b244e21SEwan Crawford 
2085b9c1b51eSKate Stone   if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
20868b244e21SEwan Crawford     if (log)
2087b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
20888b244e21SEwan Crawford     return false;
20898b244e21SEwan Crawford   }
20908b244e21SEwan Crawford 
20918b244e21SEwan Crawford   const short num_exprs = 3;
2092b9c1b51eSKate Stone   assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) &&
2093b9c1b51eSKate Stone          "Invalid number of expressions");
20948b244e21SEwan Crawford 
2095ea0636b5SEwan Crawford   char expr_buffer[jit_max_expr_size];
20968b244e21SEwan Crawford   uint64_t results;
20978b244e21SEwan Crawford 
20988b244e21SEwan Crawford   // Iterate over struct fields.
20998b244e21SEwan Crawford   const uint32_t field_count = *elem.field_count.get();
2100b9c1b51eSKate Stone   for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
21018b244e21SEwan Crawford     Element child;
2102b9c1b51eSKate Stone     for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
210380af0b9eSLuke Drummond       const char *fmt_str =
2104b9c1b51eSKate Stone           JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
210580af0b9eSLuke Drummond       int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
210680af0b9eSLuke Drummond                              field_count, field_count, field_count, context,
210780af0b9eSLuke Drummond                              *elem.element_ptr.get(), field_count, field_index);
210880af0b9eSLuke Drummond       if (written < 0) {
21098b244e21SEwan Crawford         if (log)
2110b3f7f69dSAidan Dodds           log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
21118b244e21SEwan Crawford         return false;
211280af0b9eSLuke Drummond       } else if (written >= jit_max_expr_size) {
21138b244e21SEwan Crawford         if (log)
2114b3f7f69dSAidan Dodds           log->Printf("%s - expression too long.", __FUNCTION__);
21158b244e21SEwan Crawford         return false;
21168b244e21SEwan Crawford       }
21178b244e21SEwan Crawford 
21188b244e21SEwan Crawford       // Perform expression evaluation
21198b244e21SEwan Crawford       if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
21208b244e21SEwan Crawford         return false;
21218b244e21SEwan Crawford 
21228b244e21SEwan Crawford       if (log)
2123b3f7f69dSAidan Dodds         log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
21248b244e21SEwan Crawford 
2125b9c1b51eSKate Stone       switch (expr_index) {
21268b244e21SEwan Crawford       case 0: // Element* of child
21278b244e21SEwan Crawford         child.element_ptr = static_cast<addr_t>(results);
21288b244e21SEwan Crawford         break;
21298b244e21SEwan Crawford       case 1: // Name of child
21308b244e21SEwan Crawford       {
21318b244e21SEwan Crawford         lldb::addr_t address = static_cast<addr_t>(results);
21328b244e21SEwan Crawford         Error err;
21338b244e21SEwan Crawford         std::string name;
21348b244e21SEwan Crawford         GetProcess()->ReadCStringFromMemory(address, name, err);
21358b244e21SEwan Crawford         if (!err.Fail())
21368b244e21SEwan Crawford           child.type_name = ConstString(name);
2137b9c1b51eSKate Stone         else {
21388b244e21SEwan Crawford           if (log)
2139b9c1b51eSKate Stone             log->Printf("%s - warning: Couldn't read field name.",
2140b9c1b51eSKate Stone                         __FUNCTION__);
21418b244e21SEwan Crawford         }
21428b244e21SEwan Crawford         break;
21438b244e21SEwan Crawford       }
21448b244e21SEwan Crawford       case 2: // Array size of child
21458b244e21SEwan Crawford         child.array_size = static_cast<uint32_t>(results);
21468b244e21SEwan Crawford         break;
21478b244e21SEwan Crawford       }
21488b244e21SEwan Crawford     }
21498b244e21SEwan Crawford 
21508b244e21SEwan Crawford     // We need to recursively JIT each Element field of the struct since
21518b244e21SEwan Crawford     // structs can be nested inside structs.
21528b244e21SEwan Crawford     if (!JITElementPacked(child, context, frame_ptr))
21538b244e21SEwan Crawford       return false;
21548b244e21SEwan Crawford     elem.children.push_back(child);
21558b244e21SEwan Crawford   }
21568b244e21SEwan Crawford 
2157b9c1b51eSKate Stone   // Try to infer the name of the struct type so we can pretty print the
2158b9c1b51eSKate Stone   // allocation contents.
21598b244e21SEwan Crawford   FindStructTypeName(elem, frame_ptr);
216015f2bd95SEwan Crawford 
216115f2bd95SEwan Crawford   return true;
216215f2bd95SEwan Crawford }
216315f2bd95SEwan Crawford 
2164a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
2165b9c1b51eSKate Stone // The `elem_size` parameter represents the size of a single element, including
216680af0b9eSLuke Drummond // padding. Which is needed as an offset from the last element pointer. Using
216780af0b9eSLuke Drummond // this offset minus the starting address we can calculate the size of the
216880af0b9eSLuke Drummond // allocation. Returns true on success, false otherwise
216980af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
2170b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
2171a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2172a0f08674SEwan Crawford 
217380af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
217480af0b9eSLuke Drummond       !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
2175a0f08674SEwan Crawford     if (log)
2176b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2177a0f08674SEwan Crawford     return false;
2178a0f08674SEwan Crawford   }
2179a0f08674SEwan Crawford 
2180a0f08674SEwan Crawford   // Find dimensions
218180af0b9eSLuke Drummond   uint32_t dim_x = alloc->dimension.get()->dim_1;
218280af0b9eSLuke Drummond   uint32_t dim_y = alloc->dimension.get()->dim_2;
218380af0b9eSLuke Drummond   uint32_t dim_z = alloc->dimension.get()->dim_3;
2184a0f08674SEwan Crawford 
2185b9c1b51eSKate Stone   // Our plan of jitting the last element address doesn't seem to work for
218680af0b9eSLuke Drummond   // struct Allocations` Instead try to infer the size ourselves without any
218780af0b9eSLuke Drummond   // inter element padding.
218880af0b9eSLuke Drummond   if (alloc->element.children.size() > 0) {
2189b9c1b51eSKate Stone     if (dim_x == 0)
2190b9c1b51eSKate Stone       dim_x = 1;
2191b9c1b51eSKate Stone     if (dim_y == 0)
2192b9c1b51eSKate Stone       dim_y = 1;
2193b9c1b51eSKate Stone     if (dim_z == 0)
2194b9c1b51eSKate Stone       dim_z = 1;
21958b244e21SEwan Crawford 
219680af0b9eSLuke Drummond     alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
21978b244e21SEwan Crawford 
21988b244e21SEwan Crawford     if (log)
2199b9c1b51eSKate Stone       log->Printf("%s - inferred size of struct allocation %" PRIu32 ".",
220080af0b9eSLuke Drummond                   __FUNCTION__, *alloc->size.get());
22018b244e21SEwan Crawford     return true;
22028b244e21SEwan Crawford   }
22038b244e21SEwan Crawford 
220480af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
220580af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
22068b244e21SEwan Crawford 
2207a0f08674SEwan Crawford   // Calculate last element
2208a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 0 : dim_x - 1;
2209a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 0 : dim_y - 1;
2210a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 0 : dim_z - 1;
2211a0f08674SEwan Crawford 
221280af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
221380af0b9eSLuke Drummond                          *alloc->address.get(), dim_x, dim_y, dim_z);
221480af0b9eSLuke Drummond   if (written < 0) {
2215a0f08674SEwan Crawford     if (log)
2216b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2217a0f08674SEwan Crawford     return false;
221880af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
2219a0f08674SEwan Crawford     if (log)
2220b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
2221a0f08674SEwan Crawford     return false;
2222a0f08674SEwan Crawford   }
2223a0f08674SEwan Crawford 
2224a0f08674SEwan Crawford   uint64_t result = 0;
222580af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2226a0f08674SEwan Crawford     return false;
2227a0f08674SEwan Crawford 
2228a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2229a0f08674SEwan Crawford   // Find pointer to last element and add on size of an element
223080af0b9eSLuke Drummond   alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
223180af0b9eSLuke Drummond                 *alloc->element.datum_size.get();
2232a0f08674SEwan Crawford 
2233a0f08674SEwan Crawford   return true;
2234a0f08674SEwan Crawford }
2235a0f08674SEwan Crawford 
2236b9c1b51eSKate Stone // JITs the RS runtime for information about the stride between rows in the
223780af0b9eSLuke Drummond // allocation. This is done to detect padding, since allocated memory is 16-byte
223880af0b9eSLuke Drummond // aligned.
2239a0f08674SEwan Crawford // Returns true on success, false otherwise
224080af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
2241b9c1b51eSKate Stone                                               StackFrame *frame_ptr) {
2242a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2243a0f08674SEwan Crawford 
224480af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
2245a0f08674SEwan Crawford     if (log)
2246b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2247a0f08674SEwan Crawford     return false;
2248a0f08674SEwan Crawford   }
2249a0f08674SEwan Crawford 
225080af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
225180af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
2252a0f08674SEwan Crawford 
225380af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
225480af0b9eSLuke Drummond                          *alloc->address.get(), 0, 1, 0);
225580af0b9eSLuke Drummond   if (written < 0) {
2256a0f08674SEwan Crawford     if (log)
2257b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2258a0f08674SEwan Crawford     return false;
225980af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
2260a0f08674SEwan Crawford     if (log)
2261b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
2262a0f08674SEwan Crawford     return false;
2263a0f08674SEwan Crawford   }
2264a0f08674SEwan Crawford 
2265a0f08674SEwan Crawford   uint64_t result = 0;
226680af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2267a0f08674SEwan Crawford     return false;
2268a0f08674SEwan Crawford 
2269a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
227080af0b9eSLuke Drummond   alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
2271a0f08674SEwan Crawford 
2272a0f08674SEwan Crawford   return true;
2273a0f08674SEwan Crawford }
2274a0f08674SEwan Crawford 
227515f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
227680af0b9eSLuke Drummond bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2277b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
227815f2bd95SEwan Crawford   // GetOffsetPointer()
227980af0b9eSLuke Drummond   if (!JITDataPointer(alloc, frame_ptr))
228015f2bd95SEwan Crawford     return false;
228115f2bd95SEwan Crawford 
228215f2bd95SEwan Crawford   // rsaAllocationGetType()
228380af0b9eSLuke Drummond   if (!JITTypePointer(alloc, frame_ptr))
228415f2bd95SEwan Crawford     return false;
228515f2bd95SEwan Crawford 
228615f2bd95SEwan Crawford   // rsaTypeGetNativeData()
228780af0b9eSLuke Drummond   if (!JITTypePacked(alloc, frame_ptr))
228815f2bd95SEwan Crawford     return false;
228915f2bd95SEwan Crawford 
229015f2bd95SEwan Crawford   // rsaElementGetNativeData()
229180af0b9eSLuke Drummond   if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
229215f2bd95SEwan Crawford     return false;
229315f2bd95SEwan Crawford 
22948b244e21SEwan Crawford   // Sets the datum_size member in Element
229580af0b9eSLuke Drummond   SetElementSize(alloc->element);
22968b244e21SEwan Crawford 
229755232f09SEwan Crawford   // Use GetOffsetPointer() to infer size of the allocation
229880af0b9eSLuke Drummond   if (!JITAllocationSize(alloc, frame_ptr))
229955232f09SEwan Crawford     return false;
230055232f09SEwan Crawford 
230155232f09SEwan Crawford   return true;
230255232f09SEwan Crawford }
230355232f09SEwan Crawford 
2304b9c1b51eSKate Stone // Function attempts to set the type_name member of the paramaterised Element
2305b9c1b51eSKate Stone // object.
23068b244e21SEwan Crawford // This string should be the name of the struct type the Element represents.
23078b244e21SEwan Crawford // We need this string for pretty printing the Element to users.
2308b9c1b51eSKate Stone void RenderScriptRuntime::FindStructTypeName(Element &elem,
2309b9c1b51eSKate Stone                                              StackFrame *frame_ptr) {
23108b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
23118b244e21SEwan Crawford 
23128b244e21SEwan Crawford   if (!elem.type_name.IsEmpty()) // Name already set
23138b244e21SEwan Crawford     return;
23148b244e21SEwan Crawford   else
2315b9c1b51eSKate Stone     elem.type_name = Element::GetFallbackStructName(); // Default type name if
2316b9c1b51eSKate Stone                                                        // we don't succeed
23178b244e21SEwan Crawford 
23188b244e21SEwan Crawford   // Find all the global variables from the script rs modules
231980af0b9eSLuke Drummond   VariableList var_list;
23208b244e21SEwan Crawford   for (auto module_sp : m_rsmodules)
232195eae423SZachary Turner     module_sp->m_module->FindGlobalVariables(
232280af0b9eSLuke Drummond         RegularExpression(llvm::StringRef(".")), true, UINT32_MAX, var_list);
23238b244e21SEwan Crawford 
2324b9c1b51eSKate Stone   // Iterate over all the global variables looking for one with a matching type
2325b9c1b51eSKate Stone   // to the Element.
2326b9c1b51eSKate Stone   // We make the assumption a match exists since there needs to be a global
232780af0b9eSLuke Drummond   // variable to reflect the struct type back into java host code.
232880af0b9eSLuke Drummond   for (uint32_t i = 0; i < var_list.GetSize(); ++i) {
232980af0b9eSLuke Drummond     const VariableSP var_sp(var_list.GetVariableAtIndex(i));
23308b244e21SEwan Crawford     if (!var_sp)
23318b244e21SEwan Crawford       continue;
23328b244e21SEwan Crawford 
23338b244e21SEwan Crawford     ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
23348b244e21SEwan Crawford     if (!valobj_sp)
23358b244e21SEwan Crawford       continue;
23368b244e21SEwan Crawford 
23378b244e21SEwan Crawford     // Find the number of variable fields.
2338b9c1b51eSKate Stone     // If it has no fields, or more fields than our Element, then it can't be
2339b9c1b51eSKate Stone     // the struct we're looking for.
2340b9c1b51eSKate Stone     // Don't check for equality since RS can add extra struct members for
2341b9c1b51eSKate Stone     // padding.
23428b244e21SEwan Crawford     size_t num_children = valobj_sp->GetNumChildren();
23438b244e21SEwan Crawford     if (num_children > elem.children.size() || num_children == 0)
23448b244e21SEwan Crawford       continue;
23458b244e21SEwan Crawford 
23468b244e21SEwan Crawford     // Iterate over children looking for members with matching field names.
23478b244e21SEwan Crawford     // If all the field names match, this is likely the struct we want.
2348b9c1b51eSKate Stone     //   TODO: This could be made more robust by also checking children data
2349b9c1b51eSKate Stone     //   sizes, or array size
23508b244e21SEwan Crawford     bool found = true;
235180af0b9eSLuke Drummond     for (size_t i = 0; i < num_children; ++i) {
235280af0b9eSLuke Drummond       ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
235380af0b9eSLuke Drummond       if (!child || (child->GetName() != elem.children[i].type_name)) {
23548b244e21SEwan Crawford         found = false;
23558b244e21SEwan Crawford         break;
23568b244e21SEwan Crawford       }
23578b244e21SEwan Crawford     }
23588b244e21SEwan Crawford 
2359b9c1b51eSKate Stone     // RS can add extra struct members for padding in the format
2360b9c1b51eSKate Stone     // '#rs_padding_[0-9]+'
2361b9c1b51eSKate Stone     if (found && num_children < elem.children.size()) {
2362b3f7f69dSAidan Dodds       const uint32_t size_diff = elem.children.size() - num_children;
23638b244e21SEwan Crawford       if (log)
2364b9c1b51eSKate Stone         log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2365b9c1b51eSKate Stone                     size_diff);
23668b244e21SEwan Crawford 
236780af0b9eSLuke Drummond       for (uint32_t i = 0; i < size_diff; ++i) {
236880af0b9eSLuke Drummond         const ConstString &name = elem.children[num_children + i].type_name;
23698b244e21SEwan Crawford         if (strcmp(name.AsCString(), "#rs_padding") < 0)
23708b244e21SEwan Crawford           found = false;
23718b244e21SEwan Crawford       }
23728b244e21SEwan Crawford     }
23738b244e21SEwan Crawford 
237480af0b9eSLuke Drummond     // We've found a global variable with matching type
2375b9c1b51eSKate Stone     if (found) {
23768b244e21SEwan Crawford       // Dereference since our Element type isn't a pointer.
2377b9c1b51eSKate Stone       if (valobj_sp->IsPointerType()) {
23788b244e21SEwan Crawford         Error err;
23798b244e21SEwan Crawford         ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
23808b244e21SEwan Crawford         if (!err.Fail())
23818b244e21SEwan Crawford           valobj_sp = deref_valobj;
23828b244e21SEwan Crawford       }
23838b244e21SEwan Crawford 
23848b244e21SEwan Crawford       // Save name of variable in Element.
23858b244e21SEwan Crawford       elem.type_name = valobj_sp->GetTypeName();
23868b244e21SEwan Crawford       if (log)
2387b9c1b51eSKate Stone         log->Printf("%s - element name set to %s", __FUNCTION__,
2388b9c1b51eSKate Stone                     elem.type_name.AsCString());
23898b244e21SEwan Crawford 
23908b244e21SEwan Crawford       return;
23918b244e21SEwan Crawford     }
23928b244e21SEwan Crawford   }
23938b244e21SEwan Crawford }
23948b244e21SEwan Crawford 
2395b9c1b51eSKate Stone // Function sets the datum_size member of Element. Representing the size of a
2396b9c1b51eSKate Stone // single instance including padding.
23978b244e21SEwan Crawford // Assumes the relevant allocation information has already been jitted.
2398b9c1b51eSKate Stone void RenderScriptRuntime::SetElementSize(Element &elem) {
23998b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
24008b244e21SEwan Crawford   const Element::DataType type = *elem.type.get();
2401b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2402b9c1b51eSKate Stone          "Invalid allocation type");
240355232f09SEwan Crawford 
2404b3f7f69dSAidan Dodds   const uint32_t vec_size = *elem.type_vec_size.get();
2405b3f7f69dSAidan Dodds   uint32_t data_size = 0;
2406b3f7f69dSAidan Dodds   uint32_t padding = 0;
240755232f09SEwan Crawford 
24088b244e21SEwan Crawford   // Element is of a struct type, calculate size recursively.
2409b9c1b51eSKate Stone   if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2410b9c1b51eSKate Stone     for (Element &child : elem.children) {
24118b244e21SEwan Crawford       SetElementSize(child);
2412b9c1b51eSKate Stone       const uint32_t array_size =
2413b9c1b51eSKate Stone           child.array_size.isValid() ? *child.array_size.get() : 1;
24148b244e21SEwan Crawford       data_size += *child.datum_size.get() * array_size;
24158b244e21SEwan Crawford     }
24168b244e21SEwan Crawford   }
2417b3f7f69dSAidan Dodds   // These have been packed already
2418b3f7f69dSAidan Dodds   else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2419b3f7f69dSAidan Dodds            type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2420b9c1b51eSKate Stone            type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
24212e920715SEwan Crawford     data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2422b9c1b51eSKate Stone   } else if (type < Element::RS_TYPE_ELEMENT) {
2423b9c1b51eSKate Stone     data_size =
2424b9c1b51eSKate Stone         vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
24252e920715SEwan Crawford     if (vec_size == 3)
24262e920715SEwan Crawford       padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2427b9c1b51eSKate Stone   } else
2428b9c1b51eSKate Stone     data_size =
2429b9c1b51eSKate Stone         GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
24308b244e21SEwan Crawford 
24318b244e21SEwan Crawford   elem.padding = padding;
24328b244e21SEwan Crawford   elem.datum_size = data_size + padding;
24338b244e21SEwan Crawford   if (log)
2434b9c1b51eSKate Stone     log->Printf("%s - element size set to %" PRIu32, __FUNCTION__,
2435b9c1b51eSKate Stone                 data_size + padding);
243655232f09SEwan Crawford }
243755232f09SEwan Crawford 
2438b9c1b51eSKate Stone // Given an allocation, this function copies the allocation contents from device
2439b9c1b51eSKate Stone // into a buffer on the heap.
244055232f09SEwan Crawford // Returning a shared pointer to the buffer containing the data.
244155232f09SEwan Crawford std::shared_ptr<uint8_t>
244280af0b9eSLuke Drummond RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2443b9c1b51eSKate Stone                                        StackFrame *frame_ptr) {
244455232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
244555232f09SEwan Crawford 
244655232f09SEwan Crawford   // JIT all the allocation details
244780af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
244855232f09SEwan Crawford     if (log)
2449b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info",
2450b9c1b51eSKate Stone                   __FUNCTION__);
245155232f09SEwan Crawford 
245280af0b9eSLuke Drummond     if (!RefreshAllocation(alloc, frame_ptr)) {
245355232f09SEwan Crawford       if (log)
2454b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
245555232f09SEwan Crawford       return nullptr;
245655232f09SEwan Crawford     }
245755232f09SEwan Crawford   }
245855232f09SEwan Crawford 
245980af0b9eSLuke Drummond   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
246080af0b9eSLuke Drummond          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
246180af0b9eSLuke Drummond          "Allocation information not available");
246255232f09SEwan Crawford 
246355232f09SEwan Crawford   // Allocate a buffer to copy data into
246480af0b9eSLuke Drummond   const uint32_t size = *alloc->size.get();
246555232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2466b9c1b51eSKate Stone   if (!buffer) {
246755232f09SEwan Crawford     if (log)
2468b9c1b51eSKate Stone       log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer",
2469b9c1b51eSKate Stone                   __FUNCTION__, size);
247055232f09SEwan Crawford     return nullptr;
247155232f09SEwan Crawford   }
247255232f09SEwan Crawford 
247355232f09SEwan Crawford   // Read the inferior memory
247480af0b9eSLuke Drummond   Error err;
247580af0b9eSLuke Drummond   lldb::addr_t data_ptr = *alloc->data_ptr.get();
247680af0b9eSLuke Drummond   GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
247780af0b9eSLuke Drummond   if (err.Fail()) {
247855232f09SEwan Crawford     if (log)
2479b9c1b51eSKate Stone       log->Printf("%s - '%s' Couldn't read %" PRIu32
2480b9c1b51eSKate Stone                   " bytes of allocation data from 0x%" PRIx64,
248180af0b9eSLuke Drummond                   __FUNCTION__, err.AsCString(), size, data_ptr);
248255232f09SEwan Crawford     return nullptr;
248355232f09SEwan Crawford   }
248455232f09SEwan Crawford 
248555232f09SEwan Crawford   return buffer;
248655232f09SEwan Crawford }
248755232f09SEwan Crawford 
248855232f09SEwan Crawford // Function copies data from a binary file into an allocation.
2489b9c1b51eSKate Stone // There is a header at the start of the file, FileHeader, before the data
2490b9c1b51eSKate Stone // content itself.
2491b9c1b51eSKate Stone // Information from this header is used to display warnings to the user about
2492b9c1b51eSKate Stone // incompatibilities
2493b9c1b51eSKate Stone bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
249480af0b9eSLuke Drummond                                          const char *path,
2495b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
249655232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
249755232f09SEwan Crawford 
249855232f09SEwan Crawford   // Find allocation with the given id
249955232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
250055232f09SEwan Crawford   if (!alloc)
250155232f09SEwan Crawford     return false;
250255232f09SEwan Crawford 
250355232f09SEwan Crawford   if (log)
2504b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2505b9c1b51eSKate Stone                 *alloc->address.get());
250655232f09SEwan Crawford 
250755232f09SEwan Crawford   // JIT all the allocation details
250880af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
250955232f09SEwan Crawford     if (log)
2510b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2511b9c1b51eSKate Stone                   __FUNCTION__);
251255232f09SEwan Crawford 
2513b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
251455232f09SEwan Crawford       if (log)
2515b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
25164cfc9198SSylvestre Ledru       return false;
251755232f09SEwan Crawford     }
251855232f09SEwan Crawford   }
251955232f09SEwan Crawford 
2520b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2521b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2522b9c1b51eSKate Stone          alloc->element.datum_size.isValid() &&
2523b9c1b51eSKate Stone          "Allocation information not available");
252455232f09SEwan Crawford 
252555232f09SEwan Crawford   // Check we can read from file
252680af0b9eSLuke Drummond   FileSpec file(path, true);
2527b9c1b51eSKate Stone   if (!file.Exists()) {
252880af0b9eSLuke Drummond     strm.Printf("Error: File %s does not exist", path);
252955232f09SEwan Crawford     strm.EOL();
253055232f09SEwan Crawford     return false;
253155232f09SEwan Crawford   }
253255232f09SEwan Crawford 
2533b9c1b51eSKate Stone   if (!file.Readable()) {
253480af0b9eSLuke Drummond     strm.Printf("Error: File %s does not have readable permissions", path);
253555232f09SEwan Crawford     strm.EOL();
253655232f09SEwan Crawford     return false;
253755232f09SEwan Crawford   }
253855232f09SEwan Crawford 
253955232f09SEwan Crawford   // Read file into data buffer
2540*7f6a7a37SZachary Turner   auto data_sp = DataBufferLLVM::CreateFromPath(file.GetPath());
254155232f09SEwan Crawford 
254255232f09SEwan Crawford   // Cast start of buffer to FileHeader and use pointer to read metadata
254380af0b9eSLuke Drummond   void *file_buf = data_sp->GetBytes();
254480af0b9eSLuke Drummond   if (file_buf == nullptr ||
2545b9c1b51eSKate Stone       data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2546b9c1b51eSKate Stone                                 sizeof(AllocationDetails::ElementHeader))) {
254780af0b9eSLuke Drummond     strm.Printf("Error: File %s does not contain enough data for header", path);
254826e52a70SEwan Crawford     strm.EOL();
254926e52a70SEwan Crawford     return false;
255026e52a70SEwan Crawford   }
2551b9c1b51eSKate Stone   const AllocationDetails::FileHeader *file_header =
255280af0b9eSLuke Drummond       static_cast<AllocationDetails::FileHeader *>(file_buf);
255355232f09SEwan Crawford 
255426e52a70SEwan Crawford   // Check file starts with ascii characters "RSAD"
2555b9c1b51eSKate Stone   if (memcmp(file_header->ident, "RSAD", 4)) {
2556b9c1b51eSKate Stone     strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2557b9c1b51eSKate Stone                 "dump. Are you sure this is the correct file?");
255826e52a70SEwan Crawford     strm.EOL();
255926e52a70SEwan Crawford     return false;
256026e52a70SEwan Crawford   }
256126e52a70SEwan Crawford 
256226e52a70SEwan Crawford   // Look at the type of the root element in the header
256380af0b9eSLuke Drummond   AllocationDetails::ElementHeader root_el_hdr;
256480af0b9eSLuke Drummond   memcpy(&root_el_hdr, static_cast<uint8_t *>(file_buf) +
2565b9c1b51eSKate Stone                            sizeof(AllocationDetails::FileHeader),
256626e52a70SEwan Crawford          sizeof(AllocationDetails::ElementHeader));
256755232f09SEwan Crawford 
256855232f09SEwan Crawford   if (log)
2569b9c1b51eSKate Stone     log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32,
257080af0b9eSLuke Drummond                 __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
257155232f09SEwan Crawford 
2572b9c1b51eSKate Stone   // Check if the target allocation and file both have the same number of bytes
2573b9c1b51eSKate Stone   // for an Element
257480af0b9eSLuke Drummond   if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2575b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2576b9c1b51eSKate Stone                 " bytes, allocation %" PRIu32 " bytes",
257780af0b9eSLuke Drummond                 root_el_hdr.element_size, *alloc->element.datum_size.get());
257855232f09SEwan Crawford     strm.EOL();
257955232f09SEwan Crawford   }
258055232f09SEwan Crawford 
258126e52a70SEwan Crawford   // Check if the target allocation and file both have the same type
2582b3f7f69dSAidan Dodds   const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
258380af0b9eSLuke Drummond   const uint32_t file_type = root_el_hdr.type;
258426e52a70SEwan Crawford 
2585b9c1b51eSKate Stone   if (file_type > Element::RS_TYPE_FONT) {
258626e52a70SEwan Crawford     strm.Printf("Warning: File has unknown allocation type");
258726e52a70SEwan Crawford     strm.EOL();
2588b9c1b51eSKate Stone   } else if (alloc_type != file_type) {
2589b9c1b51eSKate Stone     // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2590b9c1b51eSKate Stone     // array
259180af0b9eSLuke Drummond     uint32_t target_type_name_idx = alloc_type;
259280af0b9eSLuke Drummond     uint32_t head_type_name_idx = file_type;
2593b9c1b51eSKate Stone     if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2594b9c1b51eSKate Stone         alloc_type <= Element::RS_TYPE_FONT)
259580af0b9eSLuke Drummond       target_type_name_idx = static_cast<Element::DataType>(
2596b9c1b51eSKate Stone           (alloc_type - Element::RS_TYPE_ELEMENT) +
2597b3f7f69dSAidan Dodds           Element::RS_TYPE_MATRIX_2X2 + 1);
25982e920715SEwan Crawford 
2599b9c1b51eSKate Stone     if (file_type >= Element::RS_TYPE_ELEMENT &&
2600b9c1b51eSKate Stone         file_type <= Element::RS_TYPE_FONT)
260180af0b9eSLuke Drummond       head_type_name_idx = static_cast<Element::DataType>(
2602b9c1b51eSKate Stone           (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2603b9c1b51eSKate Stone           1);
26042e920715SEwan Crawford 
260580af0b9eSLuke Drummond     const char *head_type_name =
260680af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
260780af0b9eSLuke Drummond     const char *target_type_name =
260880af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
260955232f09SEwan Crawford 
2610b9c1b51eSKate Stone     strm.Printf(
2611b9c1b51eSKate Stone         "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
261280af0b9eSLuke Drummond         head_type_name, target_type_name);
261355232f09SEwan Crawford     strm.EOL();
261455232f09SEwan Crawford   }
261555232f09SEwan Crawford 
261626e52a70SEwan Crawford   // Advance buffer past header
261780af0b9eSLuke Drummond   file_buf = static_cast<uint8_t *>(file_buf) + file_header->hdr_size;
261826e52a70SEwan Crawford 
261955232f09SEwan Crawford   // Calculate size of allocation data in file
262080af0b9eSLuke Drummond   size_t size = data_sp->GetByteSize() - file_header->hdr_size;
262155232f09SEwan Crawford 
262255232f09SEwan Crawford   // Check if the target allocation and file both have the same total data size.
2623b3f7f69dSAidan Dodds   const uint32_t alloc_size = *alloc->size.get();
262480af0b9eSLuke Drummond   if (alloc_size != size) {
2625b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2626b9c1b51eSKate Stone                 " bytes, allocation 0x%" PRIx32 " bytes",
262780af0b9eSLuke Drummond                 (uint64_t)size, alloc_size);
262855232f09SEwan Crawford     strm.EOL();
262980af0b9eSLuke Drummond     // Set length to copy to minimum
263080af0b9eSLuke Drummond     size = alloc_size < size ? alloc_size : size;
263155232f09SEwan Crawford   }
263255232f09SEwan Crawford 
263355232f09SEwan Crawford   // Copy file data from our buffer into the target allocation.
263455232f09SEwan Crawford   lldb::addr_t alloc_data = *alloc->data_ptr.get();
263580af0b9eSLuke Drummond   Error err;
263680af0b9eSLuke Drummond   size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
263780af0b9eSLuke Drummond   if (!err.Success() || written != size) {
263880af0b9eSLuke Drummond     strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
263955232f09SEwan Crawford     strm.EOL();
264055232f09SEwan Crawford     return false;
264155232f09SEwan Crawford   }
264255232f09SEwan Crawford 
264380af0b9eSLuke Drummond   strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2644b9c1b51eSKate Stone               alloc->id);
264555232f09SEwan Crawford   strm.EOL();
264655232f09SEwan Crawford 
264755232f09SEwan Crawford   return true;
264855232f09SEwan Crawford }
264955232f09SEwan Crawford 
2650b9c1b51eSKate Stone // Function takes as parameters a byte buffer, which will eventually be written
265180af0b9eSLuke Drummond // to file as the element header, an offset into that buffer, and an Element
265280af0b9eSLuke Drummond // that will be saved into the buffer at the parametrised offset.
265326e52a70SEwan Crawford // Return value is the new offset after writing the element into the buffer.
2654b9c1b51eSKate Stone // Elements are saved to the file as the ElementHeader struct followed by
265580af0b9eSLuke Drummond // offsets to the structs of all the element's children.
2656b9c1b51eSKate Stone size_t RenderScriptRuntime::PopulateElementHeaders(
2657b9c1b51eSKate Stone     const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2658b9c1b51eSKate Stone     const Element &elem) {
2659b9c1b51eSKate Stone   // File struct for an element header with all the relevant details copied from
266080af0b9eSLuke Drummond   // elem. We assume members are valid already.
266126e52a70SEwan Crawford   AllocationDetails::ElementHeader elem_header;
266226e52a70SEwan Crawford   elem_header.type = *elem.type.get();
266326e52a70SEwan Crawford   elem_header.kind = *elem.type_kind.get();
266426e52a70SEwan Crawford   elem_header.element_size = *elem.datum_size.get();
266526e52a70SEwan Crawford   elem_header.vector_size = *elem.type_vec_size.get();
2666b9c1b51eSKate Stone   elem_header.array_size =
2667b9c1b51eSKate Stone       elem.array_size.isValid() ? *elem.array_size.get() : 0;
266826e52a70SEwan Crawford   const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
266926e52a70SEwan Crawford 
267026e52a70SEwan Crawford   // Copy struct into buffer and advance offset
2671b9c1b51eSKate Stone   // We assume that header_buffer has been checked for nullptr before this
2672b9c1b51eSKate Stone   // method is called
267326e52a70SEwan Crawford   memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
267426e52a70SEwan Crawford   offset += elem_header_size;
267526e52a70SEwan Crawford 
267626e52a70SEwan Crawford   // Starting offset of child ElementHeader struct
2677b9c1b51eSKate Stone   size_t child_offset =
2678b9c1b51eSKate Stone       offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2679b9c1b51eSKate Stone   for (const RenderScriptRuntime::Element &child : elem.children) {
2680b9c1b51eSKate Stone     // Recursively populate the buffer with the element header structs of
268180af0b9eSLuke Drummond     // children. Then save the offsets where they were set after the parent
268280af0b9eSLuke Drummond     // element header.
268326e52a70SEwan Crawford     memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
268426e52a70SEwan Crawford     offset += sizeof(uint32_t);
268526e52a70SEwan Crawford 
268626e52a70SEwan Crawford     child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
268726e52a70SEwan Crawford   }
268826e52a70SEwan Crawford 
268926e52a70SEwan Crawford   // Zero indicates no more children
269026e52a70SEwan Crawford   memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
269126e52a70SEwan Crawford 
269226e52a70SEwan Crawford   return child_offset;
269326e52a70SEwan Crawford }
269426e52a70SEwan Crawford 
2695b9c1b51eSKate Stone // Given an Element object this function returns the total size needed in the
269680af0b9eSLuke Drummond // file header to store the element's details. Taking into account the size of
269780af0b9eSLuke Drummond // the element header struct, plus the offsets to all the element's children.
2698b9c1b51eSKate Stone // Function is recursive so that the size of all ancestors is taken into
2699b9c1b51eSKate Stone // account.
2700b9c1b51eSKate Stone size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
270180af0b9eSLuke Drummond   // Offsets to children plus zero terminator
270280af0b9eSLuke Drummond   size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
270380af0b9eSLuke Drummond   // Size of header struct with type details
270480af0b9eSLuke Drummond   size += sizeof(AllocationDetails::ElementHeader);
270526e52a70SEwan Crawford 
270626e52a70SEwan Crawford   // Calculate recursively for all descendants
270726e52a70SEwan Crawford   for (const Element &child : elem.children)
270826e52a70SEwan Crawford     size += CalculateElementHeaderSize(child);
270926e52a70SEwan Crawford 
271026e52a70SEwan Crawford   return size;
271126e52a70SEwan Crawford }
271226e52a70SEwan Crawford 
271380af0b9eSLuke Drummond // Function copies allocation contents into a binary file. This file can then be
271480af0b9eSLuke Drummond // loaded later into a different allocation. There is a header, FileHeader,
271580af0b9eSLuke Drummond // before the allocation data containing meta-data.
2716b9c1b51eSKate Stone bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
271780af0b9eSLuke Drummond                                          const char *path,
2718b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
271955232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
272055232f09SEwan Crawford 
272155232f09SEwan Crawford   // Find allocation with the given id
272255232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
272355232f09SEwan Crawford   if (!alloc)
272455232f09SEwan Crawford     return false;
272555232f09SEwan Crawford 
272655232f09SEwan Crawford   if (log)
2727b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2728b9c1b51eSKate Stone                 *alloc->address.get());
272955232f09SEwan Crawford 
273055232f09SEwan Crawford   // JIT all the allocation details
273180af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
273255232f09SEwan Crawford     if (log)
2733b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2734b9c1b51eSKate Stone                   __FUNCTION__);
273555232f09SEwan Crawford 
2736b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
273755232f09SEwan Crawford       if (log)
2738b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
27394cfc9198SSylvestre Ledru       return false;
274055232f09SEwan Crawford     }
274155232f09SEwan Crawford   }
274255232f09SEwan Crawford 
2743b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2744b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() &&
2745b9c1b51eSKate Stone          alloc->element.datum_size.get() &&
2746b9c1b51eSKate Stone          alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2747b3f7f69dSAidan Dodds          "Allocation information not available");
274855232f09SEwan Crawford 
274955232f09SEwan Crawford   // Check we can create writable file
275080af0b9eSLuke Drummond   FileSpec file_spec(path, true);
2751b9c1b51eSKate Stone   File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate |
2752b9c1b51eSKate Stone                            File::eOpenOptionTruncate);
2753b9c1b51eSKate Stone   if (!file) {
275480af0b9eSLuke Drummond     strm.Printf("Error: Failed to open '%s' for writing", path);
275555232f09SEwan Crawford     strm.EOL();
275655232f09SEwan Crawford     return false;
275755232f09SEwan Crawford   }
275855232f09SEwan Crawford 
275955232f09SEwan Crawford   // Read allocation into buffer of heap memory
276055232f09SEwan Crawford   const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2761b9c1b51eSKate Stone   if (!buffer) {
276255232f09SEwan Crawford     strm.Printf("Error: Couldn't read allocation data into buffer");
276355232f09SEwan Crawford     strm.EOL();
276455232f09SEwan Crawford     return false;
276555232f09SEwan Crawford   }
276655232f09SEwan Crawford 
276755232f09SEwan Crawford   // Create the file header
276855232f09SEwan Crawford   AllocationDetails::FileHeader head;
2769b3f7f69dSAidan Dodds   memcpy(head.ident, "RSAD", 4);
27702d62328aSEwan Crawford   head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
27712d62328aSEwan Crawford   head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
27722d62328aSEwan Crawford   head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
277326e52a70SEwan Crawford 
277426e52a70SEwan Crawford   const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2775b9c1b51eSKate Stone   assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2776b9c1b51eSKate Stone              UINT16_MAX &&
2777b9c1b51eSKate Stone          "Element header too large");
2778b9c1b51eSKate Stone   head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2779b9c1b51eSKate Stone                                         element_header_size);
278055232f09SEwan Crawford 
278155232f09SEwan Crawford   // Write the file header
278255232f09SEwan Crawford   size_t num_bytes = sizeof(AllocationDetails::FileHeader);
278326e52a70SEwan Crawford   if (log)
2784b9c1b51eSKate Stone     log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2785b9c1b51eSKate Stone                 (uint64_t)num_bytes);
278626e52a70SEwan Crawford 
278726e52a70SEwan Crawford   Error err = file.Write(&head, num_bytes);
2788b9c1b51eSKate Stone   if (!err.Success()) {
278980af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
279026e52a70SEwan Crawford     strm.EOL();
279126e52a70SEwan Crawford     return false;
279226e52a70SEwan Crawford   }
279326e52a70SEwan Crawford 
279426e52a70SEwan Crawford   // Create the headers describing the element type of the allocation.
2795b9c1b51eSKate Stone   std::shared_ptr<uint8_t> element_header_buffer(
2796b9c1b51eSKate Stone       new uint8_t[element_header_size]);
2797b9c1b51eSKate Stone   if (element_header_buffer == nullptr) {
2798b9c1b51eSKate Stone     strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2799b9c1b51eSKate Stone                 " bytes on the heap",
2800b9c1b51eSKate Stone                 (uint64_t)element_header_size);
280126e52a70SEwan Crawford     strm.EOL();
280226e52a70SEwan Crawford     return false;
280326e52a70SEwan Crawford   }
280426e52a70SEwan Crawford 
280526e52a70SEwan Crawford   PopulateElementHeaders(element_header_buffer, 0, alloc->element);
280626e52a70SEwan Crawford 
280726e52a70SEwan Crawford   // Write headers for allocation element type to file
280826e52a70SEwan Crawford   num_bytes = element_header_size;
280926e52a70SEwan Crawford   if (log)
2810b9c1b51eSKate Stone     log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.",
2811b9c1b51eSKate Stone                 __FUNCTION__, (uint64_t)num_bytes);
281226e52a70SEwan Crawford 
281326e52a70SEwan Crawford   err = file.Write(element_header_buffer.get(), num_bytes);
2814b9c1b51eSKate Stone   if (!err.Success()) {
281580af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
281655232f09SEwan Crawford     strm.EOL();
281755232f09SEwan Crawford     return false;
281855232f09SEwan Crawford   }
281955232f09SEwan Crawford 
282055232f09SEwan Crawford   // Write allocation data to file
282155232f09SEwan Crawford   num_bytes = static_cast<size_t>(*alloc->size.get());
282255232f09SEwan Crawford   if (log)
2823b9c1b51eSKate Stone     log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2824b9c1b51eSKate Stone                 (uint64_t)num_bytes);
282555232f09SEwan Crawford 
282655232f09SEwan Crawford   err = file.Write(buffer.get(), num_bytes);
2827b9c1b51eSKate Stone   if (!err.Success()) {
282880af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
282955232f09SEwan Crawford     strm.EOL();
283055232f09SEwan Crawford     return false;
283155232f09SEwan Crawford   }
283255232f09SEwan Crawford 
283380af0b9eSLuke Drummond   strm.Printf("Allocation written to file '%s'", path);
283455232f09SEwan Crawford   strm.EOL();
283515f2bd95SEwan Crawford   return true;
283615f2bd95SEwan Crawford }
283715f2bd95SEwan Crawford 
2838b9c1b51eSKate Stone bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
28394640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
28404640cde1SColin Riley 
2841b9c1b51eSKate Stone   if (module_sp) {
2842b9c1b51eSKate Stone     for (const auto &rs_module : m_rsmodules) {
2843b9c1b51eSKate Stone       if (rs_module->m_module == module_sp) {
28447dc7771cSEwan Crawford         // Check if the user has enabled automatically breaking on
28457dc7771cSEwan Crawford         // all RS kernels.
28467dc7771cSEwan Crawford         if (m_breakAllKernels)
28477dc7771cSEwan Crawford           BreakOnModuleKernels(rs_module);
28487dc7771cSEwan Crawford 
28495ec532a9SColin Riley         return false;
28505ec532a9SColin Riley       }
28517dc7771cSEwan Crawford     }
2852ef20b08fSColin Riley     bool module_loaded = false;
2853b9c1b51eSKate Stone     switch (GetModuleKind(module_sp)) {
2854b9c1b51eSKate Stone     case eModuleKindKernelObj: {
28554640cde1SColin Riley       RSModuleDescriptorSP module_desc;
28564640cde1SColin Riley       module_desc.reset(new RSModuleDescriptor(module_sp));
2857b9c1b51eSKate Stone       if (module_desc->ParseRSInfo()) {
28585ec532a9SColin Riley         m_rsmodules.push_back(module_desc);
285947d64161SLuke Drummond         module_desc->WarnIfVersionMismatch(GetProcess()
286047d64161SLuke Drummond                                                ->GetTarget()
286147d64161SLuke Drummond                                                .GetDebugger()
286247d64161SLuke Drummond                                                .GetAsyncOutputStream()
286347d64161SLuke Drummond                                                .get());
2864ef20b08fSColin Riley         module_loaded = true;
28655ec532a9SColin Riley       }
2866b9c1b51eSKate Stone       if (module_loaded) {
28674640cde1SColin Riley         FixupScriptDetails(module_desc);
28684640cde1SColin Riley       }
2869ef20b08fSColin Riley       break;
2870ef20b08fSColin Riley     }
2871b9c1b51eSKate Stone     case eModuleKindDriver: {
2872b9c1b51eSKate Stone       if (!m_libRSDriver) {
28734640cde1SColin Riley         m_libRSDriver = module_sp;
28744640cde1SColin Riley         LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
28754640cde1SColin Riley       }
28764640cde1SColin Riley       break;
28774640cde1SColin Riley     }
2878b9c1b51eSKate Stone     case eModuleKindImpl: {
287921fed052SAidan Dodds       if (!m_libRSCpuRef) {
28804640cde1SColin Riley         m_libRSCpuRef = module_sp;
288121fed052SAidan Dodds         LoadRuntimeHooks(m_libRSCpuRef, RenderScriptRuntime::eModuleKindImpl);
288221fed052SAidan Dodds       }
28834640cde1SColin Riley       break;
28844640cde1SColin Riley     }
2885b9c1b51eSKate Stone     case eModuleKindLibRS: {
2886b9c1b51eSKate Stone       if (!m_libRS) {
28874640cde1SColin Riley         m_libRS = module_sp;
28884640cde1SColin Riley         static ConstString gDbgPresentStr("gDebuggerPresent");
2889b9c1b51eSKate Stone         const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2890b9c1b51eSKate Stone             gDbgPresentStr, eSymbolTypeData);
2891b9c1b51eSKate Stone         if (debug_present) {
289280af0b9eSLuke Drummond           Error err;
28934640cde1SColin Riley           uint32_t flag = 0x00000001U;
28944640cde1SColin Riley           Target &target = GetProcess()->GetTarget();
2895358cf1eaSGreg Clayton           addr_t addr = debug_present->GetLoadAddress(&target);
289680af0b9eSLuke Drummond           GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
289780af0b9eSLuke Drummond           if (err.Success()) {
28984640cde1SColin Riley             if (log)
2899b9c1b51eSKate Stone               log->Printf("%s - debugger present flag set on debugee.",
2900b9c1b51eSKate Stone                           __FUNCTION__);
29014640cde1SColin Riley 
29024640cde1SColin Riley             m_debuggerPresentFlagged = true;
2903b9c1b51eSKate Stone           } else if (log) {
2904b9c1b51eSKate Stone             log->Printf("%s - error writing debugger present flags '%s' ",
290580af0b9eSLuke Drummond                         __FUNCTION__, err.AsCString());
29064640cde1SColin Riley           }
2907b9c1b51eSKate Stone         } else if (log) {
2908b9c1b51eSKate Stone           log->Printf(
2909b9c1b51eSKate Stone               "%s - error writing debugger present flags - symbol not found",
2910b9c1b51eSKate Stone               __FUNCTION__);
29114640cde1SColin Riley         }
29124640cde1SColin Riley       }
29134640cde1SColin Riley       break;
29144640cde1SColin Riley     }
2915ef20b08fSColin Riley     default:
2916ef20b08fSColin Riley       break;
2917ef20b08fSColin Riley     }
2918ef20b08fSColin Riley     if (module_loaded)
2919ef20b08fSColin Riley       Update();
2920ef20b08fSColin Riley     return module_loaded;
29215ec532a9SColin Riley   }
29225ec532a9SColin Riley   return false;
29235ec532a9SColin Riley }
29245ec532a9SColin Riley 
2925b9c1b51eSKate Stone void RenderScriptRuntime::Update() {
2926b9c1b51eSKate Stone   if (m_rsmodules.size() > 0) {
2927b9c1b51eSKate Stone     if (!m_initiated) {
2928ef20b08fSColin Riley       Initiate();
2929ef20b08fSColin Riley     }
2930ef20b08fSColin Riley   }
2931ef20b08fSColin Riley }
2932ef20b08fSColin Riley 
293347d64161SLuke Drummond void RSModuleDescriptor::WarnIfVersionMismatch(lldb_private::Stream *s) const {
293447d64161SLuke Drummond   if (!s)
293547d64161SLuke Drummond     return;
293647d64161SLuke Drummond 
293747d64161SLuke Drummond   if (m_slang_version.empty() || m_bcc_version.empty()) {
293847d64161SLuke Drummond     s->PutCString("WARNING: Unknown bcc or slang (llvm-rs-cc) version; debug "
293947d64161SLuke Drummond                   "experience may be unreliable");
294047d64161SLuke Drummond     s->EOL();
294147d64161SLuke Drummond   } else if (m_slang_version != m_bcc_version) {
294247d64161SLuke Drummond     s->Printf("WARNING: The debug info emitted by the slang frontend "
294347d64161SLuke Drummond               "(llvm-rs-cc) used to build this module (%s) does not match the "
294447d64161SLuke Drummond               "version of bcc used to generate the debug information (%s). "
294547d64161SLuke Drummond               "This is an unsupported configuration and may result in a poor "
294647d64161SLuke Drummond               "debugging experience; proceed with caution",
294747d64161SLuke Drummond               m_slang_version.c_str(), m_bcc_version.c_str());
294847d64161SLuke Drummond     s->EOL();
294947d64161SLuke Drummond   }
295047d64161SLuke Drummond }
295147d64161SLuke Drummond 
29527f193d69SLuke Drummond bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
29537f193d69SLuke Drummond                                           size_t n_lines) {
29547f193d69SLuke Drummond   // Skip the pragma prototype line
29557f193d69SLuke Drummond   ++lines;
29567f193d69SLuke Drummond   for (; n_lines--; ++lines) {
29577f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
29587f193d69SLuke Drummond     m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
29597f193d69SLuke Drummond   }
29607f193d69SLuke Drummond   return true;
29617f193d69SLuke Drummond }
29627f193d69SLuke Drummond 
29637f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
29647f193d69SLuke Drummond                                                 size_t n_lines) {
29657f193d69SLuke Drummond   // The list of reduction kernels in the `.rs.info` symbol is of the form
29667f193d69SLuke Drummond   // "signature - accumulatordatasize - reduction_name - initializer_name -
29677f193d69SLuke Drummond   // accumulator_name - combiner_name -
29687f193d69SLuke Drummond   // outconverter_name - halter_name"
29697f193d69SLuke Drummond   // Where a function is not explicitly named by the user, or is not generated
29707f193d69SLuke Drummond   // by the compiler, it is named "." so the
29717f193d69SLuke Drummond   // dash separated list should always be 8 items long
29727f193d69SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
29737f193d69SLuke Drummond   // Skip the exportReduceCount line
29747f193d69SLuke Drummond   ++lines;
29757f193d69SLuke Drummond   for (; n_lines--; ++lines) {
29767f193d69SLuke Drummond     llvm::SmallVector<llvm::StringRef, 8> spec;
29777f193d69SLuke Drummond     lines->split(spec, " - ");
29787f193d69SLuke Drummond     if (spec.size() != 8) {
29797f193d69SLuke Drummond       if (spec.size() < 8) {
29807f193d69SLuke Drummond         if (log)
29817f193d69SLuke Drummond           log->Error("Error parsing RenderScript reduction spec. wrong number "
29827f193d69SLuke Drummond                      "of fields");
29837f193d69SLuke Drummond         return false;
29847f193d69SLuke Drummond       } else if (log)
29857f193d69SLuke Drummond         log->Warning("Extraneous members in reduction spec: '%s'",
29867f193d69SLuke Drummond                      lines->str().c_str());
29877f193d69SLuke Drummond     }
29887f193d69SLuke Drummond 
29897f193d69SLuke Drummond     const auto sig_s = spec[0];
29907f193d69SLuke Drummond     uint32_t sig;
29917f193d69SLuke Drummond     if (sig_s.getAsInteger(10, sig)) {
29927f193d69SLuke Drummond       if (log)
29937f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid kernel "
29947f193d69SLuke Drummond                    "signature: '%s'",
29957f193d69SLuke Drummond                    sig_s.str().c_str());
29967f193d69SLuke Drummond       return false;
29977f193d69SLuke Drummond     }
29987f193d69SLuke Drummond 
29997f193d69SLuke Drummond     const auto accum_data_size_s = spec[1];
30007f193d69SLuke Drummond     uint32_t accum_data_size;
30017f193d69SLuke Drummond     if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
30027f193d69SLuke Drummond       if (log)
30037f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid "
30047f193d69SLuke Drummond                    "accumulator data size %s",
30057f193d69SLuke Drummond                    accum_data_size_s.str().c_str());
30067f193d69SLuke Drummond       return false;
30077f193d69SLuke Drummond     }
30087f193d69SLuke Drummond 
30097f193d69SLuke Drummond     if (log)
30107f193d69SLuke Drummond       log->Printf("Found RenderScript reduction '%s'", spec[2].str().c_str());
30117f193d69SLuke Drummond 
30127f193d69SLuke Drummond     m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
30137f193d69SLuke Drummond                                                  spec[2], spec[3], spec[4],
30147f193d69SLuke Drummond                                                  spec[5], spec[6], spec[7]));
30157f193d69SLuke Drummond   }
30167f193d69SLuke Drummond   return true;
30177f193d69SLuke Drummond }
30187f193d69SLuke Drummond 
301947d64161SLuke Drummond bool RSModuleDescriptor::ParseVersionInfo(llvm::StringRef *lines,
302047d64161SLuke Drummond                                           size_t n_lines) {
302147d64161SLuke Drummond   // Skip the versionInfo line
302247d64161SLuke Drummond   ++lines;
302347d64161SLuke Drummond   for (; n_lines--; ++lines) {
302447d64161SLuke Drummond     // We're only interested in bcc and slang versions, and ignore all other
302547d64161SLuke Drummond     // versionInfo lines
302647d64161SLuke Drummond     const auto kv_pair = lines->split(" - ");
302747d64161SLuke Drummond     if (kv_pair.first == "slang")
302847d64161SLuke Drummond       m_slang_version = kv_pair.second.str();
302947d64161SLuke Drummond     else if (kv_pair.first == "bcc")
303047d64161SLuke Drummond       m_bcc_version = kv_pair.second.str();
303147d64161SLuke Drummond   }
303247d64161SLuke Drummond   return true;
303347d64161SLuke Drummond }
303447d64161SLuke Drummond 
30357f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
30367f193d69SLuke Drummond                                                  size_t n_lines) {
30377f193d69SLuke Drummond   // Skip the exportForeachCount line
30387f193d69SLuke Drummond   ++lines;
30397f193d69SLuke Drummond   for (; n_lines--; ++lines) {
30407f193d69SLuke Drummond     uint32_t slot;
30417f193d69SLuke Drummond     // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
30427f193d69SLuke Drummond     // pair per line
30437f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
30447f193d69SLuke Drummond     if (kv_pair.first.getAsInteger(10, slot))
30457f193d69SLuke Drummond       return false;
30467f193d69SLuke Drummond     m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
30477f193d69SLuke Drummond   }
30487f193d69SLuke Drummond   return true;
30497f193d69SLuke Drummond }
30507f193d69SLuke Drummond 
30517f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
30527f193d69SLuke Drummond                                              size_t n_lines) {
30537f193d69SLuke Drummond   // Skip the ExportVarCount line
30547f193d69SLuke Drummond   ++lines;
30557f193d69SLuke Drummond   for (; n_lines--; ++lines)
30567f193d69SLuke Drummond     m_globals.push_back(RSGlobalDescriptor(this, *lines));
30577f193d69SLuke Drummond   return true;
30587f193d69SLuke Drummond }
30595ec532a9SColin Riley 
3060b9c1b51eSKate Stone // The .rs.info symbol in renderscript modules contains a string which needs to
3061b9c1b51eSKate Stone // be parsed.
30625ec532a9SColin Riley // The string is basic and is parsed on a line by line basis.
3063b9c1b51eSKate Stone bool RSModuleDescriptor::ParseRSInfo() {
3064b0be30f7SAidan Dodds   assert(m_module);
30657f193d69SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3066b9c1b51eSKate Stone   const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
3067b9c1b51eSKate Stone       ConstString(".rs.info"), eSymbolTypeData);
3068b0be30f7SAidan Dodds   if (!info_sym)
3069b0be30f7SAidan Dodds     return false;
3070b0be30f7SAidan Dodds 
3071358cf1eaSGreg Clayton   const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
3072b0be30f7SAidan Dodds   if (addr == LLDB_INVALID_ADDRESS)
3073b0be30f7SAidan Dodds     return false;
3074b0be30f7SAidan Dodds 
30755ec532a9SColin Riley   const addr_t size = info_sym->GetByteSize();
30765ec532a9SColin Riley   const FileSpec fs = m_module->GetFileSpec();
30775ec532a9SColin Riley 
3078*7f6a7a37SZachary Turner   auto buffer = DataBufferLLVM::CreateSliceFromPath(fs.GetPath(), size, addr);
30795ec532a9SColin Riley   if (!buffer)
30805ec532a9SColin Riley     return false;
30815ec532a9SColin Riley 
3082b0be30f7SAidan Dodds   // split rs.info. contents into lines
30837f193d69SLuke Drummond   llvm::SmallVector<llvm::StringRef, 128> info_lines;
30845ec532a9SColin Riley   {
30857f193d69SLuke Drummond     const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
30867f193d69SLuke Drummond     raw_rs_info.split(info_lines, '\n');
30877f193d69SLuke Drummond     if (log)
30887f193d69SLuke Drummond       log->Printf("'.rs.info symbol for '%s':\n%s",
30897f193d69SLuke Drummond                   m_module->GetFileSpec().GetCString(),
30907f193d69SLuke Drummond                   raw_rs_info.str().c_str());
3091b0be30f7SAidan Dodds   }
3092b0be30f7SAidan Dodds 
30937f193d69SLuke Drummond   enum {
30947f193d69SLuke Drummond     eExportVar,
30957f193d69SLuke Drummond     eExportForEach,
30967f193d69SLuke Drummond     eExportReduce,
30977f193d69SLuke Drummond     ePragma,
30987f193d69SLuke Drummond     eBuildChecksum,
309947d64161SLuke Drummond     eObjectSlot,
310047d64161SLuke Drummond     eVersionInfo,
31017f193d69SLuke Drummond   };
31027f193d69SLuke Drummond 
3103b3bbcb12SLuke Drummond   const auto rs_info_handler = [](llvm::StringRef name) -> int {
3104b3bbcb12SLuke Drummond     return llvm::StringSwitch<int>(name)
3105b3bbcb12SLuke Drummond         // The number of visible global variables in the script
3106b3bbcb12SLuke Drummond         .Case("exportVarCount", eExportVar)
31077f193d69SLuke Drummond         // The number of RenderScrip `forEach` kernels __attribute__((kernel))
3108b3bbcb12SLuke Drummond         .Case("exportForEachCount", eExportForEach)
3109b3bbcb12SLuke Drummond         // The number of generalreductions: This marked in the script by
3110b3bbcb12SLuke Drummond         // `#pragma reduce()`
3111b3bbcb12SLuke Drummond         .Case("exportReduceCount", eExportReduce)
3112b3bbcb12SLuke Drummond         // Total count of all RenderScript specific `#pragmas` used in the
3113b3bbcb12SLuke Drummond         // script
3114b3bbcb12SLuke Drummond         .Case("pragmaCount", ePragma)
3115b3bbcb12SLuke Drummond         .Case("objectSlotCount", eObjectSlot)
311647d64161SLuke Drummond         .Case("versionInfo", eVersionInfo)
3117b3bbcb12SLuke Drummond         .Default(-1);
3118b3bbcb12SLuke Drummond   };
3119b0be30f7SAidan Dodds 
3120b0be30f7SAidan Dodds   // parse all text lines of .rs.info
3121b9c1b51eSKate Stone   for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
31227f193d69SLuke Drummond     const auto kv_pair = line->split(": ");
31237f193d69SLuke Drummond     const auto key = kv_pair.first;
31247f193d69SLuke Drummond     const auto val = kv_pair.second.trim();
31255ec532a9SColin Riley 
3126b3bbcb12SLuke Drummond     const auto handler = rs_info_handler(key);
3127b3bbcb12SLuke Drummond     if (handler == -1)
31287f193d69SLuke Drummond       continue;
31297f193d69SLuke Drummond     // getAsInteger returns `true` on an error condition - we're only interested
3130b3bbcb12SLuke Drummond     // in numeric fields at the moment
31317f193d69SLuke Drummond     uint64_t n_lines;
31327f193d69SLuke Drummond     if (val.getAsInteger(10, n_lines)) {
31336302bf6aSPavel Labath       LLDB_LOGV(log, "Failed to parse non-numeric '.rs.info' section {0}",
31346302bf6aSPavel Labath                 line->str());
31357f193d69SLuke Drummond       continue;
31367f193d69SLuke Drummond     }
31377f193d69SLuke Drummond     if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
31387f193d69SLuke Drummond       return false;
31397f193d69SLuke Drummond 
31407f193d69SLuke Drummond     bool success = false;
3141b3bbcb12SLuke Drummond     switch (handler) {
31427f193d69SLuke Drummond     case eExportVar:
31437f193d69SLuke Drummond       success = ParseExportVarCount(line, n_lines);
31447f193d69SLuke Drummond       break;
31457f193d69SLuke Drummond     case eExportForEach:
31467f193d69SLuke Drummond       success = ParseExportForeachCount(line, n_lines);
31477f193d69SLuke Drummond       break;
31487f193d69SLuke Drummond     case eExportReduce:
31497f193d69SLuke Drummond       success = ParseExportReduceCount(line, n_lines);
31507f193d69SLuke Drummond       break;
31517f193d69SLuke Drummond     case ePragma:
31527f193d69SLuke Drummond       success = ParsePragmaCount(line, n_lines);
31537f193d69SLuke Drummond       break;
315447d64161SLuke Drummond     case eVersionInfo:
315547d64161SLuke Drummond       success = ParseVersionInfo(line, n_lines);
315647d64161SLuke Drummond       break;
31577f193d69SLuke Drummond     default: {
31587f193d69SLuke Drummond       if (log)
31597f193d69SLuke Drummond         log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__,
31607f193d69SLuke Drummond                     line->str().c_str());
31617f193d69SLuke Drummond       continue;
31627f193d69SLuke Drummond     }
31637f193d69SLuke Drummond     }
31647f193d69SLuke Drummond     if (!success)
31657f193d69SLuke Drummond       return false;
31667f193d69SLuke Drummond     line += n_lines;
31677f193d69SLuke Drummond   }
31687f193d69SLuke Drummond   return info_lines.size() > 0;
31695ec532a9SColin Riley }
31705ec532a9SColin Riley 
3171b9c1b51eSKate Stone void RenderScriptRuntime::Status(Stream &strm) const {
3172b9c1b51eSKate Stone   if (m_libRS) {
31734640cde1SColin Riley     strm.Printf("Runtime Library discovered.");
31744640cde1SColin Riley     strm.EOL();
31754640cde1SColin Riley   }
3176b9c1b51eSKate Stone   if (m_libRSDriver) {
31774640cde1SColin Riley     strm.Printf("Runtime Driver discovered.");
31784640cde1SColin Riley     strm.EOL();
31794640cde1SColin Riley   }
3180b9c1b51eSKate Stone   if (m_libRSCpuRef) {
31814640cde1SColin Riley     strm.Printf("CPU Reference Implementation discovered.");
31824640cde1SColin Riley     strm.EOL();
31834640cde1SColin Riley   }
31844640cde1SColin Riley 
3185b9c1b51eSKate Stone   if (m_runtimeHooks.size()) {
31864640cde1SColin Riley     strm.Printf("Runtime functions hooked:");
31874640cde1SColin Riley     strm.EOL();
3188b9c1b51eSKate Stone     for (auto b : m_runtimeHooks) {
31894640cde1SColin Riley       strm.Indent(b.second->defn->name);
31904640cde1SColin Riley       strm.EOL();
31914640cde1SColin Riley     }
3192b9c1b51eSKate Stone   } else {
31934640cde1SColin Riley     strm.Printf("Runtime is not hooked.");
31944640cde1SColin Riley     strm.EOL();
31954640cde1SColin Riley   }
31964640cde1SColin Riley }
31974640cde1SColin Riley 
3198b9c1b51eSKate Stone void RenderScriptRuntime::DumpContexts(Stream &strm) const {
31994640cde1SColin Riley   strm.Printf("Inferred RenderScript Contexts:");
32004640cde1SColin Riley   strm.EOL();
32014640cde1SColin Riley   strm.IndentMore();
32024640cde1SColin Riley 
32034640cde1SColin Riley   std::map<addr_t, uint64_t> contextReferences;
32044640cde1SColin Riley 
320578f339d1SEwan Crawford   // Iterate over all of the currently discovered scripts.
3206b9c1b51eSKate Stone   // Note: We cant push or pop from m_scripts inside this loop or it may
3207b9c1b51eSKate Stone   // invalidate script.
3208b9c1b51eSKate Stone   for (const auto &script : m_scripts) {
320978f339d1SEwan Crawford     if (!script->context.isValid())
321078f339d1SEwan Crawford       continue;
321178f339d1SEwan Crawford     lldb::addr_t context = *script->context;
321278f339d1SEwan Crawford 
3213b9c1b51eSKate Stone     if (contextReferences.find(context) != contextReferences.end()) {
321478f339d1SEwan Crawford       contextReferences[context]++;
3215b9c1b51eSKate Stone     } else {
321678f339d1SEwan Crawford       contextReferences[context] = 1;
32174640cde1SColin Riley     }
32184640cde1SColin Riley   }
32194640cde1SColin Riley 
3220b9c1b51eSKate Stone   for (const auto &cRef : contextReferences) {
3221b9c1b51eSKate Stone     strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
3222b9c1b51eSKate Stone                 cRef.first, cRef.second);
32234640cde1SColin Riley     strm.EOL();
32244640cde1SColin Riley   }
32254640cde1SColin Riley   strm.IndentLess();
32264640cde1SColin Riley }
32274640cde1SColin Riley 
3228b9c1b51eSKate Stone void RenderScriptRuntime::DumpKernels(Stream &strm) const {
32294640cde1SColin Riley   strm.Printf("RenderScript Kernels:");
32304640cde1SColin Riley   strm.EOL();
32314640cde1SColin Riley   strm.IndentMore();
3232b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
32334640cde1SColin Riley     strm.Printf("Resource '%s':", module->m_resname.c_str());
32344640cde1SColin Riley     strm.EOL();
3235b9c1b51eSKate Stone     for (const auto &kernel : module->m_kernels) {
32364640cde1SColin Riley       strm.Indent(kernel.m_name.AsCString());
32374640cde1SColin Riley       strm.EOL();
32384640cde1SColin Riley     }
32394640cde1SColin Riley   }
32404640cde1SColin Riley   strm.IndentLess();
32414640cde1SColin Riley }
32424640cde1SColin Riley 
3243a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails *
3244b9c1b51eSKate Stone RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
3245a0f08674SEwan Crawford   AllocationDetails *alloc = nullptr;
3246a0f08674SEwan Crawford 
3247a0f08674SEwan Crawford   // See if we can find allocation using id as an index;
3248b9c1b51eSKate Stone   if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
3249b9c1b51eSKate Stone       m_allocations[alloc_id - 1]->id == alloc_id) {
3250a0f08674SEwan Crawford     alloc = m_allocations[alloc_id - 1].get();
3251a0f08674SEwan Crawford     return alloc;
3252a0f08674SEwan Crawford   }
3253a0f08674SEwan Crawford 
3254a0f08674SEwan Crawford   // Fallback to searching
3255b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
3256b9c1b51eSKate Stone     if (a->id == alloc_id) {
3257a0f08674SEwan Crawford       alloc = a.get();
3258a0f08674SEwan Crawford       break;
3259a0f08674SEwan Crawford     }
3260a0f08674SEwan Crawford   }
3261a0f08674SEwan Crawford 
3262b9c1b51eSKate Stone   if (alloc == nullptr) {
3263b9c1b51eSKate Stone     strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
3264b9c1b51eSKate Stone                 alloc_id);
3265a0f08674SEwan Crawford     strm.EOL();
3266a0f08674SEwan Crawford   }
3267a0f08674SEwan Crawford 
3268a0f08674SEwan Crawford   return alloc;
3269a0f08674SEwan Crawford }
3270a0f08674SEwan Crawford 
3271b9c1b51eSKate Stone // Prints the contents of an allocation to the output stream, which may be a
3272b9c1b51eSKate Stone // file
3273b9c1b51eSKate Stone bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
3274b9c1b51eSKate Stone                                          const uint32_t id) {
3275a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3276a0f08674SEwan Crawford 
3277a0f08674SEwan Crawford   // Check we can find the desired allocation
3278a0f08674SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, id);
3279a0f08674SEwan Crawford   if (!alloc)
3280a0f08674SEwan Crawford     return false; // FindAllocByID() will print error message for us here
3281a0f08674SEwan Crawford 
3282a0f08674SEwan Crawford   if (log)
3283b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
3284b9c1b51eSKate Stone                 *alloc->address.get());
3285a0f08674SEwan Crawford 
3286a0f08674SEwan Crawford   // Check we have information about the allocation, if not calculate it
328780af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
3288a0f08674SEwan Crawford     if (log)
3289b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
3290b9c1b51eSKate Stone                   __FUNCTION__);
3291a0f08674SEwan Crawford 
3292a0f08674SEwan Crawford     // JIT all the allocation information
3293b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
3294a0f08674SEwan Crawford       strm.Printf("Error: Couldn't JIT allocation details");
3295a0f08674SEwan Crawford       strm.EOL();
3296a0f08674SEwan Crawford       return false;
3297a0f08674SEwan Crawford     }
3298a0f08674SEwan Crawford   }
3299a0f08674SEwan Crawford 
3300a0f08674SEwan Crawford   // Establish format and size of each data element
3301b3f7f69dSAidan Dodds   const uint32_t vec_size = *alloc->element.type_vec_size.get();
33028b244e21SEwan Crawford   const Element::DataType type = *alloc->element.type.get();
3303a0f08674SEwan Crawford 
3304b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
3305b9c1b51eSKate Stone          "Invalid allocation type");
3306a0f08674SEwan Crawford 
33072e920715SEwan Crawford   lldb::Format format;
33082e920715SEwan Crawford   if (type >= Element::RS_TYPE_ELEMENT)
33092e920715SEwan Crawford     format = eFormatHex;
33102e920715SEwan Crawford   else
3311b9c1b51eSKate Stone     format = vec_size == 1
3312b9c1b51eSKate Stone                  ? static_cast<lldb::Format>(
3313b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatSingle])
3314b9c1b51eSKate Stone                  : static_cast<lldb::Format>(
3315b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatVector]);
3316a0f08674SEwan Crawford 
3317b3f7f69dSAidan Dodds   const uint32_t data_size = *alloc->element.datum_size.get();
3318a0f08674SEwan Crawford 
3319a0f08674SEwan Crawford   if (log)
3320b9c1b51eSKate Stone     log->Printf("%s - element size %" PRIu32 " bytes, including padding",
3321b9c1b51eSKate Stone                 __FUNCTION__, data_size);
3322a0f08674SEwan Crawford 
332355232f09SEwan Crawford   // Allocate a buffer to copy data into
332455232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3325b9c1b51eSKate Stone   if (!buffer) {
33262e920715SEwan Crawford     strm.Printf("Error: Couldn't read allocation data");
332755232f09SEwan Crawford     strm.EOL();
332855232f09SEwan Crawford     return false;
332955232f09SEwan Crawford   }
333055232f09SEwan Crawford 
3331a0f08674SEwan Crawford   // Calculate stride between rows as there may be padding at end of rows since
3332a0f08674SEwan Crawford   // allocated memory is 16-byte aligned
3333b9c1b51eSKate Stone   if (!alloc->stride.isValid()) {
3334a0f08674SEwan Crawford     if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
3335a0f08674SEwan Crawford       alloc->stride = 0;
3336b9c1b51eSKate Stone     else if (!JITAllocationStride(alloc, frame_ptr)) {
3337a0f08674SEwan Crawford       strm.Printf("Error: Couldn't calculate allocation row stride");
3338a0f08674SEwan Crawford       strm.EOL();
3339a0f08674SEwan Crawford       return false;
3340a0f08674SEwan Crawford     }
3341a0f08674SEwan Crawford   }
3342b3f7f69dSAidan Dodds   const uint32_t stride = *alloc->stride.get();
3343b3f7f69dSAidan Dodds   const uint32_t size = *alloc->size.get(); // Size of whole allocation
3344b9c1b51eSKate Stone   const uint32_t padding =
3345b9c1b51eSKate Stone       alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3346a0f08674SEwan Crawford   if (log)
3347b9c1b51eSKate Stone     log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32
3348b9c1b51eSKate Stone                 " bytes, padding %" PRIu32,
3349b3f7f69dSAidan Dodds                 __FUNCTION__, stride, size, padding);
3350a0f08674SEwan Crawford 
3351a0f08674SEwan Crawford   // Find dimensions used to index loops, so need to be non-zero
3352b3f7f69dSAidan Dodds   uint32_t dim_x = alloc->dimension.get()->dim_1;
3353a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 1 : dim_x;
3354a0f08674SEwan Crawford 
3355b3f7f69dSAidan Dodds   uint32_t dim_y = alloc->dimension.get()->dim_2;
3356a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 1 : dim_y;
3357a0f08674SEwan Crawford 
3358b3f7f69dSAidan Dodds   uint32_t dim_z = alloc->dimension.get()->dim_3;
3359a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 1 : dim_z;
3360a0f08674SEwan Crawford 
336155232f09SEwan Crawford   // Use data extractor to format output
336280af0b9eSLuke Drummond   const uint32_t target_ptr_size =
3363b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3364b9c1b51eSKate Stone   DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
336580af0b9eSLuke Drummond                            target_ptr_size);
336655232f09SEwan Crawford 
3367b3f7f69dSAidan Dodds   uint32_t offset = 0;   // Offset in buffer to next element to be printed
3368b3f7f69dSAidan Dodds   uint32_t prev_row = 0; // Offset to the start of the previous row
3369a0f08674SEwan Crawford 
3370a0f08674SEwan Crawford   // Iterate over allocation dimensions, printing results to user
3371a0f08674SEwan Crawford   strm.Printf("Data (X, Y, Z):");
3372b9c1b51eSKate Stone   for (uint32_t z = 0; z < dim_z; ++z) {
3373b9c1b51eSKate Stone     for (uint32_t y = 0; y < dim_y; ++y) {
3374a0f08674SEwan Crawford       // Use stride to index start of next row.
3375a0f08674SEwan Crawford       if (!(y == 0 && z == 0))
3376a0f08674SEwan Crawford         offset = prev_row + stride;
3377a0f08674SEwan Crawford       prev_row = offset;
3378a0f08674SEwan Crawford 
3379a0f08674SEwan Crawford       // Print each element in the row individually
3380b9c1b51eSKate Stone       for (uint32_t x = 0; x < dim_x; ++x) {
3381b3f7f69dSAidan Dodds         strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3382b9c1b51eSKate Stone         if ((type == Element::RS_TYPE_NONE) &&
3383b9c1b51eSKate Stone             (alloc->element.children.size() > 0) &&
3384b9c1b51eSKate Stone             (alloc->element.type_name != Element::GetFallbackStructName())) {
33858b244e21SEwan Crawford           // Here we are dumping an Element of struct type.
3386b9c1b51eSKate Stone           // This is done using expression evaluation with the name of the
3387b9c1b51eSKate Stone           // struct type and pointer to element.
3388b9c1b51eSKate Stone           // Don't print the name of the resulting expression, since this will
3389b9c1b51eSKate Stone           // be '$[0-9]+'
33908b244e21SEwan Crawford           DumpValueObjectOptions expr_options;
33918b244e21SEwan Crawford           expr_options.SetHideName(true);
33928b244e21SEwan Crawford 
33938b244e21SEwan Crawford           // Setup expression as derefrencing a pointer cast to element address.
3394ea0636b5SEwan Crawford           char expr_char_buffer[jit_max_expr_size];
339580af0b9eSLuke Drummond           int written =
3396b9c1b51eSKate Stone               snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3397b9c1b51eSKate Stone                        alloc->element.type_name.AsCString(),
3398b9c1b51eSKate Stone                        *alloc->data_ptr.get() + offset);
33998b244e21SEwan Crawford 
340080af0b9eSLuke Drummond           if (written < 0 || written >= jit_max_expr_size) {
34018b244e21SEwan Crawford             if (log)
3402b3f7f69dSAidan Dodds               log->Printf("%s - error in snprintf().", __FUNCTION__);
34038b244e21SEwan Crawford             continue;
34048b244e21SEwan Crawford           }
34058b244e21SEwan Crawford 
34068b244e21SEwan Crawford           // Evaluate expression
34078b244e21SEwan Crawford           ValueObjectSP expr_result;
3408b9c1b51eSKate Stone           GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3409b9c1b51eSKate Stone                                                        frame_ptr, expr_result);
34108b244e21SEwan Crawford 
34118b244e21SEwan Crawford           // Print the results to our stream.
34128b244e21SEwan Crawford           expr_result->Dump(strm, expr_options);
3413b9c1b51eSKate Stone         } else {
341429cb868aSZachary Turner           DumpDataExtractor(alloc_data, &strm, offset, format,
341529cb868aSZachary Turner                             data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0,
341629cb868aSZachary Turner                             0);
34178b244e21SEwan Crawford         }
34188b244e21SEwan Crawford         offset += data_size;
3419a0f08674SEwan Crawford       }
3420a0f08674SEwan Crawford     }
3421a0f08674SEwan Crawford   }
3422a0f08674SEwan Crawford   strm.EOL();
3423a0f08674SEwan Crawford 
3424a0f08674SEwan Crawford   return true;
3425a0f08674SEwan Crawford }
3426a0f08674SEwan Crawford 
3427b9c1b51eSKate Stone // Function recalculates all our cached information about allocations by jitting
342880af0b9eSLuke Drummond // the RS runtime regarding each allocation we know about. Returns true if all
342980af0b9eSLuke Drummond // allocations could be recomputed, false otherwise.
3430b9c1b51eSKate Stone bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3431b9c1b51eSKate Stone                                                   StackFrame *frame_ptr) {
34320d2bfcfbSEwan Crawford   bool success = true;
3433b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
34340d2bfcfbSEwan Crawford     // JIT current allocation information
3435b9c1b51eSKate Stone     if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3436b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3437b9c1b51eSKate Stone                   "\n",
3438b9c1b51eSKate Stone                   alloc->id);
34390d2bfcfbSEwan Crawford       success = false;
34400d2bfcfbSEwan Crawford     }
34410d2bfcfbSEwan Crawford   }
34420d2bfcfbSEwan Crawford 
34430d2bfcfbSEwan Crawford   if (success)
34440d2bfcfbSEwan Crawford     strm.Printf("All allocations successfully recomputed");
34450d2bfcfbSEwan Crawford   strm.EOL();
34460d2bfcfbSEwan Crawford 
34470d2bfcfbSEwan Crawford   return success;
34480d2bfcfbSEwan Crawford }
34490d2bfcfbSEwan Crawford 
345080af0b9eSLuke Drummond // Prints information regarding currently loaded allocations. These details are
345180af0b9eSLuke Drummond // gathered by jitting the runtime, which has as latency. Index parameter
345280af0b9eSLuke Drummond // specifies a single allocation ID to print, or a zero value to print them all
3453b9c1b51eSKate Stone void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3454b9c1b51eSKate Stone                                           const uint32_t index) {
345515f2bd95SEwan Crawford   strm.Printf("RenderScript Allocations:");
345615f2bd95SEwan Crawford   strm.EOL();
345715f2bd95SEwan Crawford   strm.IndentMore();
345815f2bd95SEwan Crawford 
3459b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
3460b649b005SEwan Crawford     // index will only be zero if we want to print all allocations
3461b649b005SEwan Crawford     if (index != 0 && index != alloc->id)
3462b649b005SEwan Crawford       continue;
346315f2bd95SEwan Crawford 
346415f2bd95SEwan Crawford     // JIT current allocation information
346580af0b9eSLuke Drummond     if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3466b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3467b9c1b51eSKate Stone                   alloc->id);
3468b3f7f69dSAidan Dodds       strm.EOL();
346915f2bd95SEwan Crawford       continue;
347015f2bd95SEwan Crawford     }
347115f2bd95SEwan Crawford 
3472b3f7f69dSAidan Dodds     strm.Printf("%" PRIu32 ":", alloc->id);
3473b3f7f69dSAidan Dodds     strm.EOL();
347415f2bd95SEwan Crawford     strm.IndentMore();
347515f2bd95SEwan Crawford 
347615f2bd95SEwan Crawford     strm.Indent("Context: ");
347715f2bd95SEwan Crawford     if (!alloc->context.isValid())
347815f2bd95SEwan Crawford       strm.Printf("unknown\n");
347915f2bd95SEwan Crawford     else
348015f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
348115f2bd95SEwan Crawford 
348215f2bd95SEwan Crawford     strm.Indent("Address: ");
348315f2bd95SEwan Crawford     if (!alloc->address.isValid())
348415f2bd95SEwan Crawford       strm.Printf("unknown\n");
348515f2bd95SEwan Crawford     else
348615f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
348715f2bd95SEwan Crawford 
348815f2bd95SEwan Crawford     strm.Indent("Data pointer: ");
348915f2bd95SEwan Crawford     if (!alloc->data_ptr.isValid())
349015f2bd95SEwan Crawford       strm.Printf("unknown\n");
349115f2bd95SEwan Crawford     else
349215f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
349315f2bd95SEwan Crawford 
349415f2bd95SEwan Crawford     strm.Indent("Dimensions: ");
349515f2bd95SEwan Crawford     if (!alloc->dimension.isValid())
349615f2bd95SEwan Crawford       strm.Printf("unknown\n");
349715f2bd95SEwan Crawford     else
3498b3f7f69dSAidan Dodds       strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3499b9c1b51eSKate Stone                   alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3500b9c1b51eSKate Stone                   alloc->dimension.get()->dim_3);
350115f2bd95SEwan Crawford 
350215f2bd95SEwan Crawford     strm.Indent("Data Type: ");
3503b9c1b51eSKate Stone     if (!alloc->element.type.isValid() ||
3504b9c1b51eSKate Stone         !alloc->element.type_vec_size.isValid())
350515f2bd95SEwan Crawford       strm.Printf("unknown\n");
3506b9c1b51eSKate Stone     else {
35078b244e21SEwan Crawford       const int vector_size = *alloc->element.type_vec_size.get();
35082e920715SEwan Crawford       Element::DataType type = *alloc->element.type.get();
350915f2bd95SEwan Crawford 
35108b244e21SEwan Crawford       if (!alloc->element.type_name.IsEmpty())
35118b244e21SEwan Crawford         strm.Printf("%s\n", alloc->element.type_name.AsCString());
3512b9c1b51eSKate Stone       else {
3513b9c1b51eSKate Stone         // Enum value isn't monotonous, so doesn't always index
3514b9c1b51eSKate Stone         // RsDataTypeToString array
35152e920715SEwan Crawford         if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3516b9c1b51eSKate Stone           type =
3517b9c1b51eSKate Stone               static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3518b3f7f69dSAidan Dodds                                              Element::RS_TYPE_MATRIX_2X2 + 1);
35192e920715SEwan Crawford 
3520b3f7f69dSAidan Dodds         if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3521b3f7f69dSAidan Dodds                      sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3522b3f7f69dSAidan Dodds             vector_size > 4 || vector_size < 1)
352315f2bd95SEwan Crawford           strm.Printf("invalid type\n");
352415f2bd95SEwan Crawford         else
3525b9c1b51eSKate Stone           strm.Printf(
3526b9c1b51eSKate Stone               "%s\n",
3527b9c1b51eSKate Stone               AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3528b3f7f69dSAidan Dodds                                                    [vector_size - 1]);
352915f2bd95SEwan Crawford       }
35302e920715SEwan Crawford     }
353115f2bd95SEwan Crawford 
353215f2bd95SEwan Crawford     strm.Indent("Data Kind: ");
35338b244e21SEwan Crawford     if (!alloc->element.type_kind.isValid())
353415f2bd95SEwan Crawford       strm.Printf("unknown\n");
3535b9c1b51eSKate Stone     else {
35368b244e21SEwan Crawford       const Element::DataKind kind = *alloc->element.type_kind.get();
35378b244e21SEwan Crawford       if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
353815f2bd95SEwan Crawford         strm.Printf("invalid kind\n");
353915f2bd95SEwan Crawford       else
3540b9c1b51eSKate Stone         strm.Printf(
3541b9c1b51eSKate Stone             "%s\n",
3542b9c1b51eSKate Stone             AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
354315f2bd95SEwan Crawford     }
354415f2bd95SEwan Crawford 
354515f2bd95SEwan Crawford     strm.EOL();
354615f2bd95SEwan Crawford     strm.IndentLess();
354715f2bd95SEwan Crawford   }
354815f2bd95SEwan Crawford   strm.IndentLess();
354915f2bd95SEwan Crawford }
355015f2bd95SEwan Crawford 
35517dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
3552b9c1b51eSKate Stone void RenderScriptRuntime::BreakOnModuleKernels(
3553b9c1b51eSKate Stone     const RSModuleDescriptorSP rsmodule_sp) {
3554b9c1b51eSKate Stone   for (const auto &kernel : rsmodule_sp->m_kernels) {
35557dc7771cSEwan Crawford     // Don't set breakpoint on 'root' kernel
35567dc7771cSEwan Crawford     if (strcmp(kernel.m_name.AsCString(), "root") == 0)
35577dc7771cSEwan Crawford       continue;
35587dc7771cSEwan Crawford 
35597dc7771cSEwan Crawford     CreateKernelBreakpoint(kernel.m_name);
35607dc7771cSEwan Crawford   }
35617dc7771cSEwan Crawford }
35627dc7771cSEwan Crawford 
356380af0b9eSLuke Drummond // Method is internally called by the 'kernel breakpoint all' command to enable
356480af0b9eSLuke Drummond // or disable breaking on all kernels. When do_break is true we want to enable
356580af0b9eSLuke Drummond // this functionality. When do_break is false we want to disable it.
3566b9c1b51eSKate Stone void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3567b9c1b51eSKate Stone   Log *log(
3568b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
35697dc7771cSEwan Crawford 
35707dc7771cSEwan Crawford   InitSearchFilter(target);
35717dc7771cSEwan Crawford 
35727dc7771cSEwan Crawford   // Set breakpoints on all the kernels
3573b9c1b51eSKate Stone   if (do_break && !m_breakAllKernels) {
35747dc7771cSEwan Crawford     m_breakAllKernels = true;
35757dc7771cSEwan Crawford 
35767dc7771cSEwan Crawford     for (const auto &module : m_rsmodules)
35777dc7771cSEwan Crawford       BreakOnModuleKernels(module);
35787dc7771cSEwan Crawford 
35797dc7771cSEwan Crawford     if (log)
3580b9c1b51eSKate Stone       log->Printf("%s(True) - breakpoints set on all currently loaded kernels.",
3581b9c1b51eSKate Stone                   __FUNCTION__);
3582b9c1b51eSKate Stone   } else if (!do_break &&
3583b9c1b51eSKate Stone              m_breakAllKernels) // Breakpoints won't be set on any new kernels.
35847dc7771cSEwan Crawford   {
35857dc7771cSEwan Crawford     m_breakAllKernels = false;
35867dc7771cSEwan Crawford 
35877dc7771cSEwan Crawford     if (log)
3588b9c1b51eSKate Stone       log->Printf("%s(False) - breakpoints no longer automatically set.",
3589b9c1b51eSKate Stone                   __FUNCTION__);
35907dc7771cSEwan Crawford   }
35917dc7771cSEwan Crawford }
35927dc7771cSEwan Crawford 
35937dc7771cSEwan Crawford // Given the name of a kernel this function creates a breakpoint using our
35947dc7771cSEwan Crawford // own breakpoint resolver, and returns the Breakpoint shared pointer.
35957dc7771cSEwan Crawford BreakpointSP
3596b9c1b51eSKate Stone RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) {
3597b9c1b51eSKate Stone   Log *log(
3598b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
35997dc7771cSEwan Crawford 
3600b9c1b51eSKate Stone   if (!m_filtersp) {
36017dc7771cSEwan Crawford     if (log)
3602b3f7f69dSAidan Dodds       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
36037dc7771cSEwan Crawford     return nullptr;
36047dc7771cSEwan Crawford   }
36057dc7771cSEwan Crawford 
36067dc7771cSEwan Crawford   BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3607b9c1b51eSKate Stone   BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
3608b9c1b51eSKate Stone       m_filtersp, resolver_sp, false, false, false);
36097dc7771cSEwan Crawford 
3610b9c1b51eSKate Stone   // Give RS breakpoints a specific name, so the user can manipulate them as a
3611b9c1b51eSKate Stone   // group.
361254782db7SEwan Crawford   Error err;
3613b3bbcb12SLuke Drummond   if (!bp->AddName("RenderScriptKernel", err))
3614b3bbcb12SLuke Drummond     if (log)
3615b3bbcb12SLuke Drummond       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3616b3bbcb12SLuke Drummond                   err.AsCString());
3617b3bbcb12SLuke Drummond 
3618b3bbcb12SLuke Drummond   return bp;
3619b3bbcb12SLuke Drummond }
3620b3bbcb12SLuke Drummond 
3621b3bbcb12SLuke Drummond BreakpointSP
3622b3bbcb12SLuke Drummond RenderScriptRuntime::CreateReductionBreakpoint(const ConstString &name,
3623b3bbcb12SLuke Drummond                                                int kernel_types) {
3624b3bbcb12SLuke Drummond   Log *log(
3625b3bbcb12SLuke Drummond       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3626b3bbcb12SLuke Drummond 
3627b3bbcb12SLuke Drummond   if (!m_filtersp) {
3628b3bbcb12SLuke Drummond     if (log)
3629b3bbcb12SLuke Drummond       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3630b3bbcb12SLuke Drummond     return nullptr;
3631b3bbcb12SLuke Drummond   }
3632b3bbcb12SLuke Drummond 
3633b3bbcb12SLuke Drummond   BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3634b3bbcb12SLuke Drummond       nullptr, name, &m_rsmodules, kernel_types));
3635b3bbcb12SLuke Drummond   BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
3636b3bbcb12SLuke Drummond       m_filtersp, resolver_sp, false, false, false);
3637b3bbcb12SLuke Drummond 
3638b3bbcb12SLuke Drummond   // Give RS breakpoints a specific name, so the user can manipulate them as a
3639b3bbcb12SLuke Drummond   // group.
3640b3bbcb12SLuke Drummond   Error err;
3641b3bbcb12SLuke Drummond   if (!bp->AddName("RenderScriptReduction", err))
3642b3bbcb12SLuke Drummond     if (log)
3643b9c1b51eSKate Stone       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3644b9c1b51eSKate Stone                   err.AsCString());
364554782db7SEwan Crawford 
36467dc7771cSEwan Crawford   return bp;
36477dc7771cSEwan Crawford }
36487dc7771cSEwan Crawford 
3649b9c1b51eSKate Stone // Given an expression for a variable this function tries to calculate the
365080af0b9eSLuke Drummond // variable's value. If this is possible it returns true and sets the uint64_t
365180af0b9eSLuke Drummond // parameter to the variables unsigned value. Otherwise function returns false.
3652b9c1b51eSKate Stone bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3653b9c1b51eSKate Stone                                                 const char *var_name,
3654b9c1b51eSKate Stone                                                 uint64_t &val) {
3655018f5a7eSEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
365680af0b9eSLuke Drummond   Error err;
3657018f5a7eSEwan Crawford   VariableSP var_sp;
3658018f5a7eSEwan Crawford 
3659018f5a7eSEwan Crawford   // Find variable in stack frame
3660b3f7f69dSAidan Dodds   ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3661b3f7f69dSAidan Dodds       var_name, eNoDynamicValues,
3662b9c1b51eSKate Stone       StackFrame::eExpressionPathOptionCheckPtrVsMember |
3663b9c1b51eSKate Stone           StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
366480af0b9eSLuke Drummond       var_sp, err));
366580af0b9eSLuke Drummond   if (!err.Success()) {
3666018f5a7eSEwan Crawford     if (log)
3667b9c1b51eSKate Stone       log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__,
3668b9c1b51eSKate Stone                   var_name);
3669018f5a7eSEwan Crawford     return false;
3670018f5a7eSEwan Crawford   }
3671018f5a7eSEwan Crawford 
3672b3f7f69dSAidan Dodds   // Find the uint32_t value for the variable
3673018f5a7eSEwan Crawford   bool success = false;
3674018f5a7eSEwan Crawford   val = value_sp->GetValueAsUnsigned(0, &success);
3675b9c1b51eSKate Stone   if (!success) {
3676018f5a7eSEwan Crawford     if (log)
3677b9c1b51eSKate Stone       log->Printf("%s - error, couldn't parse '%s' as an uint32_t.",
3678b9c1b51eSKate Stone                   __FUNCTION__, var_name);
3679018f5a7eSEwan Crawford     return false;
3680018f5a7eSEwan Crawford   }
3681018f5a7eSEwan Crawford 
3682018f5a7eSEwan Crawford   return true;
3683018f5a7eSEwan Crawford }
3684018f5a7eSEwan Crawford 
3685b9c1b51eSKate Stone // Function attempts to find the current coordinate of a kernel invocation by
368680af0b9eSLuke Drummond // investigating the values of frame variables in the .expand function. These
368780af0b9eSLuke Drummond // coordinates are returned via the coord array reference parameter. Returns
368880af0b9eSLuke Drummond // true if the coordinates could be found, and false otherwise.
3689b9c1b51eSKate Stone bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3690b9c1b51eSKate Stone                                               Thread *thread_ptr) {
369100f56eebSLuke Drummond   static const char *const x_expr = "rsIndex";
369200f56eebSLuke Drummond   static const char *const y_expr = "p->current.y";
369300f56eebSLuke Drummond   static const char *const z_expr = "p->current.z";
36941e05c3bcSGreg Clayton 
36954f8817c2SEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
36964f8817c2SEwan Crawford 
3697b9c1b51eSKate Stone   if (!thread_ptr) {
36984f8817c2SEwan Crawford     if (log)
36994f8817c2SEwan Crawford       log->Printf("%s - Error, No thread pointer", __FUNCTION__);
37004f8817c2SEwan Crawford 
37014f8817c2SEwan Crawford     return false;
37024f8817c2SEwan Crawford   }
37034f8817c2SEwan Crawford 
3704b9c1b51eSKate Stone   // Walk the call stack looking for a function whose name has the suffix
370580af0b9eSLuke Drummond   // '.expand' and contains the variables we're looking for.
3706b9c1b51eSKate Stone   for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
37074f8817c2SEwan Crawford     if (!thread_ptr->SetSelectedFrameByIndex(i))
37084f8817c2SEwan Crawford       continue;
37094f8817c2SEwan Crawford 
37104f8817c2SEwan Crawford     StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
37114f8817c2SEwan Crawford     if (!frame_sp)
37124f8817c2SEwan Crawford       continue;
37134f8817c2SEwan Crawford 
37144f8817c2SEwan Crawford     // Find the function name
37154f8817c2SEwan Crawford     const SymbolContext sym_ctx = frame_sp->GetSymbolContext(false);
371600f56eebSLuke Drummond     const ConstString func_name = sym_ctx.GetFunctionName();
371700f56eebSLuke Drummond     if (!func_name)
37184f8817c2SEwan Crawford       continue;
37194f8817c2SEwan Crawford 
37204f8817c2SEwan Crawford     if (log)
3721b9c1b51eSKate Stone       log->Printf("%s - Inspecting function '%s'", __FUNCTION__,
372200f56eebSLuke Drummond                   func_name.GetCString());
37234f8817c2SEwan Crawford 
37244f8817c2SEwan Crawford     // Check if function name has .expand suffix
372500f56eebSLuke Drummond     if (!func_name.GetStringRef().endswith(".expand"))
37264f8817c2SEwan Crawford       continue;
37274f8817c2SEwan Crawford 
37284f8817c2SEwan Crawford     if (log)
3729b9c1b51eSKate Stone       log->Printf("%s - Found .expand function '%s'", __FUNCTION__,
373000f56eebSLuke Drummond                   func_name.GetCString());
37314f8817c2SEwan Crawford 
3732b9c1b51eSKate Stone     // Get values for variables in .expand frame that tell us the current kernel
3733b9c1b51eSKate Stone     // invocation
373400f56eebSLuke Drummond     uint64_t x, y, z;
373500f56eebSLuke Drummond     bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
373600f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
373700f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, z_expr, z);
37384f8817c2SEwan Crawford 
373900f56eebSLuke Drummond     if (found) {
374000f56eebSLuke Drummond       // The RenderScript runtime uses uint32_t for these vars. If they're not
374100f56eebSLuke Drummond       // within bounds, our frame parsing is garbage
374200f56eebSLuke Drummond       assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
374300f56eebSLuke Drummond       coord.x = (uint32_t)x;
374400f56eebSLuke Drummond       coord.y = (uint32_t)y;
374500f56eebSLuke Drummond       coord.z = (uint32_t)z;
37464f8817c2SEwan Crawford       return true;
37474f8817c2SEwan Crawford     }
374800f56eebSLuke Drummond   }
37494f8817c2SEwan Crawford   return false;
37504f8817c2SEwan Crawford }
37514f8817c2SEwan Crawford 
3752b9c1b51eSKate Stone // Callback when a kernel breakpoint hits and we're looking for a specific
375380af0b9eSLuke Drummond // coordinate. Baton parameter contains a pointer to the target coordinate we
375480af0b9eSLuke Drummond // want to break on.
3755b9c1b51eSKate Stone // Function then checks the .expand frame for the current coordinate and breaks
3756b9c1b51eSKate Stone // to user if it matches.
3757018f5a7eSEwan Crawford // Parameter 'break_id' is the id of the Breakpoint which made the callback.
3758018f5a7eSEwan Crawford // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
3759018f5a7eSEwan Crawford // a single logical breakpoint can have multiple addresses.
3760b9c1b51eSKate Stone bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3761b9c1b51eSKate Stone                                               StoppointCallbackContext *ctx,
3762b9c1b51eSKate Stone                                               user_id_t break_id,
3763b9c1b51eSKate Stone                                               user_id_t break_loc_id) {
3764b9c1b51eSKate Stone   Log *log(
3765b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3766018f5a7eSEwan Crawford 
3767b9c1b51eSKate Stone   assert(baton &&
3768b9c1b51eSKate Stone          "Error: null baton in conditional kernel breakpoint callback");
3769018f5a7eSEwan Crawford 
3770018f5a7eSEwan Crawford   // Coordinate we want to stop on
377100f56eebSLuke Drummond   RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3772018f5a7eSEwan Crawford 
3773018f5a7eSEwan Crawford   if (log)
377400f56eebSLuke Drummond     log->Printf("%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__, break_id,
377500f56eebSLuke Drummond                 target_coord.x, target_coord.y, target_coord.z);
3776018f5a7eSEwan Crawford 
37774f8817c2SEwan Crawford   // Select current thread
3778018f5a7eSEwan Crawford   ExecutionContext context(ctx->exe_ctx_ref);
37794f8817c2SEwan Crawford   Thread *thread_ptr = context.GetThreadPtr();
37804f8817c2SEwan Crawford   assert(thread_ptr && "Null thread pointer");
37814f8817c2SEwan Crawford 
37824f8817c2SEwan Crawford   // Find current kernel invocation from .expand frame variables
378300f56eebSLuke Drummond   RSCoordinate current_coord{};
3784b9c1b51eSKate Stone   if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3785018f5a7eSEwan Crawford     if (log)
3786b9c1b51eSKate Stone       log->Printf("%s - Error, couldn't select .expand stack frame",
3787b9c1b51eSKate Stone                   __FUNCTION__);
3788018f5a7eSEwan Crawford     return false;
3789018f5a7eSEwan Crawford   }
3790018f5a7eSEwan Crawford 
3791018f5a7eSEwan Crawford   if (log)
379200f56eebSLuke Drummond     log->Printf("%s - " FMT_COORD, __FUNCTION__, current_coord.x,
379300f56eebSLuke Drummond                 current_coord.y, current_coord.z);
3794018f5a7eSEwan Crawford 
3795b9c1b51eSKate Stone   // Check if the current kernel invocation coordinate matches our target
3796b9c1b51eSKate Stone   // coordinate
379700f56eebSLuke Drummond   if (target_coord == current_coord) {
3798018f5a7eSEwan Crawford     if (log)
379900f56eebSLuke Drummond       log->Printf("%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
380000f56eebSLuke Drummond                   current_coord.y, current_coord.z);
3801018f5a7eSEwan Crawford 
3802b9c1b51eSKate Stone     BreakpointSP breakpoint_sp =
3803b9c1b51eSKate Stone         context.GetTargetPtr()->GetBreakpointByID(break_id);
3804b9c1b51eSKate Stone     assert(breakpoint_sp != nullptr &&
3805b9c1b51eSKate Stone            "Error: Couldn't find breakpoint matching break id for callback");
3806b9c1b51eSKate Stone     breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3807b9c1b51eSKate Stone                                       // should only be hit once.
3808018f5a7eSEwan Crawford     return true;
3809018f5a7eSEwan Crawford   }
3810018f5a7eSEwan Crawford 
3811018f5a7eSEwan Crawford   // No match on coordinate
3812018f5a7eSEwan Crawford   return false;
3813018f5a7eSEwan Crawford }
3814018f5a7eSEwan Crawford 
381500f56eebSLuke Drummond void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
381600f56eebSLuke Drummond                                          const RSCoordinate &coord) {
381700f56eebSLuke Drummond   messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
381800f56eebSLuke Drummond                   coord.x, coord.y, coord.z);
381900f56eebSLuke Drummond   messages.EOL();
382000f56eebSLuke Drummond 
382100f56eebSLuke Drummond   // Allocate memory for the baton, and copy over coordinate
382200f56eebSLuke Drummond   RSCoordinate *baton = new RSCoordinate(coord);
382300f56eebSLuke Drummond 
382400f56eebSLuke Drummond   // Create a callback that will be invoked every time the breakpoint is hit.
382500f56eebSLuke Drummond   // The baton object passed to the handler is the target coordinate we want to
382600f56eebSLuke Drummond   // break on.
382700f56eebSLuke Drummond   bp->SetCallback(KernelBreakpointHit, baton, true);
382800f56eebSLuke Drummond 
382900f56eebSLuke Drummond   // Store a shared pointer to the baton, so the memory will eventually be
383000f56eebSLuke Drummond   // cleaned up after destruction
383100f56eebSLuke Drummond   m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
383200f56eebSLuke Drummond }
383300f56eebSLuke Drummond 
3834b9c1b51eSKate Stone // Tries to set a breakpoint on the start of a kernel, resolved using the kernel
383580af0b9eSLuke Drummond // name. Argument 'coords', represents a three dimensional coordinate which can
383680af0b9eSLuke Drummond // be
383780af0b9eSLuke Drummond // used to specify a single kernel instance to break on. If this is set then we
383880af0b9eSLuke Drummond // add a callback
3839b9c1b51eSKate Stone // to the breakpoint.
384000f56eebSLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
384100f56eebSLuke Drummond                                                   Stream &messages,
384200f56eebSLuke Drummond                                                   const char *name,
384300f56eebSLuke Drummond                                                   const RSCoordinate *coord) {
384400f56eebSLuke Drummond   if (!name)
384500f56eebSLuke Drummond     return false;
38464640cde1SColin Riley 
38477dc7771cSEwan Crawford   InitSearchFilter(target);
384898156583SEwan Crawford 
38494640cde1SColin Riley   ConstString kernel_name(name);
38507dc7771cSEwan Crawford   BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
385100f56eebSLuke Drummond   if (!bp)
385200f56eebSLuke Drummond     return false;
3853018f5a7eSEwan Crawford 
3854018f5a7eSEwan Crawford   // We have a conditional breakpoint on a specific coordinate
385500f56eebSLuke Drummond   if (coord)
385600f56eebSLuke Drummond     SetConditional(bp, messages, *coord);
3857018f5a7eSEwan Crawford 
385800f56eebSLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3859018f5a7eSEwan Crawford 
386000f56eebSLuke Drummond   return true;
38614640cde1SColin Riley }
38624640cde1SColin Riley 
386321fed052SAidan Dodds BreakpointSP
386421fed052SAidan Dodds RenderScriptRuntime::CreateScriptGroupBreakpoint(const ConstString &name,
386521fed052SAidan Dodds                                                  bool stop_on_all) {
386621fed052SAidan Dodds   Log *log(
386721fed052SAidan Dodds       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
386821fed052SAidan Dodds 
386921fed052SAidan Dodds   if (!m_filtersp) {
387021fed052SAidan Dodds     if (log)
387121fed052SAidan Dodds       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
387221fed052SAidan Dodds     return nullptr;
387321fed052SAidan Dodds   }
387421fed052SAidan Dodds 
387521fed052SAidan Dodds   BreakpointResolverSP resolver_sp(new RSScriptGroupBreakpointResolver(
387621fed052SAidan Dodds       nullptr, name, m_scriptGroups, stop_on_all));
387721fed052SAidan Dodds   BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
387821fed052SAidan Dodds       m_filtersp, resolver_sp, false, false, false);
387921fed052SAidan Dodds   // Give RS breakpoints a specific name, so the user can manipulate them as a
388021fed052SAidan Dodds   // group.
388121fed052SAidan Dodds   Error err;
388221fed052SAidan Dodds   if (!bp->AddName(name.AsCString(), err))
388321fed052SAidan Dodds     if (log)
388421fed052SAidan Dodds       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
388521fed052SAidan Dodds                   err.AsCString());
388621fed052SAidan Dodds   // ask the breakpoint to resolve itself
388721fed052SAidan Dodds   bp->ResolveBreakpoint();
388821fed052SAidan Dodds   return bp;
388921fed052SAidan Dodds }
389021fed052SAidan Dodds 
389121fed052SAidan Dodds bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target,
389221fed052SAidan Dodds                                                        Stream &strm,
389321fed052SAidan Dodds                                                        const ConstString &name,
389421fed052SAidan Dodds                                                        bool multi) {
389521fed052SAidan Dodds   InitSearchFilter(target);
389621fed052SAidan Dodds   BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi);
389721fed052SAidan Dodds   if (bp)
389821fed052SAidan Dodds     bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
389921fed052SAidan Dodds   return bool(bp);
390021fed052SAidan Dodds }
390121fed052SAidan Dodds 
3902b3bbcb12SLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3903b3bbcb12SLuke Drummond                                                      Stream &messages,
3904b3bbcb12SLuke Drummond                                                      const char *reduce_name,
3905b3bbcb12SLuke Drummond                                                      const RSCoordinate *coord,
3906b3bbcb12SLuke Drummond                                                      int kernel_types) {
3907b3bbcb12SLuke Drummond   if (!reduce_name)
3908b3bbcb12SLuke Drummond     return false;
3909b3bbcb12SLuke Drummond 
3910b3bbcb12SLuke Drummond   InitSearchFilter(target);
3911b3bbcb12SLuke Drummond   BreakpointSP bp =
3912b3bbcb12SLuke Drummond       CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3913b3bbcb12SLuke Drummond   if (!bp)
3914b3bbcb12SLuke Drummond     return false;
3915b3bbcb12SLuke Drummond 
3916b3bbcb12SLuke Drummond   if (coord)
3917b3bbcb12SLuke Drummond     SetConditional(bp, messages, *coord);
3918b3bbcb12SLuke Drummond 
3919b3bbcb12SLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3920b3bbcb12SLuke Drummond 
3921b3bbcb12SLuke Drummond   return true;
3922b3bbcb12SLuke Drummond }
3923b3bbcb12SLuke Drummond 
3924b9c1b51eSKate Stone void RenderScriptRuntime::DumpModules(Stream &strm) const {
39255ec532a9SColin Riley   strm.Printf("RenderScript Modules:");
39265ec532a9SColin Riley   strm.EOL();
39275ec532a9SColin Riley   strm.IndentMore();
3928b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
39294640cde1SColin Riley     module->Dump(strm);
39305ec532a9SColin Riley   }
39315ec532a9SColin Riley   strm.IndentLess();
39325ec532a9SColin Riley }
39335ec532a9SColin Riley 
393478f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails *
3935b9c1b51eSKate Stone RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3936b9c1b51eSKate Stone   for (const auto &s : m_scripts) {
393778f339d1SEwan Crawford     if (s->script.isValid())
393878f339d1SEwan Crawford       if (*s->script == address)
393978f339d1SEwan Crawford         return s.get();
394078f339d1SEwan Crawford   }
3941b9c1b51eSKate Stone   if (create) {
394278f339d1SEwan Crawford     std::unique_ptr<ScriptDetails> s(new ScriptDetails);
394378f339d1SEwan Crawford     s->script = address;
394478f339d1SEwan Crawford     m_scripts.push_back(std::move(s));
3945d10ca9deSEwan Crawford     return m_scripts.back().get();
394678f339d1SEwan Crawford   }
394778f339d1SEwan Crawford   return nullptr;
394878f339d1SEwan Crawford }
394978f339d1SEwan Crawford 
395078f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails *
3951b9c1b51eSKate Stone RenderScriptRuntime::LookUpAllocation(addr_t address) {
3952b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
395378f339d1SEwan Crawford     if (a->address.isValid())
395478f339d1SEwan Crawford       if (*a->address == address)
395578f339d1SEwan Crawford         return a.get();
395678f339d1SEwan Crawford   }
39575d057637SLuke Drummond   return nullptr;
39585d057637SLuke Drummond }
39595d057637SLuke Drummond 
39605d057637SLuke Drummond RenderScriptRuntime::AllocationDetails *
3961b9c1b51eSKate Stone RenderScriptRuntime::CreateAllocation(addr_t address) {
39625d057637SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
39635d057637SLuke Drummond 
39645d057637SLuke Drummond   // Remove any previous allocation which contains the same address
39655d057637SLuke Drummond   auto it = m_allocations.begin();
3966b9c1b51eSKate Stone   while (it != m_allocations.end()) {
3967b9c1b51eSKate Stone     if (*((*it)->address) == address) {
39685d057637SLuke Drummond       if (log)
3969b9c1b51eSKate Stone         log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64,
3970b9c1b51eSKate Stone                     __FUNCTION__, (*it)->id, address);
39715d057637SLuke Drummond 
39725d057637SLuke Drummond       it = m_allocations.erase(it);
3973b9c1b51eSKate Stone     } else {
39745d057637SLuke Drummond       it++;
39755d057637SLuke Drummond     }
39765d057637SLuke Drummond   }
39775d057637SLuke Drummond 
397878f339d1SEwan Crawford   std::unique_ptr<AllocationDetails> a(new AllocationDetails);
397978f339d1SEwan Crawford   a->address = address;
398078f339d1SEwan Crawford   m_allocations.push_back(std::move(a));
3981d10ca9deSEwan Crawford   return m_allocations.back().get();
398278f339d1SEwan Crawford }
398378f339d1SEwan Crawford 
398421fed052SAidan Dodds bool RenderScriptRuntime::ResolveKernelName(lldb::addr_t kernel_addr,
398521fed052SAidan Dodds                                             ConstString &name) {
398621fed052SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
398721fed052SAidan Dodds 
398821fed052SAidan Dodds   Target &target = GetProcess()->GetTarget();
398921fed052SAidan Dodds   Address resolved;
399021fed052SAidan Dodds   // RenderScript module
399121fed052SAidan Dodds   if (!target.GetSectionLoadList().ResolveLoadAddress(kernel_addr, resolved)) {
399221fed052SAidan Dodds     if (log)
399321fed052SAidan Dodds       log->Printf("%s: unable to resolve 0x%" PRIx64 " to a loaded symbol",
399421fed052SAidan Dodds                   __FUNCTION__, kernel_addr);
399521fed052SAidan Dodds     return false;
399621fed052SAidan Dodds   }
399721fed052SAidan Dodds 
399821fed052SAidan Dodds   Symbol *sym = resolved.CalculateSymbolContextSymbol();
399921fed052SAidan Dodds   if (!sym)
400021fed052SAidan Dodds     return false;
400121fed052SAidan Dodds 
400221fed052SAidan Dodds   name = sym->GetName();
400321fed052SAidan Dodds   assert(IsRenderScriptModule(resolved.CalculateSymbolContextModule()));
400421fed052SAidan Dodds   if (log)
400521fed052SAidan Dodds     log->Printf("%s: 0x%" PRIx64 " resolved to the symbol '%s'", __FUNCTION__,
400621fed052SAidan Dodds                 kernel_addr, name.GetCString());
400721fed052SAidan Dodds   return true;
400821fed052SAidan Dodds }
400921fed052SAidan Dodds 
4010b9c1b51eSKate Stone void RSModuleDescriptor::Dump(Stream &strm) const {
40117f193d69SLuke Drummond   int indent = strm.GetIndentLevel();
40127f193d69SLuke Drummond 
40135ec532a9SColin Riley   strm.Indent();
40145ec532a9SColin Riley   m_module->GetFileSpec().Dump(&strm);
40157f193d69SLuke Drummond   strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
40167f193d69SLuke Drummond                                              : "Debug info does not exist.");
40175ec532a9SColin Riley   strm.EOL();
40185ec532a9SColin Riley   strm.IndentMore();
40197f193d69SLuke Drummond 
40205ec532a9SColin Riley   strm.Indent();
4021189598edSColin Riley   strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
40225ec532a9SColin Riley   strm.EOL();
40235ec532a9SColin Riley   strm.IndentMore();
4024b9c1b51eSKate Stone   for (const auto &global : m_globals) {
40255ec532a9SColin Riley     global.Dump(strm);
40265ec532a9SColin Riley   }
40275ec532a9SColin Riley   strm.IndentLess();
40287f193d69SLuke Drummond 
40295ec532a9SColin Riley   strm.Indent();
4030189598edSColin Riley   strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
40315ec532a9SColin Riley   strm.EOL();
40325ec532a9SColin Riley   strm.IndentMore();
4033b9c1b51eSKate Stone   for (const auto &kernel : m_kernels) {
40345ec532a9SColin Riley     kernel.Dump(strm);
40355ec532a9SColin Riley   }
40367f193d69SLuke Drummond   strm.IndentLess();
40377f193d69SLuke Drummond 
40387f193d69SLuke Drummond   strm.Indent();
40394640cde1SColin Riley   strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
40404640cde1SColin Riley   strm.EOL();
40414640cde1SColin Riley   strm.IndentMore();
4042b9c1b51eSKate Stone   for (const auto &key_val : m_pragmas) {
40437f193d69SLuke Drummond     strm.Indent();
40444640cde1SColin Riley     strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
40454640cde1SColin Riley     strm.EOL();
40464640cde1SColin Riley   }
40477f193d69SLuke Drummond   strm.IndentLess();
40487f193d69SLuke Drummond 
40497f193d69SLuke Drummond   strm.Indent();
40507f193d69SLuke Drummond   strm.Printf("Reductions: %" PRIu64,
40517f193d69SLuke Drummond               static_cast<uint64_t>(m_reductions.size()));
40527f193d69SLuke Drummond   strm.EOL();
40537f193d69SLuke Drummond   strm.IndentMore();
40547f193d69SLuke Drummond   for (const auto &reduction : m_reductions) {
40557f193d69SLuke Drummond     reduction.Dump(strm);
40567f193d69SLuke Drummond   }
40577f193d69SLuke Drummond 
40587f193d69SLuke Drummond   strm.SetIndentLevel(indent);
40595ec532a9SColin Riley }
40605ec532a9SColin Riley 
4061b9c1b51eSKate Stone void RSGlobalDescriptor::Dump(Stream &strm) const {
40625ec532a9SColin Riley   strm.Indent(m_name.AsCString());
40634640cde1SColin Riley   VariableList var_list;
40644640cde1SColin Riley   m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
4065b9c1b51eSKate Stone   if (var_list.GetSize() == 1) {
40664640cde1SColin Riley     auto var = var_list.GetVariableAtIndex(0);
40674640cde1SColin Riley     auto type = var->GetType();
4068b9c1b51eSKate Stone     if (type) {
40694640cde1SColin Riley       strm.Printf(" - ");
40704640cde1SColin Riley       type->DumpTypeName(&strm);
4071b9c1b51eSKate Stone     } else {
40724640cde1SColin Riley       strm.Printf(" - Unknown Type");
40734640cde1SColin Riley     }
4074b9c1b51eSKate Stone   } else {
40754640cde1SColin Riley     strm.Printf(" - variable identified, but not found in binary");
4076b9c1b51eSKate Stone     const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
4077b9c1b51eSKate Stone         m_name, eSymbolTypeData);
4078b9c1b51eSKate Stone     if (s) {
40794640cde1SColin Riley       strm.Printf(" (symbol exists) ");
40804640cde1SColin Riley     }
40814640cde1SColin Riley   }
40824640cde1SColin Riley 
40835ec532a9SColin Riley   strm.EOL();
40845ec532a9SColin Riley }
40855ec532a9SColin Riley 
4086b9c1b51eSKate Stone void RSKernelDescriptor::Dump(Stream &strm) const {
40875ec532a9SColin Riley   strm.Indent(m_name.AsCString());
40885ec532a9SColin Riley   strm.EOL();
40895ec532a9SColin Riley }
40905ec532a9SColin Riley 
40917f193d69SLuke Drummond void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
40927f193d69SLuke Drummond   stream.Indent(m_reduce_name.AsCString());
40937f193d69SLuke Drummond   stream.IndentMore();
40947f193d69SLuke Drummond   stream.EOL();
40957f193d69SLuke Drummond   stream.Indent();
40967f193d69SLuke Drummond   stream.Printf("accumulator: %s", m_accum_name.AsCString());
40977f193d69SLuke Drummond   stream.EOL();
40987f193d69SLuke Drummond   stream.Indent();
40997f193d69SLuke Drummond   stream.Printf("initializer: %s", m_init_name.AsCString());
41007f193d69SLuke Drummond   stream.EOL();
41017f193d69SLuke Drummond   stream.Indent();
41027f193d69SLuke Drummond   stream.Printf("combiner: %s", m_comb_name.AsCString());
41037f193d69SLuke Drummond   stream.EOL();
41047f193d69SLuke Drummond   stream.Indent();
41057f193d69SLuke Drummond   stream.Printf("outconverter: %s", m_outc_name.AsCString());
41067f193d69SLuke Drummond   stream.EOL();
41077f193d69SLuke Drummond   // XXX This is currently unspecified by RenderScript, and unused
41087f193d69SLuke Drummond   // stream.Indent();
41097f193d69SLuke Drummond   // stream.Printf("halter: '%s'", m_init_name.AsCString());
41107f193d69SLuke Drummond   // stream.EOL();
41117f193d69SLuke Drummond   stream.IndentLess();
41127f193d69SLuke Drummond }
41137f193d69SLuke Drummond 
4114b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
41155ec532a9SColin Riley public:
41165ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
4117b9c1b51eSKate Stone       : CommandObjectParsed(
4118b9c1b51eSKate Stone             interpreter, "renderscript module dump",
4119b9c1b51eSKate Stone             "Dumps renderscript specific information for all modules.",
4120b9c1b51eSKate Stone             "renderscript module dump",
4121b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
41225ec532a9SColin Riley 
4123222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
41245ec532a9SColin Riley 
4125b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
41265ec532a9SColin Riley     RenderScriptRuntime *runtime =
4127b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4128b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
41295ec532a9SColin Riley     runtime->DumpModules(result.GetOutputStream());
41305ec532a9SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
41315ec532a9SColin Riley     return true;
41325ec532a9SColin Riley   }
41335ec532a9SColin Riley };
41345ec532a9SColin Riley 
4135b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
41365ec532a9SColin Riley public:
41375ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
4138b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript module",
4139b9c1b51eSKate Stone                                "Commands that deal with RenderScript modules.",
4140b9c1b51eSKate Stone                                nullptr) {
4141b9c1b51eSKate Stone     LoadSubCommand(
4142b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
4143b9c1b51eSKate Stone                     interpreter)));
41445ec532a9SColin Riley   }
41455ec532a9SColin Riley 
4146222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModule() override = default;
41475ec532a9SColin Riley };
41485ec532a9SColin Riley 
4149b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
41504640cde1SColin Riley public:
41514640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
4152b9c1b51eSKate Stone       : CommandObjectParsed(
4153b9c1b51eSKate Stone             interpreter, "renderscript kernel list",
4154b3f7f69dSAidan Dodds             "Lists renderscript kernel names and associated script resources.",
4155b9c1b51eSKate Stone             "renderscript kernel list",
4156b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
41574640cde1SColin Riley 
4158222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelList() override = default;
41594640cde1SColin Riley 
4160b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
41614640cde1SColin Riley     RenderScriptRuntime *runtime =
4162b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4163b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
41644640cde1SColin Riley     runtime->DumpKernels(result.GetOutputStream());
41654640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
41664640cde1SColin Riley     return true;
41674640cde1SColin Riley   }
41684640cde1SColin Riley };
41694640cde1SColin Riley 
4170b3bbcb12SLuke Drummond static OptionDefinition g_renderscript_reduction_bp_set_options[] = {
4171b3bbcb12SLuke Drummond     {LLDB_OPT_SET_1, false, "function-role", 't',
4172b3bbcb12SLuke Drummond      OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOneLiner,
4173b3bbcb12SLuke Drummond      "Break on a comma separated set of reduction kernel types "
4174b3bbcb12SLuke Drummond      "(accumulator,outcoverter,combiner,initializer"},
4175b3bbcb12SLuke Drummond     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4176b3bbcb12SLuke Drummond      nullptr, nullptr, 0, eArgTypeValue,
4177b3bbcb12SLuke Drummond      "Set a breakpoint on a single invocation of the kernel with specified "
4178b3bbcb12SLuke Drummond      "coordinate.\n"
4179b3bbcb12SLuke Drummond      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4180b3bbcb12SLuke Drummond      "integers representing kernel dimensions. "
4181b3bbcb12SLuke Drummond      "Any unset dimensions will be defaulted to zero."}};
4182b3bbcb12SLuke Drummond 
4183b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReductionBreakpointSet
4184b3bbcb12SLuke Drummond     : public CommandObjectParsed {
4185b3bbcb12SLuke Drummond public:
4186b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4187b3bbcb12SLuke Drummond       CommandInterpreter &interpreter)
4188b3bbcb12SLuke Drummond       : CommandObjectParsed(
4189b3bbcb12SLuke Drummond             interpreter, "renderscript reduction breakpoint set",
4190b3bbcb12SLuke Drummond             "Set a breakpoint on named RenderScript general reductions",
4191b3bbcb12SLuke Drummond             "renderscript reduction breakpoint set  <kernel_name> [-t "
4192b3bbcb12SLuke Drummond             "<reduction_kernel_type,...>]",
4193b3bbcb12SLuke Drummond             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4194b3bbcb12SLuke Drummond                 eCommandProcessMustBePaused),
4195b3bbcb12SLuke Drummond         m_options(){};
4196b3bbcb12SLuke Drummond 
4197b3bbcb12SLuke Drummond   class CommandOptions : public Options {
4198b3bbcb12SLuke Drummond   public:
4199b3bbcb12SLuke Drummond     CommandOptions()
4200b3bbcb12SLuke Drummond         : Options(),
4201b3bbcb12SLuke Drummond           m_kernel_types(RSReduceBreakpointResolver::eKernelTypeAll) {}
4202b3bbcb12SLuke Drummond 
4203b3bbcb12SLuke Drummond     ~CommandOptions() override = default;
4204b3bbcb12SLuke Drummond 
4205fe11483bSZachary Turner     Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4206b3bbcb12SLuke Drummond                          ExecutionContext *exe_ctx) override {
4207b3bbcb12SLuke Drummond       Error err;
4208b3bbcb12SLuke Drummond       StreamString err_str;
4209b3bbcb12SLuke Drummond       const int short_option = m_getopt_table[option_idx].val;
4210b3bbcb12SLuke Drummond       switch (short_option) {
4211b3bbcb12SLuke Drummond       case 't':
4212fe11483bSZachary Turner         if (!ParseReductionTypes(option_arg, err_str))
4213b3bbcb12SLuke Drummond           err.SetErrorStringWithFormat(
4214fe11483bSZachary Turner               "Unable to deduce reduction types for %s: %s",
4215fe11483bSZachary Turner               option_arg.str().c_str(), err_str.GetData());
4216b3bbcb12SLuke Drummond         break;
4217b3bbcb12SLuke Drummond       case 'c': {
4218b3bbcb12SLuke Drummond         auto coord = RSCoordinate{};
4219fe11483bSZachary Turner         if (!ParseCoordinate(option_arg, coord))
4220b3bbcb12SLuke Drummond           err.SetErrorStringWithFormat("unable to parse coordinate for %s",
4221fe11483bSZachary Turner                                        option_arg.str().c_str());
4222b3bbcb12SLuke Drummond         else {
4223b3bbcb12SLuke Drummond           m_have_coord = true;
4224b3bbcb12SLuke Drummond           m_coord = coord;
4225b3bbcb12SLuke Drummond         }
4226b3bbcb12SLuke Drummond         break;
4227b3bbcb12SLuke Drummond       }
4228b3bbcb12SLuke Drummond       default:
4229b3bbcb12SLuke Drummond         err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
4230b3bbcb12SLuke Drummond       }
4231b3bbcb12SLuke Drummond       return err;
4232b3bbcb12SLuke Drummond     }
4233b3bbcb12SLuke Drummond 
4234b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4235b3bbcb12SLuke Drummond       m_have_coord = false;
4236b3bbcb12SLuke Drummond     }
4237b3bbcb12SLuke Drummond 
4238b3bbcb12SLuke Drummond     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4239b3bbcb12SLuke Drummond       return llvm::makeArrayRef(g_renderscript_reduction_bp_set_options);
4240b3bbcb12SLuke Drummond     }
4241b3bbcb12SLuke Drummond 
4242fe11483bSZachary Turner     bool ParseReductionTypes(llvm::StringRef option_val,
4243fe11483bSZachary Turner                              StreamString &err_str) {
4244b3bbcb12SLuke Drummond       m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
4245b3bbcb12SLuke Drummond       const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
4246b3bbcb12SLuke Drummond         return llvm::StringSwitch<int>(name)
4247b3bbcb12SLuke Drummond             .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
4248b3bbcb12SLuke Drummond             .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
4249b3bbcb12SLuke Drummond             .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
4250b3bbcb12SLuke Drummond             .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
4251b3bbcb12SLuke Drummond             .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
4252b3bbcb12SLuke Drummond             // Currently not exposed by the runtime
4253b3bbcb12SLuke Drummond             // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
4254b3bbcb12SLuke Drummond             .Default(0);
4255b3bbcb12SLuke Drummond       };
4256b3bbcb12SLuke Drummond 
4257b3bbcb12SLuke Drummond       // Matching a comma separated list of known words is fairly
4258b3bbcb12SLuke Drummond       // straightforward with PCRE, but we're
4259b3bbcb12SLuke Drummond       // using ERE, so we end up with a little ugliness...
4260b3bbcb12SLuke Drummond       RegularExpression::Match match(/* max_matches */ 5);
4261b3bbcb12SLuke Drummond       RegularExpression match_type_list(
4262b3bbcb12SLuke Drummond           llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
4263b3bbcb12SLuke Drummond 
4264b3bbcb12SLuke Drummond       assert(match_type_list.IsValid());
4265b3bbcb12SLuke Drummond 
4266fe11483bSZachary Turner       if (!match_type_list.Execute(option_val, &match)) {
4267b3bbcb12SLuke Drummond         err_str.PutCString(
4268b3bbcb12SLuke Drummond             "a comma-separated list of kernel types is required");
4269b3bbcb12SLuke Drummond         return false;
4270b3bbcb12SLuke Drummond       }
4271b3bbcb12SLuke Drummond 
4272b3bbcb12SLuke Drummond       // splitting on commas is much easier with llvm::StringRef than regex
4273b3bbcb12SLuke Drummond       llvm::SmallVector<llvm::StringRef, 5> type_names;
4274b3bbcb12SLuke Drummond       llvm::StringRef(option_val).split(type_names, ',');
4275b3bbcb12SLuke Drummond 
4276b3bbcb12SLuke Drummond       for (const auto &name : type_names) {
4277b3bbcb12SLuke Drummond         const int type = reduce_name_to_type(name);
4278b3bbcb12SLuke Drummond         if (!type) {
4279b3bbcb12SLuke Drummond           err_str.Printf("unknown kernel type name %s", name.str().c_str());
4280b3bbcb12SLuke Drummond           return false;
4281b3bbcb12SLuke Drummond         }
4282b3bbcb12SLuke Drummond         m_kernel_types |= type;
4283b3bbcb12SLuke Drummond       }
4284b3bbcb12SLuke Drummond 
4285b3bbcb12SLuke Drummond       return true;
4286b3bbcb12SLuke Drummond     }
4287b3bbcb12SLuke Drummond 
4288b3bbcb12SLuke Drummond     int m_kernel_types;
4289b3bbcb12SLuke Drummond     llvm::StringRef m_reduce_name;
4290b3bbcb12SLuke Drummond     RSCoordinate m_coord;
4291b3bbcb12SLuke Drummond     bool m_have_coord;
4292b3bbcb12SLuke Drummond   };
4293b3bbcb12SLuke Drummond 
4294b3bbcb12SLuke Drummond   Options *GetOptions() override { return &m_options; }
4295b3bbcb12SLuke Drummond 
4296b3bbcb12SLuke Drummond   bool DoExecute(Args &command, CommandReturnObject &result) override {
4297b3bbcb12SLuke Drummond     const size_t argc = command.GetArgumentCount();
4298b3bbcb12SLuke Drummond     if (argc < 1) {
4299b3bbcb12SLuke Drummond       result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
4300b3bbcb12SLuke Drummond                                    "and an optional kernel type list",
4301b3bbcb12SLuke Drummond                                    m_cmd_name.c_str());
4302b3bbcb12SLuke Drummond       result.SetStatus(eReturnStatusFailed);
4303b3bbcb12SLuke Drummond       return false;
4304b3bbcb12SLuke Drummond     }
4305b3bbcb12SLuke Drummond 
4306b3bbcb12SLuke Drummond     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4307b3bbcb12SLuke Drummond         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4308b3bbcb12SLuke Drummond             eLanguageTypeExtRenderScript));
4309b3bbcb12SLuke Drummond 
4310b3bbcb12SLuke Drummond     auto &outstream = result.GetOutputStream();
4311b3bbcb12SLuke Drummond     auto name = command.GetArgumentAtIndex(0);
4312b3bbcb12SLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
4313b3bbcb12SLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4314b3bbcb12SLuke Drummond     if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
4315b3bbcb12SLuke Drummond                                              m_options.m_kernel_types)) {
4316b3bbcb12SLuke Drummond       result.SetStatus(eReturnStatusFailed);
4317b3bbcb12SLuke Drummond       result.AppendError("Error: unable to place breakpoint on reduction");
4318b3bbcb12SLuke Drummond       return false;
4319b3bbcb12SLuke Drummond     }
4320b3bbcb12SLuke Drummond     result.AppendMessage("Breakpoint(s) created");
4321b3bbcb12SLuke Drummond     result.SetStatus(eReturnStatusSuccessFinishResult);
4322b3bbcb12SLuke Drummond     return true;
4323b3bbcb12SLuke Drummond   }
4324b3bbcb12SLuke Drummond 
4325b3bbcb12SLuke Drummond private:
4326b3bbcb12SLuke Drummond   CommandOptions m_options;
4327b3bbcb12SLuke Drummond };
4328b3bbcb12SLuke Drummond 
43291f0f5b5bSZachary Turner static OptionDefinition g_renderscript_kernel_bp_set_options[] = {
43301f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
43311f0f5b5bSZachary Turner      nullptr, nullptr, 0, eArgTypeValue,
43321f0f5b5bSZachary Turner      "Set a breakpoint on a single invocation of the kernel with specified "
43331f0f5b5bSZachary Turner      "coordinate.\n"
43341f0f5b5bSZachary Turner      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
43351f0f5b5bSZachary Turner      "integers representing kernel dimensions. "
43361f0f5b5bSZachary Turner      "Any unset dimensions will be defaulted to zero."}};
43371f0f5b5bSZachary Turner 
4338b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointSet
4339b9c1b51eSKate Stone     : public CommandObjectParsed {
43404640cde1SColin Riley public:
4341b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4342b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4343b9c1b51eSKate Stone       : CommandObjectParsed(
4344b9c1b51eSKate Stone             interpreter, "renderscript kernel breakpoint set",
4345b3f7f69dSAidan Dodds             "Sets a breakpoint on a renderscript kernel.",
4346b3f7f69dSAidan Dodds             "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
4347b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4348b9c1b51eSKate Stone                 eCommandProcessMustBePaused),
4349b9c1b51eSKate Stone         m_options() {}
43504640cde1SColin Riley 
4351222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
4352222b937cSEugene Zelenko 
4353b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
4354018f5a7eSEwan Crawford 
4355b9c1b51eSKate Stone   class CommandOptions : public Options {
4356018f5a7eSEwan Crawford   public:
4357e1cfbc79STodd Fiala     CommandOptions() : Options() {}
4358018f5a7eSEwan Crawford 
4359222b937cSEugene Zelenko     ~CommandOptions() override = default;
4360018f5a7eSEwan Crawford 
4361fe11483bSZachary Turner     Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4362b3bbcb12SLuke Drummond                          ExecutionContext *exe_ctx) override {
436380af0b9eSLuke Drummond       Error err;
4364018f5a7eSEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
4365018f5a7eSEwan Crawford 
4366b9c1b51eSKate Stone       switch (short_option) {
436700f56eebSLuke Drummond       case 'c': {
436800f56eebSLuke Drummond         auto coord = RSCoordinate{};
436900f56eebSLuke Drummond         if (!ParseCoordinate(option_arg, coord))
437080af0b9eSLuke Drummond           err.SetErrorStringWithFormat(
4371b9c1b51eSKate Stone               "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
4372fe11483bSZachary Turner               option_arg.str().c_str());
437300f56eebSLuke Drummond         else {
437400f56eebSLuke Drummond           m_have_coord = true;
437500f56eebSLuke Drummond           m_coord = coord;
437600f56eebSLuke Drummond         }
4377018f5a7eSEwan Crawford         break;
437800f56eebSLuke Drummond       }
4379018f5a7eSEwan Crawford       default:
438080af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4381018f5a7eSEwan Crawford         break;
4382018f5a7eSEwan Crawford       }
438380af0b9eSLuke Drummond       return err;
4384018f5a7eSEwan Crawford     }
4385018f5a7eSEwan Crawford 
4386b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
438700f56eebSLuke Drummond       m_have_coord = false;
4388018f5a7eSEwan Crawford     }
4389018f5a7eSEwan Crawford 
43901f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
439170602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
43921f0f5b5bSZachary Turner     }
4393018f5a7eSEwan Crawford 
439400f56eebSLuke Drummond     RSCoordinate m_coord;
439500f56eebSLuke Drummond     bool m_have_coord;
4396018f5a7eSEwan Crawford   };
4397018f5a7eSEwan Crawford 
4398b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
43994640cde1SColin Riley     const size_t argc = command.GetArgumentCount();
4400b9c1b51eSKate Stone     if (argc < 1) {
4401b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4402b9c1b51eSKate Stone           "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4403b3f7f69dSAidan Dodds           m_cmd_name.c_str());
4404018f5a7eSEwan Crawford       result.SetStatus(eReturnStatusFailed);
4405018f5a7eSEwan Crawford       return false;
4406018f5a7eSEwan Crawford     }
4407018f5a7eSEwan Crawford 
44084640cde1SColin Riley     RenderScriptRuntime *runtime =
4409b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4410b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
44114640cde1SColin Riley 
441200f56eebSLuke Drummond     auto &outstream = result.GetOutputStream();
441300f56eebSLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
441400f56eebSLuke Drummond     auto name = command.GetArgumentAtIndex(0);
441500f56eebSLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
441600f56eebSLuke Drummond     if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
441700f56eebSLuke Drummond       result.SetStatus(eReturnStatusFailed);
441800f56eebSLuke Drummond       result.AppendErrorWithFormat(
441900f56eebSLuke Drummond           "Error: unable to set breakpoint on kernel '%s'", name);
442000f56eebSLuke Drummond       return false;
442100f56eebSLuke Drummond     }
44224640cde1SColin Riley 
44234640cde1SColin Riley     result.AppendMessage("Breakpoint(s) created");
44244640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
44254640cde1SColin Riley     return true;
44264640cde1SColin Riley   }
44274640cde1SColin Riley 
4428018f5a7eSEwan Crawford private:
4429018f5a7eSEwan Crawford   CommandOptions m_options;
44304640cde1SColin Riley };
44314640cde1SColin Riley 
4432b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4433b9c1b51eSKate Stone     : public CommandObjectParsed {
44347dc7771cSEwan Crawford public:
4435b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4436b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4437b3f7f69dSAidan Dodds       : CommandObjectParsed(
4438b3f7f69dSAidan Dodds             interpreter, "renderscript kernel breakpoint all",
4439b9c1b51eSKate Stone             "Automatically sets a breakpoint on all renderscript kernels that "
4440b9c1b51eSKate Stone             "are or will be loaded.\n"
4441b9c1b51eSKate Stone             "Disabling option means breakpoints will no longer be set on any "
4442b9c1b51eSKate Stone             "kernels loaded in the future, "
44437dc7771cSEwan Crawford             "but does not remove currently set breakpoints.",
44447dc7771cSEwan Crawford             "renderscript kernel breakpoint all <enable/disable>",
4445b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4446b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
44477dc7771cSEwan Crawford 
4448222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
44497dc7771cSEwan Crawford 
4450b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
44517dc7771cSEwan Crawford     const size_t argc = command.GetArgumentCount();
4452b9c1b51eSKate Stone     if (argc != 1) {
4453b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4454b9c1b51eSKate Stone           "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
44557dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
44567dc7771cSEwan Crawford       return false;
44577dc7771cSEwan Crawford     }
44587dc7771cSEwan Crawford 
4459b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4460b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4461b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
44627dc7771cSEwan Crawford 
44637dc7771cSEwan Crawford     bool do_break = false;
44647dc7771cSEwan Crawford     const char *argument = command.GetArgumentAtIndex(0);
4465b9c1b51eSKate Stone     if (strcmp(argument, "enable") == 0) {
44667dc7771cSEwan Crawford       do_break = true;
44677dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will be set on all kernels.");
4468b9c1b51eSKate Stone     } else if (strcmp(argument, "disable") == 0) {
44697dc7771cSEwan Crawford       do_break = false;
44707dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will not be set on any new kernels.");
4471b9c1b51eSKate Stone     } else {
4472b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4473b9c1b51eSKate Stone           "Argument must be either 'enable' or 'disable'");
44747dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
44757dc7771cSEwan Crawford       return false;
44767dc7771cSEwan Crawford     }
44777dc7771cSEwan Crawford 
44787dc7771cSEwan Crawford     runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
44797dc7771cSEwan Crawford 
44807dc7771cSEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
44817dc7771cSEwan Crawford     return true;
44827dc7771cSEwan Crawford   }
44837dc7771cSEwan Crawford };
44847dc7771cSEwan Crawford 
4485b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReductionBreakpoint
4486b3bbcb12SLuke Drummond     : public CommandObjectMultiword {
4487b3bbcb12SLuke Drummond public:
4488b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReductionBreakpoint(
4489b3bbcb12SLuke Drummond       CommandInterpreter &interpreter)
4490b3bbcb12SLuke Drummond       : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4491b3bbcb12SLuke Drummond                                "Commands that manipulate breakpoints on "
4492b3bbcb12SLuke Drummond                                "renderscript general reductions.",
4493b3bbcb12SLuke Drummond                                nullptr) {
4494b3bbcb12SLuke Drummond     LoadSubCommand(
4495b3bbcb12SLuke Drummond         "set", CommandObjectSP(
4496b3bbcb12SLuke Drummond                    new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4497b3bbcb12SLuke Drummond                        interpreter)));
4498b3bbcb12SLuke Drummond   }
4499b3bbcb12SLuke Drummond 
4500b3bbcb12SLuke Drummond   ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4501b3bbcb12SLuke Drummond };
4502b3bbcb12SLuke Drummond 
4503b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelCoordinate
4504b9c1b51eSKate Stone     : public CommandObjectParsed {
45054f8817c2SEwan Crawford public:
4506b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelCoordinate(
4507b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4508b9c1b51eSKate Stone       : CommandObjectParsed(
4509b9c1b51eSKate Stone             interpreter, "renderscript kernel coordinate",
45104f8817c2SEwan Crawford             "Shows the (x,y,z) coordinate of the current kernel invocation.",
45114f8817c2SEwan Crawford             "renderscript kernel coordinate",
4512b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4513b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
45144f8817c2SEwan Crawford 
45154f8817c2SEwan Crawford   ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
45164f8817c2SEwan Crawford 
4517b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
451800f56eebSLuke Drummond     RSCoordinate coord{};
4519b9c1b51eSKate Stone     bool success = RenderScriptRuntime::GetKernelCoordinate(
4520b9c1b51eSKate Stone         coord, m_exe_ctx.GetThreadPtr());
45214f8817c2SEwan Crawford     Stream &stream = result.GetOutputStream();
45224f8817c2SEwan Crawford 
4523b9c1b51eSKate Stone     if (success) {
452400f56eebSLuke Drummond       stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
45254f8817c2SEwan Crawford       stream.EOL();
45264f8817c2SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4527b9c1b51eSKate Stone     } else {
45284f8817c2SEwan Crawford       stream.Printf("Error: Coordinate could not be found.");
45294f8817c2SEwan Crawford       stream.EOL();
45304f8817c2SEwan Crawford       result.SetStatus(eReturnStatusFailed);
45314f8817c2SEwan Crawford     }
45324f8817c2SEwan Crawford     return true;
45334f8817c2SEwan Crawford   }
45344f8817c2SEwan Crawford };
45354f8817c2SEwan Crawford 
4536b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpoint
4537b9c1b51eSKate Stone     : public CommandObjectMultiword {
45387dc7771cSEwan Crawford public:
4539b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpoint(
4540b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4541b9c1b51eSKate Stone       : CommandObjectMultiword(
4542b9c1b51eSKate Stone             interpreter, "renderscript kernel",
4543b9c1b51eSKate Stone             "Commands that generate breakpoints on renderscript kernels.",
4544b9c1b51eSKate Stone             nullptr) {
4545b9c1b51eSKate Stone     LoadSubCommand(
4546b9c1b51eSKate Stone         "set",
4547b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4548b9c1b51eSKate Stone             interpreter)));
4549b9c1b51eSKate Stone     LoadSubCommand(
4550b9c1b51eSKate Stone         "all",
4551b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4552b9c1b51eSKate Stone             interpreter)));
45537dc7771cSEwan Crawford   }
45547dc7771cSEwan Crawford 
4555222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
45567dc7771cSEwan Crawford };
45577dc7771cSEwan Crawford 
4558b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
45594640cde1SColin Riley public:
45604640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4561b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript kernel",
4562b9c1b51eSKate Stone                                "Commands that deal with RenderScript kernels.",
4563b9c1b51eSKate Stone                                nullptr) {
4564b9c1b51eSKate Stone     LoadSubCommand(
4565b9c1b51eSKate Stone         "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4566b9c1b51eSKate Stone                     interpreter)));
4567b9c1b51eSKate Stone     LoadSubCommand(
4568b9c1b51eSKate Stone         "coordinate",
4569b9c1b51eSKate Stone         CommandObjectSP(
4570b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4571b9c1b51eSKate Stone     LoadSubCommand(
4572b9c1b51eSKate Stone         "breakpoint",
4573b9c1b51eSKate Stone         CommandObjectSP(
4574b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
45754640cde1SColin Riley   }
45764640cde1SColin Riley 
4577222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernel() override = default;
45784640cde1SColin Riley };
45794640cde1SColin Riley 
4580b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
45814640cde1SColin Riley public:
45824640cde1SColin Riley   CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4583b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript context dump",
4584b9c1b51eSKate Stone                             "Dumps renderscript context information.",
4585b9c1b51eSKate Stone                             "renderscript context dump",
4586b9c1b51eSKate Stone                             eCommandRequiresProcess |
4587b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
45884640cde1SColin Riley 
4589222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContextDump() override = default;
45904640cde1SColin Riley 
4591b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
45924640cde1SColin Riley     RenderScriptRuntime *runtime =
4593b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4594b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
45954640cde1SColin Riley     runtime->DumpContexts(result.GetOutputStream());
45964640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
45974640cde1SColin Riley     return true;
45984640cde1SColin Riley   }
45994640cde1SColin Riley };
46004640cde1SColin Riley 
46011f0f5b5bSZachary Turner static OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
46021f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
46031f0f5b5bSZachary Turner      nullptr, nullptr, 0, eArgTypeFilename,
46041f0f5b5bSZachary Turner      "Print results to specified file instead of command line."}};
46051f0f5b5bSZachary Turner 
4606b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
46074640cde1SColin Riley public:
46084640cde1SColin Riley   CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4609b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript context",
4610b9c1b51eSKate Stone                                "Commands that deal with RenderScript contexts.",
4611b9c1b51eSKate Stone                                nullptr) {
4612b9c1b51eSKate Stone     LoadSubCommand(
4613b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4614b9c1b51eSKate Stone                     interpreter)));
46154640cde1SColin Riley   }
46164640cde1SColin Riley 
4617222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContext() override = default;
46184640cde1SColin Riley };
46194640cde1SColin Riley 
4620b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationDump
4621b9c1b51eSKate Stone     : public CommandObjectParsed {
4622a0f08674SEwan Crawford public:
4623b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationDump(
4624b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4625a0f08674SEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation dump",
4626b9c1b51eSKate Stone                             "Displays the contents of a particular allocation",
4627b9c1b51eSKate Stone                             "renderscript allocation dump <ID>",
4628b9c1b51eSKate Stone                             eCommandRequiresProcess |
4629b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched),
4630b9c1b51eSKate Stone         m_options() {}
4631a0f08674SEwan Crawford 
4632222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4633222b937cSEugene Zelenko 
4634b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
4635a0f08674SEwan Crawford 
4636b9c1b51eSKate Stone   class CommandOptions : public Options {
4637a0f08674SEwan Crawford   public:
4638e1cfbc79STodd Fiala     CommandOptions() : Options() {}
4639a0f08674SEwan Crawford 
4640222b937cSEugene Zelenko     ~CommandOptions() override = default;
4641a0f08674SEwan Crawford 
4642fe11483bSZachary Turner     Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4643b3bbcb12SLuke Drummond                          ExecutionContext *exe_ctx) override {
464480af0b9eSLuke Drummond       Error err;
4645a0f08674SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
4646a0f08674SEwan Crawford 
4647b9c1b51eSKate Stone       switch (short_option) {
4648a0f08674SEwan Crawford       case 'f':
4649a0f08674SEwan Crawford         m_outfile.SetFile(option_arg, true);
4650b9c1b51eSKate Stone         if (m_outfile.Exists()) {
4651a0f08674SEwan Crawford           m_outfile.Clear();
4652fe11483bSZachary Turner           err.SetErrorStringWithFormat("file already exists: '%s'",
4653fe11483bSZachary Turner                                        option_arg.str().c_str());
4654a0f08674SEwan Crawford         }
4655a0f08674SEwan Crawford         break;
4656a0f08674SEwan Crawford       default:
465780af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4658a0f08674SEwan Crawford         break;
4659a0f08674SEwan Crawford       }
466080af0b9eSLuke Drummond       return err;
4661a0f08674SEwan Crawford     }
4662a0f08674SEwan Crawford 
4663b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4664a0f08674SEwan Crawford       m_outfile.Clear();
4665a0f08674SEwan Crawford     }
4666a0f08674SEwan Crawford 
46671f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
466870602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
46691f0f5b5bSZachary Turner     }
4670a0f08674SEwan Crawford 
4671a0f08674SEwan Crawford     FileSpec m_outfile;
4672a0f08674SEwan Crawford   };
4673a0f08674SEwan Crawford 
4674b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4675a0f08674SEwan Crawford     const size_t argc = command.GetArgumentCount();
4676b9c1b51eSKate Stone     if (argc < 1) {
4677b9c1b51eSKate Stone       result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4678b9c1b51eSKate Stone                                    "As well as an optional -f argument",
4679a0f08674SEwan Crawford                                    m_cmd_name.c_str());
4680a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4681a0f08674SEwan Crawford       return false;
4682a0f08674SEwan Crawford     }
4683a0f08674SEwan Crawford 
4684b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4685b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4686b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4687a0f08674SEwan Crawford 
4688a0f08674SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
468980af0b9eSLuke Drummond     bool success = false;
4690b9c1b51eSKate Stone     const uint32_t id =
469180af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
469280af0b9eSLuke Drummond     if (!success) {
4693b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4694b9c1b51eSKate Stone                                    id_cstr);
4695a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4696a0f08674SEwan Crawford       return false;
4697a0f08674SEwan Crawford     }
4698a0f08674SEwan Crawford 
4699a0f08674SEwan Crawford     Stream *output_strm = nullptr;
4700a0f08674SEwan Crawford     StreamFile outfile_stream;
4701b9c1b51eSKate Stone     const FileSpec &outfile_spec =
4702b9c1b51eSKate Stone         m_options.m_outfile; // Dump allocation to file instead
4703b9c1b51eSKate Stone     if (outfile_spec) {
4704a0f08674SEwan Crawford       // Open output file
4705a0f08674SEwan Crawford       char path[256];
4706a0f08674SEwan Crawford       outfile_spec.GetPath(path, sizeof(path));
4707b9c1b51eSKate Stone       if (outfile_stream.GetFile()
4708b9c1b51eSKate Stone               .Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate)
4709b9c1b51eSKate Stone               .Success()) {
4710a0f08674SEwan Crawford         output_strm = &outfile_stream;
4711a0f08674SEwan Crawford         result.GetOutputStream().Printf("Results written to '%s'", path);
4712a0f08674SEwan Crawford         result.GetOutputStream().EOL();
4713b9c1b51eSKate Stone       } else {
4714a0f08674SEwan Crawford         result.AppendErrorWithFormat("Couldn't open file '%s'", path);
4715a0f08674SEwan Crawford         result.SetStatus(eReturnStatusFailed);
4716a0f08674SEwan Crawford         return false;
4717a0f08674SEwan Crawford       }
4718b9c1b51eSKate Stone     } else
4719a0f08674SEwan Crawford       output_strm = &result.GetOutputStream();
4720a0f08674SEwan Crawford 
4721a0f08674SEwan Crawford     assert(output_strm != nullptr);
472280af0b9eSLuke Drummond     bool dumped =
4723b9c1b51eSKate Stone         runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4724a0f08674SEwan Crawford 
472580af0b9eSLuke Drummond     if (dumped)
4726a0f08674SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4727a0f08674SEwan Crawford     else
4728a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4729a0f08674SEwan Crawford 
4730a0f08674SEwan Crawford     return true;
4731a0f08674SEwan Crawford   }
4732a0f08674SEwan Crawford 
4733a0f08674SEwan Crawford private:
4734a0f08674SEwan Crawford   CommandOptions m_options;
4735a0f08674SEwan Crawford };
4736a0f08674SEwan Crawford 
47371f0f5b5bSZachary Turner static OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
47381f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
47391f0f5b5bSZachary Turner      nullptr, 0, eArgTypeIndex,
47401f0f5b5bSZachary Turner      "Only show details of a single allocation with specified id."}};
4741a0f08674SEwan Crawford 
4742b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationList
4743b9c1b51eSKate Stone     : public CommandObjectParsed {
474415f2bd95SEwan Crawford public:
4745b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationList(
4746b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4747b9c1b51eSKate Stone       : CommandObjectParsed(
4748b9c1b51eSKate Stone             interpreter, "renderscript allocation list",
4749b9c1b51eSKate Stone             "List renderscript allocations and their information.",
4750b9c1b51eSKate Stone             "renderscript allocation list",
4751b3f7f69dSAidan Dodds             eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4752b9c1b51eSKate Stone         m_options() {}
475315f2bd95SEwan Crawford 
4754222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4755222b937cSEugene Zelenko 
4756b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
475715f2bd95SEwan Crawford 
4758b9c1b51eSKate Stone   class CommandOptions : public Options {
475915f2bd95SEwan Crawford   public:
4760e1cfbc79STodd Fiala     CommandOptions() : Options(), m_id(0) {}
476115f2bd95SEwan Crawford 
4762222b937cSEugene Zelenko     ~CommandOptions() override = default;
476315f2bd95SEwan Crawford 
4764fe11483bSZachary Turner     Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4765b3bbcb12SLuke Drummond                          ExecutionContext *exe_ctx) override {
476680af0b9eSLuke Drummond       Error err;
476715f2bd95SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
476815f2bd95SEwan Crawford 
4769b9c1b51eSKate Stone       switch (short_option) {
4770b649b005SEwan Crawford       case 'i':
4771fe11483bSZachary Turner         if (option_arg.getAsInteger(0, m_id))
477280af0b9eSLuke Drummond           err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4773b9c1b51eSKate Stone                                        short_option);
477415f2bd95SEwan Crawford         break;
477580af0b9eSLuke Drummond       default:
477680af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
477780af0b9eSLuke Drummond         break;
477815f2bd95SEwan Crawford       }
477980af0b9eSLuke Drummond       return err;
478015f2bd95SEwan Crawford     }
478115f2bd95SEwan Crawford 
4782b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
478315f2bd95SEwan Crawford 
47841f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
478570602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
47861f0f5b5bSZachary Turner     }
478715f2bd95SEwan Crawford 
4788b649b005SEwan Crawford     uint32_t m_id;
478915f2bd95SEwan Crawford   };
479015f2bd95SEwan Crawford 
4791b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4792b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4793b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4794b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4795b9c1b51eSKate Stone     runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4796b9c1b51eSKate Stone                              m_options.m_id);
479715f2bd95SEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
479815f2bd95SEwan Crawford     return true;
479915f2bd95SEwan Crawford   }
480015f2bd95SEwan Crawford 
480115f2bd95SEwan Crawford private:
480215f2bd95SEwan Crawford   CommandOptions m_options;
480315f2bd95SEwan Crawford };
480415f2bd95SEwan Crawford 
4805b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationLoad
4806b9c1b51eSKate Stone     : public CommandObjectParsed {
480755232f09SEwan Crawford public:
4808b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationLoad(
4809b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4810b3f7f69dSAidan Dodds       : CommandObjectParsed(
4811b9c1b51eSKate Stone             interpreter, "renderscript allocation load",
4812b9c1b51eSKate Stone             "Loads renderscript allocation contents from a file.",
4813b9c1b51eSKate Stone             "renderscript allocation load <ID> <filename>",
4814b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
481555232f09SEwan Crawford 
4816222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
481755232f09SEwan Crawford 
4818b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
481955232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4820b9c1b51eSKate Stone     if (argc != 2) {
4821b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4822b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4823b3f7f69dSAidan Dodds           m_cmd_name.c_str());
482455232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
482555232f09SEwan Crawford       return false;
482655232f09SEwan Crawford     }
482755232f09SEwan Crawford 
4828b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4829b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4830b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
483155232f09SEwan Crawford 
483255232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
483380af0b9eSLuke Drummond     bool success = false;
4834b9c1b51eSKate Stone     const uint32_t id =
483580af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
483680af0b9eSLuke Drummond     if (!success) {
4837b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4838b9c1b51eSKate Stone                                    id_cstr);
483955232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
484055232f09SEwan Crawford       return false;
484155232f09SEwan Crawford     }
484255232f09SEwan Crawford 
484380af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
484480af0b9eSLuke Drummond     bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
484580af0b9eSLuke Drummond                                           m_exe_ctx.GetFramePtr());
484655232f09SEwan Crawford 
484780af0b9eSLuke Drummond     if (loaded)
484855232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
484955232f09SEwan Crawford     else
485055232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
485155232f09SEwan Crawford 
485255232f09SEwan Crawford     return true;
485355232f09SEwan Crawford   }
485455232f09SEwan Crawford };
485555232f09SEwan Crawford 
4856b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationSave
4857b9c1b51eSKate Stone     : public CommandObjectParsed {
485855232f09SEwan Crawford public:
4859b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationSave(
4860b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4861b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript allocation save",
4862b9c1b51eSKate Stone                             "Write renderscript allocation contents to a file.",
4863b9c1b51eSKate Stone                             "renderscript allocation save <ID> <filename>",
4864b9c1b51eSKate Stone                             eCommandRequiresProcess |
4865b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
486655232f09SEwan Crawford 
4867222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
486855232f09SEwan Crawford 
4869b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
487055232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4871b9c1b51eSKate Stone     if (argc != 2) {
4872b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4873b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4874b3f7f69dSAidan Dodds           m_cmd_name.c_str());
487555232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
487655232f09SEwan Crawford       return false;
487755232f09SEwan Crawford     }
487855232f09SEwan Crawford 
4879b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4880b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4881b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
488255232f09SEwan Crawford 
488355232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
488480af0b9eSLuke Drummond     bool success = false;
4885b9c1b51eSKate Stone     const uint32_t id =
488680af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
488780af0b9eSLuke Drummond     if (!success) {
4888b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4889b9c1b51eSKate Stone                                    id_cstr);
489055232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
489155232f09SEwan Crawford       return false;
489255232f09SEwan Crawford     }
489355232f09SEwan Crawford 
489480af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
489580af0b9eSLuke Drummond     bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
489680af0b9eSLuke Drummond                                          m_exe_ctx.GetFramePtr());
489755232f09SEwan Crawford 
489880af0b9eSLuke Drummond     if (saved)
489955232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
490055232f09SEwan Crawford     else
490155232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
490255232f09SEwan Crawford 
490355232f09SEwan Crawford     return true;
490455232f09SEwan Crawford   }
490555232f09SEwan Crawford };
490655232f09SEwan Crawford 
4907b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationRefresh
4908b9c1b51eSKate Stone     : public CommandObjectParsed {
49090d2bfcfbSEwan Crawford public:
4910b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationRefresh(
4911b9c1b51eSKate Stone       CommandInterpreter &interpreter)
49120d2bfcfbSEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4913b9c1b51eSKate Stone                             "Recomputes the details of all allocations.",
4914b9c1b51eSKate Stone                             "renderscript allocation refresh",
4915b9c1b51eSKate Stone                             eCommandRequiresProcess |
4916b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
49170d2bfcfbSEwan Crawford 
49180d2bfcfbSEwan Crawford   ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
49190d2bfcfbSEwan Crawford 
4920b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
49210d2bfcfbSEwan Crawford     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4922b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4923b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
49240d2bfcfbSEwan Crawford 
4925b9c1b51eSKate Stone     bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4926b9c1b51eSKate Stone                                                     m_exe_ctx.GetFramePtr());
49270d2bfcfbSEwan Crawford 
4928b9c1b51eSKate Stone     if (success) {
49290d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
49300d2bfcfbSEwan Crawford       return true;
4931b9c1b51eSKate Stone     } else {
49320d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusFailed);
49330d2bfcfbSEwan Crawford       return false;
49340d2bfcfbSEwan Crawford     }
49350d2bfcfbSEwan Crawford   }
49360d2bfcfbSEwan Crawford };
49370d2bfcfbSEwan Crawford 
4938b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocation
4939b9c1b51eSKate Stone     : public CommandObjectMultiword {
494015f2bd95SEwan Crawford public:
494115f2bd95SEwan Crawford   CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4942b9c1b51eSKate Stone       : CommandObjectMultiword(
4943b9c1b51eSKate Stone             interpreter, "renderscript allocation",
4944b9c1b51eSKate Stone             "Commands that deal with RenderScript allocations.", nullptr) {
4945b9c1b51eSKate Stone     LoadSubCommand(
4946b9c1b51eSKate Stone         "list",
4947b9c1b51eSKate Stone         CommandObjectSP(
4948b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4949b9c1b51eSKate Stone     LoadSubCommand(
4950b9c1b51eSKate Stone         "dump",
4951b9c1b51eSKate Stone         CommandObjectSP(
4952b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4953b9c1b51eSKate Stone     LoadSubCommand(
4954b9c1b51eSKate Stone         "save",
4955b9c1b51eSKate Stone         CommandObjectSP(
4956b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4957b9c1b51eSKate Stone     LoadSubCommand(
4958b9c1b51eSKate Stone         "load",
4959b9c1b51eSKate Stone         CommandObjectSP(
4960b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4961b9c1b51eSKate Stone     LoadSubCommand(
4962b9c1b51eSKate Stone         "refresh",
4963b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4964b9c1b51eSKate Stone             interpreter)));
496515f2bd95SEwan Crawford   }
496615f2bd95SEwan Crawford 
4967222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocation() override = default;
496815f2bd95SEwan Crawford };
496915f2bd95SEwan Crawford 
4970b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
49714640cde1SColin Riley public:
49724640cde1SColin Riley   CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4973b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript status",
4974b9c1b51eSKate Stone                             "Displays current RenderScript runtime status.",
4975b9c1b51eSKate Stone                             "renderscript status",
4976b9c1b51eSKate Stone                             eCommandRequiresProcess |
4977b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
49784640cde1SColin Riley 
4979222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeStatus() override = default;
49804640cde1SColin Riley 
4981b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
49824640cde1SColin Riley     RenderScriptRuntime *runtime =
4983b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4984b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
49854640cde1SColin Riley     runtime->Status(result.GetOutputStream());
49864640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
49874640cde1SColin Riley     return true;
49884640cde1SColin Riley   }
49894640cde1SColin Riley };
49904640cde1SColin Riley 
4991b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReduction
4992b3bbcb12SLuke Drummond     : public CommandObjectMultiword {
4993b3bbcb12SLuke Drummond public:
4994b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
4995b3bbcb12SLuke Drummond       : CommandObjectMultiword(interpreter, "renderscript reduction",
4996b3bbcb12SLuke Drummond                                "Commands that handle general reduction kernels",
4997b3bbcb12SLuke Drummond                                nullptr) {
4998b3bbcb12SLuke Drummond     LoadSubCommand(
4999b3bbcb12SLuke Drummond         "breakpoint",
5000b3bbcb12SLuke Drummond         CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
5001b3bbcb12SLuke Drummond             interpreter)));
5002b3bbcb12SLuke Drummond   }
5003b3bbcb12SLuke Drummond   ~CommandObjectRenderScriptRuntimeReduction() override = default;
5004b3bbcb12SLuke Drummond };
5005b3bbcb12SLuke Drummond 
5006b9c1b51eSKate Stone class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
50075ec532a9SColin Riley public:
50085ec532a9SColin Riley   CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
5009b9c1b51eSKate Stone       : CommandObjectMultiword(
5010b9c1b51eSKate Stone             interpreter, "renderscript",
5011b9c1b51eSKate Stone             "Commands for operating on the RenderScript runtime.",
5012b9c1b51eSKate Stone             "renderscript <subcommand> [<subcommand-options>]") {
5013b9c1b51eSKate Stone     LoadSubCommand(
5014b9c1b51eSKate Stone         "module", CommandObjectSP(
5015b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeModule(interpreter)));
5016b9c1b51eSKate Stone     LoadSubCommand(
5017b9c1b51eSKate Stone         "status", CommandObjectSP(
5018b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeStatus(interpreter)));
5019b9c1b51eSKate Stone     LoadSubCommand(
5020b9c1b51eSKate Stone         "kernel", CommandObjectSP(
5021b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeKernel(interpreter)));
5022b9c1b51eSKate Stone     LoadSubCommand("context",
5023b9c1b51eSKate Stone                    CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
5024b9c1b51eSKate Stone                        interpreter)));
5025b9c1b51eSKate Stone     LoadSubCommand(
5026b9c1b51eSKate Stone         "allocation",
5027b9c1b51eSKate Stone         CommandObjectSP(
5028b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
502921fed052SAidan Dodds     LoadSubCommand("scriptgroup",
503021fed052SAidan Dodds                    NewCommandObjectRenderScriptScriptGroup(interpreter));
5031b3bbcb12SLuke Drummond     LoadSubCommand(
5032b3bbcb12SLuke Drummond         "reduction",
5033b3bbcb12SLuke Drummond         CommandObjectSP(
5034b3bbcb12SLuke Drummond             new CommandObjectRenderScriptRuntimeReduction(interpreter)));
50355ec532a9SColin Riley   }
50365ec532a9SColin Riley 
5037222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntime() override = default;
50385ec532a9SColin Riley };
5039ef20b08fSColin Riley 
5040b9c1b51eSKate Stone void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
5041ef20b08fSColin Riley 
5042ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
5043b9c1b51eSKate Stone     : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
5044b9c1b51eSKate Stone       m_debuggerPresentFlagged(false), m_breakAllKernels(false),
5045b9c1b51eSKate Stone       m_ir_passes(nullptr) {
50464640cde1SColin Riley   ModulesDidLoad(process->GetTarget().GetImages());
5047ef20b08fSColin Riley }
50484640cde1SColin Riley 
5049b9c1b51eSKate Stone lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
5050b9c1b51eSKate Stone     lldb_private::CommandInterpreter &interpreter) {
50510a66e2f1SEnrico Granata   return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
50524640cde1SColin Riley }
50534640cde1SColin Riley 
505478f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
5055