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 
10b3bbcb12SLuke Drummond #include "llvm/ADT/StringSwitch.h"
117f193d69SLuke Drummond 
125ec532a9SColin Riley #include "RenderScriptRuntime.h"
1321fed052SAidan Dodds #include "RenderScriptScriptGroup.h"
145ec532a9SColin Riley 
15b3f7f69dSAidan Dodds #include "lldb/Breakpoint/StoppointCallbackContext.h"
165ec532a9SColin Riley #include "lldb/Core/Debugger.h"
1729cb868aSZachary Turner #include "lldb/Core/DumpDataExtractor.h"
185ec532a9SColin Riley #include "lldb/Core/PluginManager.h"
19b3f7f69dSAidan Dodds #include "lldb/Core/ValueObjectVariable.h"
208b244e21SEwan Crawford #include "lldb/DataFormatters/DumpValueObjectOptions.h"
21b3f7f69dSAidan Dodds #include "lldb/Expression/UserExpression.h"
223eb2b44dSZachary Turner #include "lldb/Host/OptionParser.h"
23a0f08674SEwan Crawford #include "lldb/Host/StringConvert.h"
24b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandInterpreter.h"
25b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandObjectMultiword.h"
26b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandReturnObject.h"
27b3f7f69dSAidan Dodds #include "lldb/Interpreter/Options.h"
2821fed052SAidan Dodds #include "lldb/Symbol/Function.h"
295ec532a9SColin Riley #include "lldb/Symbol/Symbol.h"
304640cde1SColin Riley #include "lldb/Symbol/Type.h"
31b3f7f69dSAidan Dodds #include "lldb/Symbol/VariableList.h"
325ec532a9SColin Riley #include "lldb/Target/Process.h"
33b3f7f69dSAidan Dodds #include "lldb/Target/RegisterContext.h"
3421fed052SAidan Dodds #include "lldb/Target/SectionLoadList.h"
355ec532a9SColin Riley #include "lldb/Target/Target.h"
36018f5a7eSEwan Crawford #include "lldb/Target/Thread.h"
37145d95c9SPavel Labath #include "lldb/Utility/Args.h"
38bf9a7730SZachary Turner #include "lldb/Utility/ConstString.h"
396f9e6901SZachary Turner #include "lldb/Utility/Log.h"
40d821c997SPavel Labath #include "lldb/Utility/RegisterValue.h"
41bf9a7730SZachary Turner #include "lldb/Utility/RegularExpression.h"
4297206d57SZachary Turner #include "lldb/Utility/Status.h"
435ec532a9SColin Riley 
445ec532a9SColin Riley using namespace lldb;
455ec532a9SColin Riley using namespace lldb_private;
4698156583SEwan Crawford using namespace lldb_renderscript;
475ec532a9SColin Riley 
4800f56eebSLuke Drummond #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")"
4900f56eebSLuke Drummond 
50b9c1b51eSKate Stone namespace {
5178f339d1SEwan Crawford 
5278f339d1SEwan Crawford // The empirical_type adds a basic level of validation to arbitrary data
5380af0b9eSLuke Drummond // allowing us to track if data has been discovered and stored or not. An
5480af0b9eSLuke Drummond // empirical_type will be marked as valid only if it has been explicitly
55b9c1b51eSKate Stone // assigned to.
56b9c1b51eSKate Stone template <typename type_t> class empirical_type {
5778f339d1SEwan Crawford public:
5878f339d1SEwan Crawford   // Ctor. Contents is invalid when constructed.
59b3f7f69dSAidan Dodds   empirical_type() : valid(false) {}
6078f339d1SEwan Crawford 
6178f339d1SEwan Crawford   // Return true and copy contents to out if valid, else return false.
62b9c1b51eSKate Stone   bool get(type_t &out) const {
6378f339d1SEwan Crawford     if (valid)
6478f339d1SEwan Crawford       out = data;
6578f339d1SEwan Crawford     return valid;
6678f339d1SEwan Crawford   }
6778f339d1SEwan Crawford 
6878f339d1SEwan Crawford   // Return a pointer to the contents or nullptr if it was not valid.
69b9c1b51eSKate Stone   const type_t *get() const { return valid ? &data : nullptr; }
7078f339d1SEwan Crawford 
7178f339d1SEwan Crawford   // Assign data explicitly.
72b9c1b51eSKate Stone   void set(const type_t in) {
7378f339d1SEwan Crawford     data = in;
7478f339d1SEwan Crawford     valid = true;
7578f339d1SEwan Crawford   }
7678f339d1SEwan Crawford 
7778f339d1SEwan Crawford   // Mark contents as invalid.
78b9c1b51eSKate Stone   void invalidate() { valid = false; }
7978f339d1SEwan Crawford 
8078f339d1SEwan Crawford   // Returns true if this type contains valid data.
81b9c1b51eSKate Stone   bool isValid() const { return valid; }
8278f339d1SEwan Crawford 
8378f339d1SEwan Crawford   // Assignment operator.
84b9c1b51eSKate Stone   empirical_type<type_t> &operator=(const type_t in) {
8578f339d1SEwan Crawford     set(in);
8678f339d1SEwan Crawford     return *this;
8778f339d1SEwan Crawford   }
8878f339d1SEwan Crawford 
8978f339d1SEwan Crawford   // Dereference operator returns contents.
9078f339d1SEwan Crawford   // Warning: Will assert if not valid so use only when you know data is valid.
91b9c1b51eSKate Stone   const type_t &operator*() const {
9278f339d1SEwan Crawford     assert(valid);
9378f339d1SEwan Crawford     return data;
9478f339d1SEwan Crawford   }
9578f339d1SEwan Crawford 
9678f339d1SEwan Crawford protected:
9778f339d1SEwan Crawford   bool valid;
9878f339d1SEwan Crawford   type_t data;
9978f339d1SEwan Crawford };
10078f339d1SEwan Crawford 
101b9c1b51eSKate Stone // ArgItem is used by the GetArgs() function when reading function arguments
102b9c1b51eSKate Stone // from the target.
103b9c1b51eSKate Stone struct ArgItem {
104b9c1b51eSKate Stone   enum { ePointer, eInt32, eInt64, eLong, eBool } type;
105f4786785SAidan Dodds 
106f4786785SAidan Dodds   uint64_t value;
107f4786785SAidan Dodds 
108f4786785SAidan Dodds   explicit operator uint64_t() const { return value; }
109f4786785SAidan Dodds };
110f4786785SAidan Dodds 
111b9c1b51eSKate Stone // Context structure to be passed into GetArgsXXX(), argument reading functions
112b9c1b51eSKate Stone // below.
113b9c1b51eSKate Stone struct GetArgsCtx {
114f4786785SAidan Dodds   RegisterContext *reg_ctx;
115f4786785SAidan Dodds   Process *process;
116f4786785SAidan Dodds };
117f4786785SAidan Dodds 
118b9c1b51eSKate Stone bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
119f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
120f4786785SAidan Dodds 
12197206d57SZachary Turner   Status err;
12267dc3e15SAidan Dodds 
123f4786785SAidan Dodds   // get the current stack pointer
124f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
125f4786785SAidan Dodds 
126b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
127f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
128f4786785SAidan Dodds     // advance up the stack by one argument
129f4786785SAidan Dodds     sp += sizeof(uint32_t);
130f4786785SAidan Dodds     // get the argument type size
131f4786785SAidan Dodds     size_t arg_size = sizeof(uint32_t);
132f4786785SAidan Dodds     // read the argument from memory
133f4786785SAidan Dodds     arg.value = 0;
13497206d57SZachary Turner     Status err;
135b9c1b51eSKate Stone     size_t read =
13680af0b9eSLuke Drummond         ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
13780af0b9eSLuke Drummond     if (read != arg_size || !err.Success()) {
138f4786785SAidan Dodds       if (log)
139b9c1b51eSKate Stone         log->Printf("%s - error reading argument: %" PRIu64 " '%s'",
14080af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString());
141f4786785SAidan Dodds       return false;
142f4786785SAidan Dodds     }
143f4786785SAidan Dodds   }
144f4786785SAidan Dodds   return true;
145f4786785SAidan Dodds }
146f4786785SAidan Dodds 
147b9c1b51eSKate Stone bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
148f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
149f4786785SAidan Dodds 
150f4786785SAidan Dodds   // number of arguments passed in registers
15180af0b9eSLuke Drummond   static const uint32_t args_in_reg = 6;
152f4786785SAidan Dodds   // register passing order
15380af0b9eSLuke Drummond   static const std::array<const char *, args_in_reg> reg_names{
154b9c1b51eSKate Stone       {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
155f4786785SAidan Dodds   // argument type to size mapping
1561ee07253SSaleem Abdulrasool   static const std::array<size_t, 5> arg_size{{
157f4786785SAidan Dodds       8, // ePointer,
158f4786785SAidan Dodds       4, // eInt32,
159f4786785SAidan Dodds       8, // eInt64,
160f4786785SAidan Dodds       8, // eLong,
161f4786785SAidan Dodds       4, // eBool,
1621ee07253SSaleem Abdulrasool   }};
163f4786785SAidan Dodds 
16497206d57SZachary Turner   Status err;
16517e07c0aSAidan Dodds 
166f4786785SAidan Dodds   // get the current stack pointer
167f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
168f4786785SAidan Dodds   // step over the return address
169f4786785SAidan Dodds   sp += sizeof(uint64_t);
170f4786785SAidan Dodds 
171f4786785SAidan Dodds   // check the stack alignment was correct (16 byte aligned)
172b9c1b51eSKate Stone   if ((sp & 0xf) != 0x0) {
173f4786785SAidan Dodds     if (log)
174f4786785SAidan Dodds       log->Printf("%s - stack misaligned", __FUNCTION__);
175f4786785SAidan Dodds     return false;
176f4786785SAidan Dodds   }
177f4786785SAidan Dodds 
178f4786785SAidan Dodds   // find the start of arguments on the stack
179f4786785SAidan Dodds   uint64_t sp_offset = 0;
18080af0b9eSLuke Drummond   for (uint32_t i = args_in_reg; i < num_args; ++i) {
181f4786785SAidan Dodds     sp_offset += arg_size[arg_list[i].type];
182f4786785SAidan Dodds   }
183f4786785SAidan Dodds   // round up to multiple of 16
184f4786785SAidan Dodds   sp_offset = (sp_offset + 0xf) & 0xf;
185f4786785SAidan Dodds   sp += sp_offset;
186f4786785SAidan Dodds 
187b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
188f4786785SAidan Dodds     bool success = false;
189f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
190f4786785SAidan Dodds     // arguments passed in registers
19180af0b9eSLuke Drummond     if (i < args_in_reg) {
19280af0b9eSLuke Drummond       const RegisterInfo *reg =
19380af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoByName(reg_names[i]);
19480af0b9eSLuke Drummond       RegisterValue reg_val;
19580af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
19680af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
197f4786785SAidan Dodds     }
198f4786785SAidan Dodds     // arguments passed on the stack
199b9c1b51eSKate Stone     else {
200f4786785SAidan Dodds       // get the argument type size
201f4786785SAidan Dodds       const size_t size = arg_size[arg_list[i].type];
202f4786785SAidan Dodds       // read the argument from memory
203f4786785SAidan Dodds       arg.value = 0;
204b9c1b51eSKate Stone       // note: due to little endian layout reading 4 or 8 bytes will give the
205b9c1b51eSKate Stone       // correct value.
20680af0b9eSLuke Drummond       size_t read = ctx.process->ReadMemory(sp, &arg.value, size, err);
20780af0b9eSLuke Drummond       success = (err.Success() && read == size);
208f4786785SAidan Dodds       // advance past this argument
209f4786785SAidan Dodds       sp -= size;
210f4786785SAidan Dodds     }
211f4786785SAidan Dodds     // fail if we couldn't read this argument
212b9c1b51eSKate Stone     if (!success) {
213f4786785SAidan Dodds       if (log)
21417e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
21580af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
216f4786785SAidan Dodds       return false;
217f4786785SAidan Dodds     }
218f4786785SAidan Dodds   }
219f4786785SAidan Dodds   return true;
220f4786785SAidan Dodds }
221f4786785SAidan Dodds 
222b9c1b51eSKate Stone bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
223f4786785SAidan Dodds   // number of arguments passed in registers
22480af0b9eSLuke Drummond   static const uint32_t args_in_reg = 4;
225f4786785SAidan Dodds 
226f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
227f4786785SAidan Dodds 
22897206d57SZachary Turner   Status err;
22917e07c0aSAidan Dodds 
230f4786785SAidan Dodds   // get the current stack pointer
231f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
232f4786785SAidan Dodds 
233b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
234f4786785SAidan Dodds     bool success = false;
235f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
236f4786785SAidan Dodds     // arguments passed in registers
23780af0b9eSLuke Drummond     if (i < args_in_reg) {
23880af0b9eSLuke Drummond       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
23980af0b9eSLuke Drummond       RegisterValue reg_val;
24080af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
24180af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt32(0, &success);
242f4786785SAidan Dodds     }
243f4786785SAidan Dodds     // arguments passed on the stack
244b9c1b51eSKate Stone     else {
245f4786785SAidan Dodds       // get the argument type size
246f4786785SAidan Dodds       const size_t arg_size = sizeof(uint32_t);
247f4786785SAidan Dodds       // clear all 64bits
248f4786785SAidan Dodds       arg.value = 0;
249f4786785SAidan Dodds       // read this argument from memory
250b9c1b51eSKate Stone       size_t bytes_read =
25180af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
25280af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
253f4786785SAidan Dodds       // advance the stack pointer
254f4786785SAidan Dodds       sp += sizeof(uint32_t);
255f4786785SAidan Dodds     }
256f4786785SAidan Dodds     // fail if we couldn't read this argument
257b9c1b51eSKate Stone     if (!success) {
258f4786785SAidan Dodds       if (log)
25917e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
26080af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
261f4786785SAidan Dodds       return false;
262f4786785SAidan Dodds     }
263f4786785SAidan Dodds   }
264f4786785SAidan Dodds   return true;
265f4786785SAidan Dodds }
266f4786785SAidan Dodds 
267b9c1b51eSKate Stone bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
268f4786785SAidan Dodds   // number of arguments passed in registers
26980af0b9eSLuke Drummond   static const uint32_t args_in_reg = 8;
270f4786785SAidan Dodds 
271f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
272f4786785SAidan Dodds 
273b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
274f4786785SAidan Dodds     bool success = false;
275f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
276f4786785SAidan Dodds     // arguments passed in registers
27780af0b9eSLuke Drummond     if (i < args_in_reg) {
27880af0b9eSLuke Drummond       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
27980af0b9eSLuke Drummond       RegisterValue reg_val;
28080af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
28180af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
282f4786785SAidan Dodds     }
283f4786785SAidan Dodds     // arguments passed on the stack
284b9c1b51eSKate Stone     else {
285f4786785SAidan Dodds       if (log)
286b9c1b51eSKate Stone         log->Printf("%s - reading arguments spilled to stack not implemented",
287b9c1b51eSKate Stone                     __FUNCTION__);
288f4786785SAidan Dodds     }
289f4786785SAidan Dodds     // fail if we couldn't read this argument
290b9c1b51eSKate Stone     if (!success) {
291f4786785SAidan Dodds       if (log)
292f4786785SAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__,
293f4786785SAidan Dodds                     uint64_t(i));
294f4786785SAidan Dodds       return false;
295f4786785SAidan Dodds     }
296f4786785SAidan Dodds   }
297f4786785SAidan Dodds   return true;
298f4786785SAidan Dodds }
299f4786785SAidan Dodds 
300b9c1b51eSKate Stone bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
301f4786785SAidan Dodds   // number of arguments passed in registers
30280af0b9eSLuke Drummond   static const uint32_t args_in_reg = 4;
303f4786785SAidan Dodds   // register file offset to first argument
30480af0b9eSLuke Drummond   static const uint32_t reg_offset = 4;
305f4786785SAidan Dodds 
306f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
307f4786785SAidan Dodds 
30897206d57SZachary Turner   Status err;
30917e07c0aSAidan Dodds 
31005097246SAdrian Prantl   // find offset to arguments on the stack (+16 to skip over a0-a3 shadow
31105097246SAdrian Prantl   // space)
31217e07c0aSAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP() + 16;
31317e07c0aSAidan Dodds 
314b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
315f4786785SAidan Dodds     bool success = false;
316f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
317f4786785SAidan Dodds     // arguments passed in registers
31880af0b9eSLuke Drummond     if (i < args_in_reg) {
31980af0b9eSLuke Drummond       const RegisterInfo *reg =
32080af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
32180af0b9eSLuke Drummond       RegisterValue reg_val;
32280af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
32380af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
324f4786785SAidan Dodds     }
325f4786785SAidan Dodds     // arguments passed on the stack
326b9c1b51eSKate Stone     else {
3276dd4b579SAidan Dodds       const size_t arg_size = sizeof(uint32_t);
3286dd4b579SAidan Dodds       arg.value = 0;
329b9c1b51eSKate Stone       size_t bytes_read =
33080af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
33180af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
33267dc3e15SAidan Dodds       // advance the stack pointer
33367dc3e15SAidan Dodds       sp += arg_size;
334f4786785SAidan Dodds     }
335f4786785SAidan Dodds     // fail if we couldn't read this argument
336b9c1b51eSKate Stone     if (!success) {
337f4786785SAidan Dodds       if (log)
33867dc3e15SAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
33980af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
340f4786785SAidan Dodds       return false;
341f4786785SAidan Dodds     }
342f4786785SAidan Dodds   }
343f4786785SAidan Dodds   return true;
344f4786785SAidan Dodds }
345f4786785SAidan Dodds 
346b9c1b51eSKate Stone bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
347f4786785SAidan Dodds   // number of arguments passed in registers
34880af0b9eSLuke Drummond   static const uint32_t args_in_reg = 8;
349f4786785SAidan Dodds   // register file offset to first argument
35080af0b9eSLuke Drummond   static const uint32_t reg_offset = 4;
351f4786785SAidan Dodds 
352f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
353f4786785SAidan Dodds 
35497206d57SZachary Turner   Status err;
35517e07c0aSAidan Dodds 
356f4786785SAidan Dodds   // get the current stack pointer
357f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
358f4786785SAidan Dodds 
359b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
360f4786785SAidan Dodds     bool success = false;
361f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
362f4786785SAidan Dodds     // arguments passed in registers
36380af0b9eSLuke Drummond     if (i < args_in_reg) {
36480af0b9eSLuke Drummond       const RegisterInfo *reg =
36580af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
36680af0b9eSLuke Drummond       RegisterValue reg_val;
36780af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
36880af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
369f4786785SAidan Dodds     }
370f4786785SAidan Dodds     // arguments passed on the stack
371b9c1b51eSKate Stone     else {
372f4786785SAidan Dodds       // get the argument type size
373f4786785SAidan Dodds       const size_t arg_size = sizeof(uint64_t);
374f4786785SAidan Dodds       // clear all 64bits
375f4786785SAidan Dodds       arg.value = 0;
376f4786785SAidan Dodds       // read this argument from memory
377b9c1b51eSKate Stone       size_t bytes_read =
37880af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
37980af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
380f4786785SAidan Dodds       // advance the stack pointer
381f4786785SAidan Dodds       sp += arg_size;
382f4786785SAidan Dodds     }
383f4786785SAidan Dodds     // fail if we couldn't read this argument
384b9c1b51eSKate Stone     if (!success) {
385f4786785SAidan Dodds       if (log)
38617e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
38780af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
388f4786785SAidan Dodds       return false;
389f4786785SAidan Dodds     }
390f4786785SAidan Dodds   }
391f4786785SAidan Dodds   return true;
392f4786785SAidan Dodds }
393f4786785SAidan Dodds 
39480af0b9eSLuke Drummond bool GetArgs(ExecutionContext &exe_ctx, ArgItem *arg_list, size_t num_args) {
395f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
396f4786785SAidan Dodds 
397f4786785SAidan Dodds   // verify that we have a target
39880af0b9eSLuke Drummond   if (!exe_ctx.GetTargetPtr()) {
399f4786785SAidan Dodds     if (log)
400f4786785SAidan Dodds       log->Printf("%s - invalid target", __FUNCTION__);
401f4786785SAidan Dodds     return false;
402f4786785SAidan Dodds   }
403f4786785SAidan Dodds 
40480af0b9eSLuke Drummond   GetArgsCtx ctx = {exe_ctx.GetRegisterContext(), exe_ctx.GetProcessPtr()};
405f4786785SAidan Dodds   assert(ctx.reg_ctx && ctx.process);
406f4786785SAidan Dodds 
407f4786785SAidan Dodds   // dispatch based on architecture
40880af0b9eSLuke Drummond   switch (exe_ctx.GetTargetPtr()->GetArchitecture().GetMachine()) {
409f4786785SAidan Dodds   case llvm::Triple::ArchType::x86:
410f4786785SAidan Dodds     return GetArgsX86(ctx, arg_list, num_args);
411f4786785SAidan Dodds 
412f4786785SAidan Dodds   case llvm::Triple::ArchType::x86_64:
413f4786785SAidan Dodds     return GetArgsX86_64(ctx, arg_list, num_args);
414f4786785SAidan Dodds 
415f4786785SAidan Dodds   case llvm::Triple::ArchType::arm:
416f4786785SAidan Dodds     return GetArgsArm(ctx, arg_list, num_args);
417f4786785SAidan Dodds 
418f4786785SAidan Dodds   case llvm::Triple::ArchType::aarch64:
419f4786785SAidan Dodds     return GetArgsAarch64(ctx, arg_list, num_args);
420f4786785SAidan Dodds 
421f4786785SAidan Dodds   case llvm::Triple::ArchType::mipsel:
422f4786785SAidan Dodds     return GetArgsMipsel(ctx, arg_list, num_args);
423f4786785SAidan Dodds 
424f4786785SAidan Dodds   case llvm::Triple::ArchType::mips64el:
425f4786785SAidan Dodds     return GetArgsMips64el(ctx, arg_list, num_args);
426f4786785SAidan Dodds 
427f4786785SAidan Dodds   default:
428f4786785SAidan Dodds     // unsupported architecture
429b9c1b51eSKate Stone     if (log) {
430b9c1b51eSKate Stone       log->Printf(
431b9c1b51eSKate Stone           "%s - architecture not supported: '%s'", __FUNCTION__,
43280af0b9eSLuke Drummond           exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
433f4786785SAidan Dodds     }
434f4786785SAidan Dodds     return false;
435f4786785SAidan Dodds   }
436f4786785SAidan Dodds }
43700f56eebSLuke Drummond 
438b3bbcb12SLuke Drummond bool IsRenderScriptScriptModule(ModuleSP module) {
439b3bbcb12SLuke Drummond   if (!module)
440b3bbcb12SLuke Drummond     return false;
441b3bbcb12SLuke Drummond   return module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
442b3bbcb12SLuke Drummond                                                 eSymbolTypeData) != nullptr;
443b3bbcb12SLuke Drummond }
444b3bbcb12SLuke Drummond 
44500f56eebSLuke Drummond bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
44605097246SAdrian Prantl   // takes an argument of the form 'num[,num][,num]'. Where 'coord_s' is a
44705097246SAdrian Prantl   // comma separated 1,2 or 3-dimensional coordinate with the whitespace
44805097246SAdrian Prantl   // trimmed. Missing coordinates are defaulted to zero. If parsing of any
44905097246SAdrian Prantl   // elements fails the contents of &coord are undefined and `false` is
45005097246SAdrian Prantl   // returned, `true` otherwise
45100f56eebSLuke Drummond 
45200f56eebSLuke Drummond   RegularExpression regex;
45300f56eebSLuke Drummond   RegularExpression::Match regex_match(3);
45400f56eebSLuke Drummond 
45500f56eebSLuke Drummond   bool matched = false;
45600f56eebSLuke Drummond   if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+),([0-9]+)$")) &&
45700f56eebSLuke Drummond       regex.Execute(coord_s, &regex_match))
45800f56eebSLuke Drummond     matched = true;
45900f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([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]+)$")) &&
46300f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
46400f56eebSLuke Drummond     matched = true;
46500f56eebSLuke Drummond 
46600f56eebSLuke Drummond   if (!matched)
46700f56eebSLuke Drummond     return false;
46800f56eebSLuke Drummond 
46900f56eebSLuke Drummond   auto get_index = [&](int idx, uint32_t &i) -> bool {
47000f56eebSLuke Drummond     std::string group;
47100f56eebSLuke Drummond     errno = 0;
47200f56eebSLuke Drummond     if (regex_match.GetMatchAtIndex(coord_s.str().c_str(), idx + 1, group))
47300f56eebSLuke Drummond       return !llvm::StringRef(group).getAsInteger<uint32_t>(10, i);
47400f56eebSLuke Drummond     return true;
47500f56eebSLuke Drummond   };
47600f56eebSLuke Drummond 
47700f56eebSLuke Drummond   return get_index(0, coord.x) && get_index(1, coord.y) &&
47800f56eebSLuke Drummond          get_index(2, coord.z);
47900f56eebSLuke Drummond }
48021fed052SAidan Dodds 
48121fed052SAidan Dodds bool SkipPrologue(lldb::ModuleSP &module, Address &addr) {
48221fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
48321fed052SAidan Dodds   SymbolContext sc;
48421fed052SAidan Dodds   uint32_t resolved_flags =
48521fed052SAidan Dodds       module->ResolveSymbolContextForAddress(addr, eSymbolContextFunction, sc);
48621fed052SAidan Dodds   if (resolved_flags & eSymbolContextFunction) {
48721fed052SAidan Dodds     if (sc.function) {
48821fed052SAidan Dodds       const uint32_t offset = sc.function->GetPrologueByteSize();
48921fed052SAidan Dodds       ConstString name = sc.GetFunctionName();
49021fed052SAidan Dodds       if (offset)
49121fed052SAidan Dodds         addr.Slide(offset);
49221fed052SAidan Dodds       if (log)
49321fed052SAidan Dodds         log->Printf("%s: Prologue offset for %s is %" PRIu32, __FUNCTION__,
49421fed052SAidan Dodds                     name.AsCString(), offset);
49521fed052SAidan Dodds     }
49621fed052SAidan Dodds     return true;
49721fed052SAidan Dodds   } else
49821fed052SAidan Dodds     return false;
49921fed052SAidan Dodds }
500222b937cSEugene Zelenko } // anonymous namespace
50178f339d1SEwan Crawford 
502b9c1b51eSKate Stone // The ScriptDetails class collects data associated with a single script
503b9c1b51eSKate Stone // instance.
504b9c1b51eSKate Stone struct RenderScriptRuntime::ScriptDetails {
505222b937cSEugene Zelenko   ~ScriptDetails() = default;
50678f339d1SEwan Crawford 
507b9c1b51eSKate Stone   enum ScriptType { eScript, eScriptC };
50878f339d1SEwan Crawford 
50978f339d1SEwan Crawford   // The derived type of the script.
51078f339d1SEwan Crawford   empirical_type<ScriptType> type;
51178f339d1SEwan Crawford   // The name of the original source file.
51280af0b9eSLuke Drummond   empirical_type<std::string> res_name;
51378f339d1SEwan Crawford   // Path to script .so file on the device.
51480af0b9eSLuke Drummond   empirical_type<std::string> shared_lib;
51578f339d1SEwan Crawford   // Directory where kernel objects are cached on device.
51680af0b9eSLuke Drummond   empirical_type<std::string> cache_dir;
51778f339d1SEwan Crawford   // Pointer to the context which owns this script.
51878f339d1SEwan Crawford   empirical_type<lldb::addr_t> context;
51978f339d1SEwan Crawford   // Pointer to the script object itself.
52078f339d1SEwan Crawford   empirical_type<lldb::addr_t> script;
52178f339d1SEwan Crawford };
52278f339d1SEwan Crawford 
52380af0b9eSLuke Drummond // This Element class represents the Element object in RS, defining the type
52480af0b9eSLuke Drummond // associated with an Allocation.
525b9c1b51eSKate Stone struct RenderScriptRuntime::Element {
52615f2bd95SEwan Crawford   // Taken from rsDefines.h
527b9c1b51eSKate Stone   enum DataKind {
52815f2bd95SEwan Crawford     RS_KIND_USER,
52915f2bd95SEwan Crawford     RS_KIND_PIXEL_L = 7,
53015f2bd95SEwan Crawford     RS_KIND_PIXEL_A,
53115f2bd95SEwan Crawford     RS_KIND_PIXEL_LA,
53215f2bd95SEwan Crawford     RS_KIND_PIXEL_RGB,
53315f2bd95SEwan Crawford     RS_KIND_PIXEL_RGBA,
53415f2bd95SEwan Crawford     RS_KIND_PIXEL_DEPTH,
53515f2bd95SEwan Crawford     RS_KIND_PIXEL_YUV,
53615f2bd95SEwan Crawford     RS_KIND_INVALID = 100
53715f2bd95SEwan Crawford   };
53878f339d1SEwan Crawford 
53915f2bd95SEwan Crawford   // Taken from rsDefines.h
540b9c1b51eSKate Stone   enum DataType {
54115f2bd95SEwan Crawford     RS_TYPE_NONE = 0,
54215f2bd95SEwan Crawford     RS_TYPE_FLOAT_16,
54315f2bd95SEwan Crawford     RS_TYPE_FLOAT_32,
54415f2bd95SEwan Crawford     RS_TYPE_FLOAT_64,
54515f2bd95SEwan Crawford     RS_TYPE_SIGNED_8,
54615f2bd95SEwan Crawford     RS_TYPE_SIGNED_16,
54715f2bd95SEwan Crawford     RS_TYPE_SIGNED_32,
54815f2bd95SEwan Crawford     RS_TYPE_SIGNED_64,
54915f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_8,
55015f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_16,
55115f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_32,
55215f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_64,
5532e920715SEwan Crawford     RS_TYPE_BOOLEAN,
5542e920715SEwan Crawford 
5552e920715SEwan Crawford     RS_TYPE_UNSIGNED_5_6_5,
5562e920715SEwan Crawford     RS_TYPE_UNSIGNED_5_5_5_1,
5572e920715SEwan Crawford     RS_TYPE_UNSIGNED_4_4_4_4,
5582e920715SEwan Crawford 
5592e920715SEwan Crawford     RS_TYPE_MATRIX_4X4,
5602e920715SEwan Crawford     RS_TYPE_MATRIX_3X3,
5612e920715SEwan Crawford     RS_TYPE_MATRIX_2X2,
5622e920715SEwan Crawford 
5632e920715SEwan Crawford     RS_TYPE_ELEMENT = 1000,
5642e920715SEwan Crawford     RS_TYPE_TYPE,
5652e920715SEwan Crawford     RS_TYPE_ALLOCATION,
5662e920715SEwan Crawford     RS_TYPE_SAMPLER,
5672e920715SEwan Crawford     RS_TYPE_SCRIPT,
5682e920715SEwan Crawford     RS_TYPE_MESH,
5692e920715SEwan Crawford     RS_TYPE_PROGRAM_FRAGMENT,
5702e920715SEwan Crawford     RS_TYPE_PROGRAM_VERTEX,
5712e920715SEwan Crawford     RS_TYPE_PROGRAM_RASTER,
5722e920715SEwan Crawford     RS_TYPE_PROGRAM_STORE,
5732e920715SEwan Crawford     RS_TYPE_FONT,
5742e920715SEwan Crawford 
5752e920715SEwan Crawford     RS_TYPE_INVALID = 10000
57678f339d1SEwan Crawford   };
57778f339d1SEwan Crawford 
5788b244e21SEwan Crawford   std::vector<Element> children; // Child Element fields for structs
579b9c1b51eSKate Stone   empirical_type<lldb::addr_t>
580b9c1b51eSKate Stone       element_ptr; // Pointer to the RS Element of the Type
581b9c1b51eSKate Stone   empirical_type<DataType>
582b9c1b51eSKate Stone       type; // Type of each data pointer stored by the allocation
583b9c1b51eSKate Stone   empirical_type<DataKind>
584b9c1b51eSKate Stone       type_kind; // Defines pixel type if Allocation is created from an image
585b9c1b51eSKate Stone   empirical_type<uint32_t>
586b9c1b51eSKate Stone       type_vec_size; // Vector size of each data point, e.g '4' for uchar4
5878b244e21SEwan Crawford   empirical_type<uint32_t> field_count; // Number of Subelements
5888b244e21SEwan Crawford   empirical_type<uint32_t> datum_size;  // Size of a single Element with padding
5898b244e21SEwan Crawford   empirical_type<uint32_t> padding;     // Number of padding bytes
590b9c1b51eSKate Stone   empirical_type<uint32_t>
5914ebdee0aSBruce Mitchener       array_size;        // Number of items in array, only needed for structs
5928b244e21SEwan Crawford   ConstString type_name; // Name of type, only needed for structs
5938b244e21SEwan Crawford 
594b3f7f69dSAidan Dodds   static const ConstString &
595b3f7f69dSAidan Dodds   GetFallbackStructName(); // Print this as the type name of a struct Element
5968b244e21SEwan Crawford                            // If we can't resolve the actual struct name
5978b59062aSEwan Crawford 
59880af0b9eSLuke Drummond   bool ShouldRefresh() const {
5998b59062aSEwan Crawford     const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
600b9c1b51eSKate Stone     const bool valid_type =
601b9c1b51eSKate Stone         type.isValid() && type_vec_size.isValid() && type_kind.isValid();
6028b59062aSEwan Crawford     return !valid_ptr || !valid_type || !datum_size.isValid();
6038b59062aSEwan Crawford   }
6048b244e21SEwan Crawford };
6058b244e21SEwan Crawford 
6068b244e21SEwan Crawford // This AllocationDetails class collects data associated with a single
6078b244e21SEwan Crawford // allocation instance.
608b9c1b51eSKate Stone struct RenderScriptRuntime::AllocationDetails {
609b9c1b51eSKate Stone   struct Dimension {
61015f2bd95SEwan Crawford     uint32_t dim_1;
61115f2bd95SEwan Crawford     uint32_t dim_2;
61215f2bd95SEwan Crawford     uint32_t dim_3;
61380af0b9eSLuke Drummond     uint32_t cube_map;
61415f2bd95SEwan Crawford 
615b9c1b51eSKate Stone     Dimension() {
61615f2bd95SEwan Crawford       dim_1 = 0;
61715f2bd95SEwan Crawford       dim_2 = 0;
61815f2bd95SEwan Crawford       dim_3 = 0;
61980af0b9eSLuke Drummond       cube_map = 0;
62015f2bd95SEwan Crawford     }
62178f339d1SEwan Crawford   };
62278f339d1SEwan Crawford 
623b9c1b51eSKate Stone   // The FileHeader struct specifies the header we use for writing allocations
62480af0b9eSLuke Drummond   // to a binary file. Our format begins with the ASCII characters "RSAD",
62580af0b9eSLuke Drummond   // identifying the file as an allocation dump. Member variables dims and
62680af0b9eSLuke Drummond   // hdr_size are then written consecutively, immediately followed by an
62780af0b9eSLuke Drummond   // instance of the ElementHeader struct. Because Elements can contain
62880af0b9eSLuke Drummond   // subelements, there may be more than one instance of the ElementHeader
62980af0b9eSLuke Drummond   // struct. With this first instance being the root element, and the other
63080af0b9eSLuke Drummond   // instances being the root's descendants. To identify which instances are an
63105097246SAdrian Prantl   // ElementHeader's children, each struct is immediately followed by a
63205097246SAdrian Prantl   // sequence of consecutive offsets to the start of its child structs. These
63305097246SAdrian Prantl   // offsets are
63480af0b9eSLuke Drummond   // 4 bytes in size, and the 0 offset signifies no more children.
635b9c1b51eSKate Stone   struct FileHeader {
63655232f09SEwan Crawford     uint8_t ident[4];  // ASCII 'RSAD' identifying the file
63726e52a70SEwan Crawford     uint32_t dims[3];  // Dimensions
63826e52a70SEwan Crawford     uint16_t hdr_size; // Header size in bytes, including all element headers
63926e52a70SEwan Crawford   };
64026e52a70SEwan Crawford 
641b9c1b51eSKate Stone   struct ElementHeader {
64255232f09SEwan Crawford     uint16_t type;         // DataType enum
64355232f09SEwan Crawford     uint32_t kind;         // DataKind enum
64455232f09SEwan Crawford     uint32_t element_size; // Size of a single element, including padding
64526e52a70SEwan Crawford     uint16_t vector_size;  // Vector width
64626e52a70SEwan Crawford     uint32_t array_size;   // Number of elements in array
64755232f09SEwan Crawford   };
64855232f09SEwan Crawford 
64915f2bd95SEwan Crawford   // Monotonically increasing from 1
650b3f7f69dSAidan Dodds   static uint32_t ID;
65115f2bd95SEwan Crawford 
65205097246SAdrian Prantl   // Maps Allocation DataType enum and vector size to printable strings using
65305097246SAdrian Prantl   // mapping from RenderScript numerical types summary documentation
65415f2bd95SEwan Crawford   static const char *RsDataTypeToString[][4];
65515f2bd95SEwan Crawford 
65615f2bd95SEwan Crawford   // Maps Allocation DataKind enum to printable strings
65715f2bd95SEwan Crawford   static const char *RsDataKindToString[];
65815f2bd95SEwan Crawford 
659a0f08674SEwan Crawford   // Maps allocation types to format sizes for printing.
660b3f7f69dSAidan Dodds   static const uint32_t RSTypeToFormat[][3];
661a0f08674SEwan Crawford 
66215f2bd95SEwan Crawford   // Give each allocation an ID as a way
66315f2bd95SEwan Crawford   // for commands to reference it.
664b3f7f69dSAidan Dodds   const uint32_t id;
66515f2bd95SEwan Crawford 
66680af0b9eSLuke Drummond   // Allocation Element type
66780af0b9eSLuke Drummond   RenderScriptRuntime::Element element;
66880af0b9eSLuke Drummond   // Dimensions of the Allocation
66980af0b9eSLuke Drummond   empirical_type<Dimension> dimension;
67080af0b9eSLuke Drummond   // Pointer to address of the RS Allocation
67180af0b9eSLuke Drummond   empirical_type<lldb::addr_t> address;
67280af0b9eSLuke Drummond   // Pointer to the data held by the Allocation
67380af0b9eSLuke Drummond   empirical_type<lldb::addr_t> data_ptr;
67480af0b9eSLuke Drummond   // Pointer to the RS Type of the Allocation
67580af0b9eSLuke Drummond   empirical_type<lldb::addr_t> type_ptr;
67680af0b9eSLuke Drummond   // Pointer to the RS Context of the Allocation
67780af0b9eSLuke Drummond   empirical_type<lldb::addr_t> context;
67880af0b9eSLuke Drummond   // Size of the allocation
67980af0b9eSLuke Drummond   empirical_type<uint32_t> size;
68080af0b9eSLuke Drummond   // Stride between rows of the allocation
68180af0b9eSLuke Drummond   empirical_type<uint32_t> stride;
68215f2bd95SEwan Crawford 
68315f2bd95SEwan Crawford   // Give each allocation an id, so we can reference it in user commands.
684b3f7f69dSAidan Dodds   AllocationDetails() : id(ID++) {}
6858b59062aSEwan Crawford 
68680af0b9eSLuke Drummond   bool ShouldRefresh() const {
6878b59062aSEwan Crawford     bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
6888b59062aSEwan Crawford     valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
689b9c1b51eSKate Stone     return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
69080af0b9eSLuke Drummond            element.ShouldRefresh();
6918b59062aSEwan Crawford   }
69215f2bd95SEwan Crawford };
69315f2bd95SEwan Crawford 
694b9c1b51eSKate Stone const ConstString &RenderScriptRuntime::Element::GetFallbackStructName() {
695fe06b5adSAdrian McCarthy   static const ConstString FallbackStructName("struct");
696fe06b5adSAdrian McCarthy   return FallbackStructName;
697fe06b5adSAdrian McCarthy }
6988b244e21SEwan Crawford 
699b3f7f69dSAidan Dodds uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
70015f2bd95SEwan Crawford 
701b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
702b9c1b51eSKate Stone     "User",       "Undefined",   "Undefined", "Undefined",
703b9c1b51eSKate Stone     "Undefined",  "Undefined",   "Undefined", // Enum jumps from 0 to 7
704b3f7f69dSAidan Dodds     "L Pixel",    "A Pixel",     "LA Pixel",  "RGB Pixel",
705b3f7f69dSAidan Dodds     "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
70615f2bd95SEwan Crawford 
707b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
70815f2bd95SEwan Crawford     {"None", "None", "None", "None"},
70915f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
71015f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
71115f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
71215f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
71315f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
71415f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
71515f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
71615f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
71715f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
71815f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
71915f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
7202e920715SEwan Crawford     {"bool", "bool2", "bool3", "bool4"},
7212e920715SEwan Crawford     {"packed_565", "packed_565", "packed_565", "packed_565"},
7222e920715SEwan Crawford     {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
7232e920715SEwan Crawford     {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
7242e920715SEwan Crawford     {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
7252e920715SEwan Crawford     {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
7262e920715SEwan Crawford     {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
7272e920715SEwan Crawford 
7282e920715SEwan Crawford     // Handlers
7292e920715SEwan Crawford     {"RS Element", "RS Element", "RS Element", "RS Element"},
7302e920715SEwan Crawford     {"RS Type", "RS Type", "RS Type", "RS Type"},
7312e920715SEwan Crawford     {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
7322e920715SEwan Crawford     {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
7332e920715SEwan Crawford     {"RS Script", "RS Script", "RS Script", "RS Script"},
7342e920715SEwan Crawford 
7352e920715SEwan Crawford     // Deprecated
7362e920715SEwan Crawford     {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
737b9c1b51eSKate Stone     {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
738b9c1b51eSKate Stone      "RS Program Fragment"},
739b9c1b51eSKate Stone     {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
740b9c1b51eSKate Stone      "RS Program Vertex"},
741b9c1b51eSKate Stone     {"RS Program Raster", "RS Program Raster", "RS Program Raster",
742b9c1b51eSKate Stone      "RS Program Raster"},
743b9c1b51eSKate Stone     {"RS Program Store", "RS Program Store", "RS Program Store",
744b9c1b51eSKate Stone      "RS Program Store"},
745b3f7f69dSAidan Dodds     {"RS Font", "RS Font", "RS Font", "RS Font"}};
74678f339d1SEwan Crawford 
747a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
748b9c1b51eSKate Stone enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
749a0f08674SEwan Crawford 
750b9c1b51eSKate Stone // { format enum of single element, format enum of element vector, size of
751b9c1b51eSKate Stone // element}
752b3f7f69dSAidan Dodds const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
75380af0b9eSLuke Drummond     // RS_TYPE_NONE
75480af0b9eSLuke Drummond     {eFormatHex, eFormatHex, 1},
75580af0b9eSLuke Drummond     // RS_TYPE_FLOAT_16
75680af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat16, 2},
75780af0b9eSLuke Drummond     // RS_TYPE_FLOAT_32
75880af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
75980af0b9eSLuke Drummond     // RS_TYPE_FLOAT_64
76080af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
76180af0b9eSLuke Drummond     // RS_TYPE_SIGNED_8
76280af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
76380af0b9eSLuke Drummond     // RS_TYPE_SIGNED_16
76480af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
76580af0b9eSLuke Drummond     // RS_TYPE_SIGNED_32
76680af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
76780af0b9eSLuke Drummond     // RS_TYPE_SIGNED_64
76880af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
76980af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_8
77080af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
77180af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_16
77280af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
77380af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_32
77480af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
77580af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_64
77680af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
77780af0b9eSLuke Drummond     // RS_TYPE_BOOL
77880af0b9eSLuke Drummond     {eFormatBoolean, eFormatBoolean, 1},
77980af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_5_6_5
78080af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
78180af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_5_5_5_1
78280af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
78380af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_4_4_4_4
78480af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
78580af0b9eSLuke Drummond     // RS_TYPE_MATRIX_4X4
78680af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
78780af0b9eSLuke Drummond     // RS_TYPE_MATRIX_3X3
78880af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
78980af0b9eSLuke Drummond     // RS_TYPE_MATRIX_2X2
79080af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
791a0f08674SEwan Crawford 
7925ec532a9SColin Riley //------------------------------------------------------------------
7935ec532a9SColin Riley // Static Functions
7945ec532a9SColin Riley //------------------------------------------------------------------
7955ec532a9SColin Riley LanguageRuntime *
796b9c1b51eSKate Stone RenderScriptRuntime::CreateInstance(Process *process,
797b9c1b51eSKate Stone                                     lldb::LanguageType language) {
7985ec532a9SColin Riley 
7995ec532a9SColin Riley   if (language == eLanguageTypeExtRenderScript)
8005ec532a9SColin Riley     return new RenderScriptRuntime(process);
8015ec532a9SColin Riley   else
802b3f7f69dSAidan Dodds     return nullptr;
8035ec532a9SColin Riley }
8045ec532a9SColin Riley 
80580af0b9eSLuke Drummond // Callback with a module to search for matching symbols. We first check that
80680af0b9eSLuke Drummond // the module contains RS kernels. Then look for a symbol which matches our
80780af0b9eSLuke Drummond // kernel name. The breakpoint address is finally set using the address of this
80880af0b9eSLuke Drummond // symbol.
80998156583SEwan Crawford Searcher::CallbackReturn
810b9c1b51eSKate Stone RSBreakpointResolver::SearchCallback(SearchFilter &filter,
811b9c1b51eSKate Stone                                      SymbolContext &context, Address *, bool) {
81298156583SEwan Crawford   ModuleSP module = context.module_sp;
81398156583SEwan Crawford 
814b3bbcb12SLuke Drummond   if (!module || !IsRenderScriptScriptModule(module))
81598156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
81698156583SEwan Crawford 
817b9c1b51eSKate Stone   // Attempt to set a breakpoint on the kernel name symbol within the module
81880af0b9eSLuke Drummond   // library. If it's not found, it's likely debug info is unavailable - try to
81980af0b9eSLuke Drummond   // set a breakpoint on <name>.expand.
820b9c1b51eSKate Stone   const Symbol *kernel_sym =
821b9c1b51eSKate Stone       module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
822b9c1b51eSKate Stone   if (!kernel_sym) {
82398156583SEwan Crawford     std::string kernel_name_expanded(m_kernel_name.AsCString());
82498156583SEwan Crawford     kernel_name_expanded.append(".expand");
825b9c1b51eSKate Stone     kernel_sym = module->FindFirstSymbolWithNameAndType(
826b9c1b51eSKate Stone         ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
82798156583SEwan Crawford   }
82898156583SEwan Crawford 
829b9c1b51eSKate Stone   if (kernel_sym) {
83098156583SEwan Crawford     Address bp_addr = kernel_sym->GetAddress();
83198156583SEwan Crawford     if (filter.AddressPasses(bp_addr))
83298156583SEwan Crawford       m_breakpoint->AddLocation(bp_addr);
83398156583SEwan Crawford   }
83498156583SEwan Crawford 
83598156583SEwan Crawford   return Searcher::eCallbackReturnContinue;
83698156583SEwan Crawford }
83798156583SEwan Crawford 
838b3bbcb12SLuke Drummond Searcher::CallbackReturn
839b3bbcb12SLuke Drummond RSReduceBreakpointResolver::SearchCallback(lldb_private::SearchFilter &filter,
840b3bbcb12SLuke Drummond                                            lldb_private::SymbolContext &context,
841b3bbcb12SLuke Drummond                                            Address *, bool) {
842b3bbcb12SLuke Drummond   // We need to have access to the list of reductions currently parsed, as
84305097246SAdrian Prantl   // reduce names don't actually exist as symbols in a module. They are only
84405097246SAdrian Prantl   // identifiable by parsing the .rs.info packet, or finding the expand symbol.
84505097246SAdrian Prantl   // We therefore need access to the list of parsed rs modules to properly
84605097246SAdrian Prantl   // resolve reduction names.
847b3bbcb12SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
848b3bbcb12SLuke Drummond   ModuleSP module = context.module_sp;
849b3bbcb12SLuke Drummond 
850b3bbcb12SLuke Drummond   if (!module || !IsRenderScriptScriptModule(module))
851b3bbcb12SLuke Drummond     return Searcher::eCallbackReturnContinue;
852b3bbcb12SLuke Drummond 
853b3bbcb12SLuke Drummond   if (!m_rsmodules)
854b3bbcb12SLuke Drummond     return Searcher::eCallbackReturnContinue;
855b3bbcb12SLuke Drummond 
856b3bbcb12SLuke Drummond   for (const auto &module_desc : *m_rsmodules) {
857b3bbcb12SLuke Drummond     if (module_desc->m_module != module)
858b3bbcb12SLuke Drummond       continue;
859b3bbcb12SLuke Drummond 
860b3bbcb12SLuke Drummond     for (const auto &reduction : module_desc->m_reductions) {
861b3bbcb12SLuke Drummond       if (reduction.m_reduce_name != m_reduce_name)
862b3bbcb12SLuke Drummond         continue;
863b3bbcb12SLuke Drummond 
864b3bbcb12SLuke Drummond       std::array<std::pair<ConstString, int>, 5> funcs{
865b3bbcb12SLuke Drummond           {{reduction.m_init_name, eKernelTypeInit},
866b3bbcb12SLuke Drummond            {reduction.m_accum_name, eKernelTypeAccum},
867b3bbcb12SLuke Drummond            {reduction.m_comb_name, eKernelTypeComb},
868b3bbcb12SLuke Drummond            {reduction.m_outc_name, eKernelTypeOutC},
869b3bbcb12SLuke Drummond            {reduction.m_halter_name, eKernelTypeHalter}}};
870b3bbcb12SLuke Drummond 
871b3bbcb12SLuke Drummond       for (const auto &kernel : funcs) {
872b3bbcb12SLuke Drummond         // Skip constituent functions that don't match our spec
873b3bbcb12SLuke Drummond         if (!(m_kernel_types & kernel.second))
874b3bbcb12SLuke Drummond           continue;
875b3bbcb12SLuke Drummond 
876b3bbcb12SLuke Drummond         const auto kernel_name = kernel.first;
877b3bbcb12SLuke Drummond         const auto symbol = module->FindFirstSymbolWithNameAndType(
878b3bbcb12SLuke Drummond             kernel_name, eSymbolTypeCode);
879b3bbcb12SLuke Drummond         if (!symbol)
880b3bbcb12SLuke Drummond           continue;
881b3bbcb12SLuke Drummond 
882b3bbcb12SLuke Drummond         auto address = symbol->GetAddress();
883b3bbcb12SLuke Drummond         if (filter.AddressPasses(address)) {
884b3bbcb12SLuke Drummond           bool new_bp;
88581fc84faSLuke Drummond           if (!SkipPrologue(module, address)) {
88681fc84faSLuke Drummond             if (log)
88781fc84faSLuke Drummond               log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
88881fc84faSLuke Drummond           }
889b3bbcb12SLuke Drummond           m_breakpoint->AddLocation(address, &new_bp);
890b3bbcb12SLuke Drummond           if (log)
891b3bbcb12SLuke Drummond             log->Printf("%s: %s reduction breakpoint on %s in %s", __FUNCTION__,
892b3bbcb12SLuke Drummond                         new_bp ? "new" : "existing", kernel_name.GetCString(),
893b3bbcb12SLuke Drummond                         address.GetModule()->GetFileSpec().GetCString());
894b3bbcb12SLuke Drummond         }
895b3bbcb12SLuke Drummond       }
896b3bbcb12SLuke Drummond     }
897b3bbcb12SLuke Drummond   }
898b3bbcb12SLuke Drummond   return eCallbackReturnContinue;
899b3bbcb12SLuke Drummond }
900b3bbcb12SLuke Drummond 
90121fed052SAidan Dodds Searcher::CallbackReturn RSScriptGroupBreakpointResolver::SearchCallback(
90221fed052SAidan Dodds     SearchFilter &filter, SymbolContext &context, Address *addr,
90321fed052SAidan Dodds     bool containing) {
90421fed052SAidan Dodds 
90521fed052SAidan Dodds   if (!m_breakpoint)
90621fed052SAidan Dodds     return eCallbackReturnContinue;
90721fed052SAidan Dodds 
90821fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
90921fed052SAidan Dodds   ModuleSP &module = context.module_sp;
91021fed052SAidan Dodds 
91121fed052SAidan Dodds   if (!module || !IsRenderScriptScriptModule(module))
91221fed052SAidan Dodds     return Searcher::eCallbackReturnContinue;
91321fed052SAidan Dodds 
91421fed052SAidan Dodds   std::vector<std::string> names;
91521fed052SAidan Dodds   m_breakpoint->GetNames(names);
91621fed052SAidan Dodds   if (names.empty())
91721fed052SAidan Dodds     return eCallbackReturnContinue;
91821fed052SAidan Dodds 
91921fed052SAidan Dodds   for (auto &name : names) {
92021fed052SAidan Dodds     const RSScriptGroupDescriptorSP sg = FindScriptGroup(ConstString(name));
92121fed052SAidan Dodds     if (!sg) {
92221fed052SAidan Dodds       if (log)
92321fed052SAidan Dodds         log->Printf("%s: could not find script group for %s", __FUNCTION__,
92421fed052SAidan Dodds                     name.c_str());
92521fed052SAidan Dodds       continue;
92621fed052SAidan Dodds     }
92721fed052SAidan Dodds 
92821fed052SAidan Dodds     if (log)
92921fed052SAidan Dodds       log->Printf("%s: Found ScriptGroup for %s", __FUNCTION__, name.c_str());
93021fed052SAidan Dodds 
93121fed052SAidan Dodds     for (const RSScriptGroupDescriptor::Kernel &k : sg->m_kernels) {
93221fed052SAidan Dodds       if (log) {
93321fed052SAidan Dodds         log->Printf("%s: Adding breakpoint for %s", __FUNCTION__,
93421fed052SAidan Dodds                     k.m_name.AsCString());
93521fed052SAidan Dodds         log->Printf("%s: Kernel address 0x%" PRIx64, __FUNCTION__, k.m_addr);
93621fed052SAidan Dodds       }
93721fed052SAidan Dodds 
93821fed052SAidan Dodds       const lldb_private::Symbol *sym =
93921fed052SAidan Dodds           module->FindFirstSymbolWithNameAndType(k.m_name, eSymbolTypeCode);
94021fed052SAidan Dodds       if (!sym) {
94121fed052SAidan Dodds         if (log)
94221fed052SAidan Dodds           log->Printf("%s: Unable to find symbol for %s", __FUNCTION__,
94321fed052SAidan Dodds                       k.m_name.AsCString());
94421fed052SAidan Dodds         continue;
94521fed052SAidan Dodds       }
94621fed052SAidan Dodds 
94721fed052SAidan Dodds       if (log) {
94821fed052SAidan Dodds         log->Printf("%s: Found symbol name is %s", __FUNCTION__,
94921fed052SAidan Dodds                     sym->GetName().AsCString());
95021fed052SAidan Dodds       }
95121fed052SAidan Dodds 
95221fed052SAidan Dodds       auto address = sym->GetAddress();
95321fed052SAidan Dodds       if (!SkipPrologue(module, address)) {
95421fed052SAidan Dodds         if (log)
95521fed052SAidan Dodds           log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
95621fed052SAidan Dodds       }
95721fed052SAidan Dodds 
95821fed052SAidan Dodds       bool new_bp;
95921fed052SAidan Dodds       m_breakpoint->AddLocation(address, &new_bp);
96021fed052SAidan Dodds 
96121fed052SAidan Dodds       if (log)
96221fed052SAidan Dodds         log->Printf("%s: Placed %sbreakpoint on %s", __FUNCTION__,
96321fed052SAidan Dodds                     new_bp ? "new " : "", k.m_name.AsCString());
96421fed052SAidan Dodds 
96505097246SAdrian Prantl       // exit after placing the first breakpoint if we do not intend to stop on
96605097246SAdrian Prantl       // all kernels making up this script group
96721fed052SAidan Dodds       if (!m_stop_on_all)
96821fed052SAidan Dodds         break;
96921fed052SAidan Dodds     }
97021fed052SAidan Dodds   }
97121fed052SAidan Dodds 
97221fed052SAidan Dodds   return eCallbackReturnContinue;
97321fed052SAidan Dodds }
97421fed052SAidan Dodds 
975b9c1b51eSKate Stone void RenderScriptRuntime::Initialize() {
976b9c1b51eSKate Stone   PluginManager::RegisterPlugin(GetPluginNameStatic(),
977b9c1b51eSKate Stone                                 "RenderScript language support", CreateInstance,
978b3f7f69dSAidan Dodds                                 GetCommandObject);
9795ec532a9SColin Riley }
9805ec532a9SColin Riley 
981b9c1b51eSKate Stone void RenderScriptRuntime::Terminate() {
9825ec532a9SColin Riley   PluginManager::UnregisterPlugin(CreateInstance);
9835ec532a9SColin Riley }
9845ec532a9SColin Riley 
985b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginNameStatic() {
98680af0b9eSLuke Drummond   static ConstString plugin_name("renderscript");
98780af0b9eSLuke Drummond   return plugin_name;
9885ec532a9SColin Riley }
9895ec532a9SColin Riley 
990ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
991b9c1b51eSKate Stone RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
992b9c1b51eSKate Stone   if (module_sp) {
993b3bbcb12SLuke Drummond     if (IsRenderScriptScriptModule(module_sp))
994ef20b08fSColin Riley       return eModuleKindKernelObj;
9954640cde1SColin Riley 
9964640cde1SColin Riley     // Is this the main RS runtime library
9974640cde1SColin Riley     const ConstString rs_lib("libRS.so");
998b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
9994640cde1SColin Riley       return eModuleKindLibRS;
10004640cde1SColin Riley     }
10014640cde1SColin Riley 
10024640cde1SColin Riley     const ConstString rs_driverlib("libRSDriver.so");
1003b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
10044640cde1SColin Riley       return eModuleKindDriver;
10054640cde1SColin Riley     }
10064640cde1SColin Riley 
100715f2bd95SEwan Crawford     const ConstString rs_cpureflib("libRSCpuRef.so");
1008b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
10094640cde1SColin Riley       return eModuleKindImpl;
10104640cde1SColin Riley     }
1011ef20b08fSColin Riley   }
1012ef20b08fSColin Riley   return eModuleKindIgnored;
1013ef20b08fSColin Riley }
1014ef20b08fSColin Riley 
1015b9c1b51eSKate Stone bool RenderScriptRuntime::IsRenderScriptModule(
1016b9c1b51eSKate Stone     const lldb::ModuleSP &module_sp) {
1017ef20b08fSColin Riley   return GetModuleKind(module_sp) != eModuleKindIgnored;
1018ef20b08fSColin Riley }
1019ef20b08fSColin Riley 
1020b9c1b51eSKate Stone void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
1021bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1022ef20b08fSColin Riley 
1023ef20b08fSColin Riley   size_t num_modules = module_list.GetSize();
1024b9c1b51eSKate Stone   for (size_t i = 0; i < num_modules; i++) {
1025ef20b08fSColin Riley     auto mod = module_list.GetModuleAtIndex(i);
1026b9c1b51eSKate Stone     if (IsRenderScriptModule(mod)) {
1027ef20b08fSColin Riley       LoadModule(mod);
1028ef20b08fSColin Riley     }
1029ef20b08fSColin Riley   }
1030ef20b08fSColin Riley }
1031ef20b08fSColin Riley 
10325ec532a9SColin Riley //------------------------------------------------------------------
10335ec532a9SColin Riley // PluginInterface protocol
10345ec532a9SColin Riley //------------------------------------------------------------------
1035b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginName() {
10365ec532a9SColin Riley   return GetPluginNameStatic();
10375ec532a9SColin Riley }
10385ec532a9SColin Riley 
1039b9c1b51eSKate Stone uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; }
10405ec532a9SColin Riley 
1041b9c1b51eSKate Stone bool RenderScriptRuntime::IsVTableName(const char *name) { return false; }
10425ec532a9SColin Riley 
1043b9c1b51eSKate Stone bool RenderScriptRuntime::GetDynamicTypeAndAddress(
1044b9c1b51eSKate Stone     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
10455f57b6eeSEnrico Granata     TypeAndOrName &class_type_or_name, Address &address,
1046b9c1b51eSKate Stone     Value::ValueType &value_type) {
10475ec532a9SColin Riley   return false;
10485ec532a9SColin Riley }
10495ec532a9SColin Riley 
1050c74275bcSEnrico Granata TypeAndOrName
1051b9c1b51eSKate Stone RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
1052b9c1b51eSKate Stone                                       ValueObject &static_value) {
1053c74275bcSEnrico Granata   return type_and_or_name;
1054c74275bcSEnrico Granata }
1055c74275bcSEnrico Granata 
1056b9c1b51eSKate Stone bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
10575ec532a9SColin Riley   return false;
10585ec532a9SColin Riley }
10595ec532a9SColin Riley 
10605ec532a9SColin Riley lldb::BreakpointResolverSP
106180af0b9eSLuke Drummond RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bp, bool catch_bp,
1062b9c1b51eSKate Stone                                              bool throw_bp) {
10635ec532a9SColin Riley   BreakpointResolverSP resolver_sp;
10645ec532a9SColin Riley   return resolver_sp;
10655ec532a9SColin Riley }
10665ec532a9SColin Riley 
1067b9c1b51eSKate Stone const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
1068b9c1b51eSKate Stone     {
10694640cde1SColin Riley         // rsdScript
1070b9c1b51eSKate Stone         {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
1071b9c1b51eSKate Stone                           "NS0_7ScriptCEPKcS7_PKhjj",
1072b9c1b51eSKate Stone          "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
1073b9c1b51eSKate Stone          "7ScriptCEPKcS7_PKhmj",
1074b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1075b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInit},
1076b9c1b51eSKate Stone         {"rsdScriptInvokeForEachMulti",
1077b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1078b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
1079b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1080b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
1081b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1082b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
1083b9c1b51eSKate Stone         {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
1084b9c1b51eSKate Stone                                   "script7ContextEPKNS0_6ScriptEjPvj",
1085b9c1b51eSKate Stone          "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
1086b9c1b51eSKate Stone          "6ScriptEjPvm",
1087b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1088b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
10894640cde1SColin Riley 
10904640cde1SColin Riley         // rsdAllocation
1091b9c1b51eSKate Stone         {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
1092b9c1b51eSKate Stone                               "ontextEPNS0_10AllocationEb",
1093b9c1b51eSKate Stone          "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
1094b9c1b51eSKate Stone          "10AllocationEb",
1095b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1096b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
1097b9c1b51eSKate Stone         {"rsdAllocationRead2D",
1098b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1099b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1100b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1101b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1102b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1103b9c1b51eSKate Stone         {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1104b9c1b51eSKate Stone                                  "ript7ContextEPNS0_10AllocationE",
1105b9c1b51eSKate Stone          "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1106b9c1b51eSKate Stone          "10AllocationE",
1107b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1108b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
110921fed052SAidan Dodds 
111021fed052SAidan Dodds         // renderscript script groups
111121fed052SAidan Dodds         {"rsdDebugHintScriptGroup2", "_ZN7android12renderscript21debugHintScrip"
111221fed052SAidan Dodds                                      "tGroup2EPKcjPKPFvPK24RsExpandKernelDriver"
111321fed052SAidan Dodds                                      "InfojjjEj",
111421fed052SAidan Dodds          "_ZN7android12renderscript21debugHintScriptGroup2EPKcjPKPFvPK24RsExpan"
111521fed052SAidan Dodds          "dKernelDriverInfojjjEj",
111621fed052SAidan Dodds          0, RenderScriptRuntime::eModuleKindImpl,
111721fed052SAidan Dodds          &lldb_private::RenderScriptRuntime::CaptureDebugHintScriptGroup2}};
11184640cde1SColin Riley 
1119b9c1b51eSKate Stone const size_t RenderScriptRuntime::s_runtimeHookCount =
1120b9c1b51eSKate Stone     sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
11214640cde1SColin Riley 
1122b9c1b51eSKate Stone bool RenderScriptRuntime::HookCallback(void *baton,
1123b9c1b51eSKate Stone                                        StoppointCallbackContext *ctx,
1124b9c1b51eSKate Stone                                        lldb::user_id_t break_id,
1125b9c1b51eSKate Stone                                        lldb::user_id_t break_loc_id) {
112680af0b9eSLuke Drummond   RuntimeHook *hook = (RuntimeHook *)baton;
112780af0b9eSLuke Drummond   ExecutionContext exe_ctx(ctx->exe_ctx_ref);
11284640cde1SColin Riley 
1129b3f7f69dSAidan Dodds   RenderScriptRuntime *lang_rt =
113080af0b9eSLuke Drummond       (RenderScriptRuntime *)exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1131b9c1b51eSKate Stone           eLanguageTypeExtRenderScript);
11324640cde1SColin Riley 
113380af0b9eSLuke Drummond   lang_rt->HookCallback(hook, exe_ctx);
11344640cde1SColin Riley 
11354640cde1SColin Riley   return false;
11364640cde1SColin Riley }
11374640cde1SColin Riley 
113880af0b9eSLuke Drummond void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
113980af0b9eSLuke Drummond                                        ExecutionContext &exe_ctx) {
11404640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11414640cde1SColin Riley 
11424640cde1SColin Riley   if (log)
114380af0b9eSLuke Drummond     log->Printf("%s - '%s'", __FUNCTION__, hook->defn->name);
11444640cde1SColin Riley 
114580af0b9eSLuke Drummond   if (hook->defn->grabber) {
114680af0b9eSLuke Drummond     (this->*(hook->defn->grabber))(hook, exe_ctx);
11474640cde1SColin Riley   }
11484640cde1SColin Riley }
11494640cde1SColin Riley 
115021fed052SAidan Dodds void RenderScriptRuntime::CaptureDebugHintScriptGroup2(
115121fed052SAidan Dodds     RuntimeHook *hook_info, ExecutionContext &context) {
115221fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
115321fed052SAidan Dodds 
115421fed052SAidan Dodds   enum {
115521fed052SAidan Dodds     eGroupName = 0,
115621fed052SAidan Dodds     eGroupNameSize,
115721fed052SAidan Dodds     eKernel,
115821fed052SAidan Dodds     eKernelCount,
115921fed052SAidan Dodds   };
116021fed052SAidan Dodds 
116121fed052SAidan Dodds   std::array<ArgItem, 4> args{{
116221fed052SAidan Dodds       {ArgItem::ePointer, 0}, // const char         *groupName
116321fed052SAidan Dodds       {ArgItem::eInt32, 0},   // const uint32_t      groupNameSize
116421fed052SAidan Dodds       {ArgItem::ePointer, 0}, // const ExpandFuncTy *kernel
116521fed052SAidan Dodds       {ArgItem::eInt32, 0},   // const uint32_t      kernelCount
116621fed052SAidan Dodds   }};
116721fed052SAidan Dodds 
116821fed052SAidan Dodds   if (!GetArgs(context, args.data(), args.size())) {
116921fed052SAidan Dodds     if (log)
117021fed052SAidan Dodds       log->Printf("%s - Error while reading the function parameters",
117121fed052SAidan Dodds                   __FUNCTION__);
117221fed052SAidan Dodds     return;
117321fed052SAidan Dodds   } else if (log) {
117421fed052SAidan Dodds     log->Printf("%s - groupName    : 0x%" PRIx64, __FUNCTION__,
117521fed052SAidan Dodds                 addr_t(args[eGroupName]));
117621fed052SAidan Dodds     log->Printf("%s - groupNameSize: %" PRIu64, __FUNCTION__,
117721fed052SAidan Dodds                 uint64_t(args[eGroupNameSize]));
117821fed052SAidan Dodds     log->Printf("%s - kernel       : 0x%" PRIx64, __FUNCTION__,
117921fed052SAidan Dodds                 addr_t(args[eKernel]));
118021fed052SAidan Dodds     log->Printf("%s - kernelCount  : %" PRIu64, __FUNCTION__,
118121fed052SAidan Dodds                 uint64_t(args[eKernelCount]));
118221fed052SAidan Dodds   }
118321fed052SAidan Dodds 
118421fed052SAidan Dodds   // parse script group name
118521fed052SAidan Dodds   ConstString group_name;
118621fed052SAidan Dodds   {
118797206d57SZachary Turner     Status err;
118821fed052SAidan Dodds     const uint64_t len = uint64_t(args[eGroupNameSize]);
118921fed052SAidan Dodds     std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]);
119021fed052SAidan Dodds     m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err);
119121fed052SAidan Dodds     buffer.get()[len] = '\0';
119221fed052SAidan Dodds     if (!err.Success()) {
119321fed052SAidan Dodds       if (log)
119421fed052SAidan Dodds         log->Printf("Error reading scriptgroup name from target");
119521fed052SAidan Dodds       return;
119621fed052SAidan Dodds     } else {
119721fed052SAidan Dodds       if (log)
119821fed052SAidan Dodds         log->Printf("Extracted scriptgroup name %s", buffer.get());
119921fed052SAidan Dodds     }
120021fed052SAidan Dodds     // write back the script group name
120121fed052SAidan Dodds     group_name.SetCString(buffer.get());
120221fed052SAidan Dodds   }
120321fed052SAidan Dodds 
120421fed052SAidan Dodds   // create or access existing script group
120521fed052SAidan Dodds   RSScriptGroupDescriptorSP group;
120621fed052SAidan Dodds   {
120721fed052SAidan Dodds     // search for existing script group
120821fed052SAidan Dodds     for (auto sg : m_scriptGroups) {
120921fed052SAidan Dodds       if (sg->m_name == group_name) {
121021fed052SAidan Dodds         group = sg;
121121fed052SAidan Dodds         break;
121221fed052SAidan Dodds       }
121321fed052SAidan Dodds     }
121421fed052SAidan Dodds     if (!group) {
121521fed052SAidan Dodds       group.reset(new RSScriptGroupDescriptor);
121621fed052SAidan Dodds       group->m_name = group_name;
121721fed052SAidan Dodds       m_scriptGroups.push_back(group);
121821fed052SAidan Dodds     } else {
121921fed052SAidan Dodds       // already have this script group
122021fed052SAidan Dodds       if (log)
122121fed052SAidan Dodds         log->Printf("Attempt to add duplicate script group %s",
122221fed052SAidan Dodds                     group_name.AsCString());
122321fed052SAidan Dodds       return;
122421fed052SAidan Dodds     }
122521fed052SAidan Dodds   }
122621fed052SAidan Dodds   assert(group);
122721fed052SAidan Dodds 
122821fed052SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
122921fed052SAidan Dodds   std::vector<addr_t> kernels;
123021fed052SAidan Dodds   // parse kernel addresses in script group
123121fed052SAidan Dodds   for (uint64_t i = 0; i < uint64_t(args[eKernelCount]); ++i) {
123221fed052SAidan Dodds     RSScriptGroupDescriptor::Kernel kernel;
123321fed052SAidan Dodds     // extract script group kernel addresses from the target
123421fed052SAidan Dodds     const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size;
123521fed052SAidan Dodds     uint64_t kernel_addr = 0;
123697206d57SZachary Turner     Status err;
123721fed052SAidan Dodds     size_t read =
123821fed052SAidan Dodds         m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err);
123921fed052SAidan Dodds     if (!err.Success() || read != target_ptr_size) {
124021fed052SAidan Dodds       if (log)
124121fed052SAidan Dodds         log->Printf("Error parsing kernel address %" PRIu64 " in script group",
124221fed052SAidan Dodds                     i);
124321fed052SAidan Dodds       return;
124421fed052SAidan Dodds     }
124521fed052SAidan Dodds     if (log)
124621fed052SAidan Dodds       log->Printf("Extracted scriptgroup kernel address - 0x%" PRIx64,
124721fed052SAidan Dodds                   kernel_addr);
124821fed052SAidan Dodds     kernel.m_addr = kernel_addr;
124921fed052SAidan Dodds 
125021fed052SAidan Dodds     // try to resolve the associated kernel name
125121fed052SAidan Dodds     if (!ResolveKernelName(kernel.m_addr, kernel.m_name)) {
125221fed052SAidan Dodds       if (log)
125321fed052SAidan Dodds         log->Printf("Parsed scriptgroup kernel %" PRIu64 " - 0x%" PRIx64, i,
125421fed052SAidan Dodds                     kernel_addr);
125521fed052SAidan Dodds       return;
125621fed052SAidan Dodds     }
125721fed052SAidan Dodds 
125821fed052SAidan Dodds     // try to find the non '.expand' function
125921fed052SAidan Dodds     {
126021fed052SAidan Dodds       const llvm::StringRef expand(".expand");
126121fed052SAidan Dodds       const llvm::StringRef name_ref = kernel.m_name.GetStringRef();
126221fed052SAidan Dodds       if (name_ref.endswith(expand)) {
126321fed052SAidan Dodds         const ConstString base_kernel(name_ref.drop_back(expand.size()));
126421fed052SAidan Dodds         // verify this function is a valid kernel
126521fed052SAidan Dodds         if (IsKnownKernel(base_kernel)) {
126621fed052SAidan Dodds           kernel.m_name = base_kernel;
126721fed052SAidan Dodds           if (log)
126821fed052SAidan Dodds             log->Printf("%s - found non expand version '%s'", __FUNCTION__,
126921fed052SAidan Dodds                         base_kernel.GetCString());
127021fed052SAidan Dodds         }
127121fed052SAidan Dodds       }
127221fed052SAidan Dodds     }
127321fed052SAidan Dodds     // add to a list of script group kernels we know about
127421fed052SAidan Dodds     group->m_kernels.push_back(kernel);
127521fed052SAidan Dodds   }
127621fed052SAidan Dodds 
127721fed052SAidan Dodds   // Resolve any pending scriptgroup breakpoints
127821fed052SAidan Dodds   {
127921fed052SAidan Dodds     Target &target = m_process->GetTarget();
128021fed052SAidan Dodds     const BreakpointList &list = target.GetBreakpointList();
128121fed052SAidan Dodds     const size_t num_breakpoints = list.GetSize();
128221fed052SAidan Dodds     if (log)
128321fed052SAidan Dodds       log->Printf("Resolving %zu breakpoints", num_breakpoints);
128421fed052SAidan Dodds     for (size_t i = 0; i < num_breakpoints; ++i) {
128521fed052SAidan Dodds       const BreakpointSP bp = list.GetBreakpointAtIndex(i);
128621fed052SAidan Dodds       if (bp) {
128721fed052SAidan Dodds         if (bp->MatchesName(group_name.AsCString())) {
128821fed052SAidan Dodds           if (log)
128921fed052SAidan Dodds             log->Printf("Found breakpoint with name %s",
129021fed052SAidan Dodds                         group_name.AsCString());
129121fed052SAidan Dodds           bp->ResolveBreakpoint();
129221fed052SAidan Dodds         }
129321fed052SAidan Dodds       }
129421fed052SAidan Dodds     }
129521fed052SAidan Dodds   }
129621fed052SAidan Dodds }
129721fed052SAidan Dodds 
1298b9c1b51eSKate Stone void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
129980af0b9eSLuke Drummond     RuntimeHook *hook, ExecutionContext &exe_ctx) {
1300e09c44b6SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1301e09c44b6SAidan Dodds 
1302b9c1b51eSKate Stone   enum {
1303f4786785SAidan Dodds     eRsContext = 0,
1304f4786785SAidan Dodds     eRsScript,
1305f4786785SAidan Dodds     eRsSlot,
1306f4786785SAidan Dodds     eRsAIns,
1307f4786785SAidan Dodds     eRsInLen,
1308f4786785SAidan Dodds     eRsAOut,
1309f4786785SAidan Dodds     eRsUsr,
1310f4786785SAidan Dodds     eRsUsrLen,
1311f4786785SAidan Dodds     eRsSc,
1312f4786785SAidan Dodds   };
1313e09c44b6SAidan Dodds 
13141ee07253SSaleem Abdulrasool   std::array<ArgItem, 9> args{{
1315f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Context       *rsc
1316f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Script              *s
1317f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // uint32_t             slot
1318f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Allocation   **aIns
1319f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               inLen
1320f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Allocation          *aout
1321f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const void          *usr
1322f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               usrLen
1323f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall  *sc
13241ee07253SSaleem Abdulrasool   }};
1325e09c44b6SAidan Dodds 
132680af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1327b9c1b51eSKate Stone   if (!success) {
1328e09c44b6SAidan Dodds     if (log)
1329b9c1b51eSKate Stone       log->Printf("%s - Error while reading the function parameters",
1330b9c1b51eSKate Stone                   __FUNCTION__);
1331e09c44b6SAidan Dodds     return;
1332e09c44b6SAidan Dodds   }
1333e09c44b6SAidan Dodds 
1334e09c44b6SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
133597206d57SZachary Turner   Status err;
1336e09c44b6SAidan Dodds   std::vector<uint64_t> allocs;
1337e09c44b6SAidan Dodds 
1338e09c44b6SAidan Dodds   // traverse allocation list
1339b9c1b51eSKate Stone   for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1340e09c44b6SAidan Dodds     // calculate offest to allocation pointer
1341f4786785SAidan Dodds     const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1342e09c44b6SAidan Dodds 
134380af0b9eSLuke Drummond     // Note: due to little endian layout, reading 32bits or 64bits into res
134480af0b9eSLuke Drummond     // will give the correct results.
134580af0b9eSLuke Drummond     uint64_t result = 0;
134680af0b9eSLuke Drummond     size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
134780af0b9eSLuke Drummond     if (read != target_ptr_size || !err.Success()) {
1348e09c44b6SAidan Dodds       if (log)
1349b9c1b51eSKate Stone         log->Printf(
1350b9c1b51eSKate Stone             "%s - Error while reading allocation list argument %" PRIu64,
1351b9c1b51eSKate Stone             __FUNCTION__, i);
1352b9c1b51eSKate Stone     } else {
135380af0b9eSLuke Drummond       allocs.push_back(result);
1354e09c44b6SAidan Dodds     }
1355e09c44b6SAidan Dodds   }
1356e09c44b6SAidan Dodds 
1357e09c44b6SAidan Dodds   // if there is an output allocation track it
135880af0b9eSLuke Drummond   if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
135980af0b9eSLuke Drummond     allocs.push_back(alloc_out);
1360e09c44b6SAidan Dodds   }
1361e09c44b6SAidan Dodds 
1362e09c44b6SAidan Dodds   // for all allocations we have found
1363b9c1b51eSKate Stone   for (const uint64_t alloc_addr : allocs) {
13645d057637SLuke Drummond     AllocationDetails *alloc = LookUpAllocation(alloc_addr);
13655d057637SLuke Drummond     if (!alloc)
13665d057637SLuke Drummond       alloc = CreateAllocation(alloc_addr);
13675d057637SLuke Drummond 
1368b9c1b51eSKate Stone     if (alloc) {
1369e09c44b6SAidan Dodds       // save the allocation address
1370b9c1b51eSKate Stone       if (alloc->address.isValid()) {
1371e09c44b6SAidan Dodds         // check the allocation address we already have matches
1372e09c44b6SAidan Dodds         assert(*alloc->address.get() == alloc_addr);
1373b9c1b51eSKate Stone       } else {
1374e09c44b6SAidan Dodds         alloc->address = alloc_addr;
1375e09c44b6SAidan Dodds       }
1376e09c44b6SAidan Dodds 
1377e09c44b6SAidan Dodds       // save the context
1378b9c1b51eSKate Stone       if (log) {
1379b9c1b51eSKate Stone         if (alloc->context.isValid() &&
1380b9c1b51eSKate Stone             *alloc->context.get() != addr_t(args[eRsContext]))
1381b9c1b51eSKate Stone           log->Printf("%s - Allocation used by multiple contexts",
1382b9c1b51eSKate Stone                       __FUNCTION__);
1383e09c44b6SAidan Dodds       }
1384f4786785SAidan Dodds       alloc->context = addr_t(args[eRsContext]);
1385e09c44b6SAidan Dodds     }
1386e09c44b6SAidan Dodds   }
1387e09c44b6SAidan Dodds 
1388e09c44b6SAidan Dodds   // make sure we track this script object
1389b9c1b51eSKate Stone   if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1390b9c1b51eSKate Stone           LookUpScript(addr_t(args[eRsScript]), true)) {
1391b9c1b51eSKate Stone     if (log) {
1392b9c1b51eSKate Stone       if (script->context.isValid() &&
1393b9c1b51eSKate Stone           *script->context.get() != addr_t(args[eRsContext]))
1394b3f7f69dSAidan Dodds         log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1395e09c44b6SAidan Dodds     }
1396f4786785SAidan Dodds     script->context = addr_t(args[eRsContext]);
1397e09c44b6SAidan Dodds   }
1398e09c44b6SAidan Dodds }
1399e09c44b6SAidan Dodds 
140080af0b9eSLuke Drummond void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1401b9c1b51eSKate Stone                                               ExecutionContext &context) {
14024640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14034640cde1SColin Riley 
1404b9c1b51eSKate Stone   enum {
1405f4786785SAidan Dodds     eRsContext,
1406f4786785SAidan Dodds     eRsScript,
1407f4786785SAidan Dodds     eRsId,
1408f4786785SAidan Dodds     eRsData,
1409f4786785SAidan Dodds     eRsLength,
1410f4786785SAidan Dodds   };
14114640cde1SColin Riley 
14121ee07253SSaleem Abdulrasool   std::array<ArgItem, 5> args{{
1413f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1414f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsScript
1415f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsId
1416f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsData
1417f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsLength
14181ee07253SSaleem Abdulrasool   }};
14194640cde1SColin Riley 
1420f4786785SAidan Dodds   bool success = GetArgs(context, &args[0], args.size());
1421b9c1b51eSKate Stone   if (!success) {
142282780287SAidan Dodds     if (log)
1423b3f7f69dSAidan Dodds       log->Printf("%s - error reading the function parameters.", __FUNCTION__);
142482780287SAidan Dodds     return;
142582780287SAidan Dodds   }
14264640cde1SColin Riley 
1427b9c1b51eSKate Stone   if (log) {
1428b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1429b9c1b51eSKate Stone                 ":%" PRIu64 "bytes.",
1430b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1431b9c1b51eSKate Stone                 uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1432f4786785SAidan Dodds                 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
14334640cde1SColin Riley 
1434f4786785SAidan Dodds     addr_t script_addr = addr_t(args[eRsScript]);
1435b9c1b51eSKate Stone     if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
14364640cde1SColin Riley       auto rsm = m_scriptMappings[script_addr];
1437b9c1b51eSKate Stone       if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1438f4786785SAidan Dodds         auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1439b9c1b51eSKate Stone         log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__,
1440b9c1b51eSKate Stone                     rsg.m_name.AsCString(),
1441f4786785SAidan Dodds                     rsm->m_module->GetFileSpec().GetFilename().AsCString());
14424640cde1SColin Riley       }
14434640cde1SColin Riley     }
14444640cde1SColin Riley   }
14454640cde1SColin Riley }
14464640cde1SColin Riley 
144780af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
144880af0b9eSLuke Drummond                                                 ExecutionContext &exe_ctx) {
14494640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14504640cde1SColin Riley 
1451b9c1b51eSKate Stone   enum { eRsContext, eRsAlloc, eRsForceZero };
14524640cde1SColin Riley 
14531ee07253SSaleem Abdulrasool   std::array<ArgItem, 3> args{{
1454f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1455f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1456f4786785SAidan Dodds       ArgItem{ArgItem::eBool, 0},    // eRsForceZero
14571ee07253SSaleem Abdulrasool   }};
14584640cde1SColin Riley 
145980af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
146080af0b9eSLuke Drummond   if (!success) {
146182780287SAidan Dodds     if (log)
1462b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters",
1463b9c1b51eSKate Stone                   __FUNCTION__);
146480af0b9eSLuke Drummond     return;
146582780287SAidan Dodds   }
14664640cde1SColin Riley 
14674640cde1SColin Riley   if (log)
1468b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1469b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1470f4786785SAidan Dodds                 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
147178f339d1SEwan Crawford 
14725d057637SLuke Drummond   AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
147378f339d1SEwan Crawford   if (alloc)
1474f4786785SAidan Dodds     alloc->context = uint64_t(args[eRsContext]);
14754640cde1SColin Riley }
14764640cde1SColin Riley 
147780af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
147880af0b9eSLuke Drummond                                                    ExecutionContext &exe_ctx) {
1479e69df382SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1480e69df382SEwan Crawford 
1481b9c1b51eSKate Stone   enum {
1482f4786785SAidan Dodds     eRsContext,
1483f4786785SAidan Dodds     eRsAlloc,
1484f4786785SAidan Dodds   };
1485e69df382SEwan Crawford 
14861ee07253SSaleem Abdulrasool   std::array<ArgItem, 2> args{{
1487f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1488f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
14891ee07253SSaleem Abdulrasool   }};
1490f4786785SAidan Dodds 
149180af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1492b9c1b51eSKate Stone   if (!success) {
1493e69df382SEwan Crawford     if (log)
1494b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1495b9c1b51eSKate Stone                   __FUNCTION__);
1496b3f7f69dSAidan Dodds     return;
1497e69df382SEwan Crawford   }
1498e69df382SEwan Crawford 
1499e69df382SEwan Crawford   if (log)
1500b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1501b9c1b51eSKate Stone                 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1502e69df382SEwan Crawford 
1503b9c1b51eSKate Stone   for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1504e69df382SEwan Crawford     auto &allocation_ap = *iter; // get the unique pointer
1505b9c1b51eSKate Stone     if (allocation_ap->address.isValid() &&
1506b9c1b51eSKate Stone         *allocation_ap->address.get() == addr_t(args[eRsAlloc])) {
1507e69df382SEwan Crawford       m_allocations.erase(iter);
1508e69df382SEwan Crawford       if (log)
1509b3f7f69dSAidan Dodds         log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1510e69df382SEwan Crawford       return;
1511e69df382SEwan Crawford     }
1512e69df382SEwan Crawford   }
1513e69df382SEwan Crawford 
1514e69df382SEwan Crawford   if (log)
1515b3f7f69dSAidan Dodds     log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1516e69df382SEwan Crawford }
1517e69df382SEwan Crawford 
151880af0b9eSLuke Drummond void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
151980af0b9eSLuke Drummond                                             ExecutionContext &exe_ctx) {
15204640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
15214640cde1SColin Riley 
152297206d57SZachary Turner   Status err;
152380af0b9eSLuke Drummond   Process *process = exe_ctx.GetProcessPtr();
15244640cde1SColin Riley 
1525b9c1b51eSKate Stone   enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
15264640cde1SColin Riley 
1527b9c1b51eSKate Stone   std::array<ArgItem, 4> args{
1528b9c1b51eSKate Stone       {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
15291ee07253SSaleem Abdulrasool        ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
153080af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1531b9c1b51eSKate Stone   if (!success) {
153282780287SAidan Dodds     if (log)
1533b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1534b9c1b51eSKate Stone                   __FUNCTION__);
153582780287SAidan Dodds     return;
153682780287SAidan Dodds   }
153782780287SAidan Dodds 
153880af0b9eSLuke Drummond   std::string res_name;
153980af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
154080af0b9eSLuke Drummond   if (err.Fail()) {
15414640cde1SColin Riley     if (log)
154280af0b9eSLuke Drummond       log->Printf("%s - error reading res_name: %s.", __FUNCTION__,
154380af0b9eSLuke Drummond                   err.AsCString());
15444640cde1SColin Riley   }
15454640cde1SColin Riley 
154680af0b9eSLuke Drummond   std::string cache_dir;
154780af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
154880af0b9eSLuke Drummond   if (err.Fail()) {
15494640cde1SColin Riley     if (log)
155080af0b9eSLuke Drummond       log->Printf("%s - error reading cache_dir: %s.", __FUNCTION__,
155180af0b9eSLuke Drummond                   err.AsCString());
15524640cde1SColin Riley   }
15534640cde1SColin Riley 
15544640cde1SColin Riley   if (log)
1555b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1556b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
155780af0b9eSLuke Drummond                 uint64_t(args[eRsScript]), res_name.c_str(), cache_dir.c_str());
15584640cde1SColin Riley 
155980af0b9eSLuke Drummond   if (res_name.size() > 0) {
15604640cde1SColin Riley     StreamString strm;
156180af0b9eSLuke Drummond     strm.Printf("librs.%s.so", res_name.c_str());
15624640cde1SColin Riley 
1563f4786785SAidan Dodds     ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1564b9c1b51eSKate Stone     if (script) {
156578f339d1SEwan Crawford       script->type = ScriptDetails::eScriptC;
156680af0b9eSLuke Drummond       script->cache_dir = cache_dir;
156780af0b9eSLuke Drummond       script->res_name = res_name;
1568c156427dSZachary Turner       script->shared_lib = strm.GetString();
1569f4786785SAidan Dodds       script->context = addr_t(args[eRsContext]);
157078f339d1SEwan Crawford     }
15714640cde1SColin Riley 
15724640cde1SColin Riley     if (log)
1573b9c1b51eSKate Stone       log->Printf("%s - '%s' tagged with context 0x%" PRIx64
1574b9c1b51eSKate Stone                   " and script 0x%" PRIx64 ".",
1575b9c1b51eSKate Stone                   __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1576b9c1b51eSKate Stone                   uint64_t(args[eRsScript]));
1577b9c1b51eSKate Stone   } else if (log) {
1578b3f7f69dSAidan Dodds     log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
15794640cde1SColin Riley   }
15804640cde1SColin Riley }
15814640cde1SColin Riley 
1582b9c1b51eSKate Stone void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1583b9c1b51eSKate Stone                                            ModuleKind kind) {
15844640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
15854640cde1SColin Riley 
1586b9c1b51eSKate Stone   if (!module) {
15874640cde1SColin Riley     return;
15884640cde1SColin Riley   }
15894640cde1SColin Riley 
159082780287SAidan Dodds   Target &target = GetProcess()->GetTarget();
159121fed052SAidan Dodds   const llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
159282780287SAidan Dodds 
159380af0b9eSLuke Drummond   if (machine != llvm::Triple::ArchType::x86 &&
159480af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::arm &&
159580af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::aarch64 &&
159680af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mipsel &&
159780af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mips64el &&
159880af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::x86_64) {
15994640cde1SColin Riley     if (log)
1600b3f7f69dSAidan Dodds       log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
16014640cde1SColin Riley     return;
16024640cde1SColin Riley   }
16034640cde1SColin Riley 
160421fed052SAidan Dodds   const uint32_t target_ptr_size =
160521fed052SAidan Dodds       target.GetArchitecture().GetAddressByteSize();
160621fed052SAidan Dodds 
160721fed052SAidan Dodds   std::array<bool, s_runtimeHookCount> hook_placed;
160821fed052SAidan Dodds   hook_placed.fill(false);
16094640cde1SColin Riley 
1610b9c1b51eSKate Stone   for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
16114640cde1SColin Riley     const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1612b9c1b51eSKate Stone     if (hook_defn->kind != kind) {
16134640cde1SColin Riley       continue;
16144640cde1SColin Riley     }
16154640cde1SColin Riley 
161680af0b9eSLuke Drummond     const char *symbol_name = (target_ptr_size == 4)
161780af0b9eSLuke Drummond                                   ? hook_defn->symbol_name_m32
1618b9c1b51eSKate Stone                                   : hook_defn->symbol_name_m64;
161982780287SAidan Dodds 
1620b9c1b51eSKate Stone     const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1621b9c1b51eSKate Stone         ConstString(symbol_name), eSymbolTypeCode);
1622b9c1b51eSKate Stone     if (!sym) {
1623b9c1b51eSKate Stone       if (log) {
1624b3f7f69dSAidan Dodds         log->Printf("%s - symbol '%s' related to the function %s not found",
1625b3f7f69dSAidan Dodds                     __FUNCTION__, symbol_name, hook_defn->name);
162682780287SAidan Dodds       }
162782780287SAidan Dodds       continue;
162882780287SAidan Dodds     }
16294640cde1SColin Riley 
1630358cf1eaSGreg Clayton     addr_t addr = sym->GetLoadAddress(&target);
1631b9c1b51eSKate Stone     if (addr == LLDB_INVALID_ADDRESS) {
16324640cde1SColin Riley       if (log)
1633b9c1b51eSKate Stone         log->Printf("%s - unable to resolve the address of hook function '%s' "
1634b9c1b51eSKate Stone                     "with symbol '%s'.",
1635b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, symbol_name);
16364640cde1SColin Riley       continue;
1637b9c1b51eSKate Stone     } else {
163882780287SAidan Dodds       if (log)
1639b3f7f69dSAidan Dodds         log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1640b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, addr);
164182780287SAidan Dodds     }
16424640cde1SColin Riley 
16434640cde1SColin Riley     RuntimeHookSP hook(new RuntimeHook());
16444640cde1SColin Riley     hook->address = addr;
16454640cde1SColin Riley     hook->defn = hook_defn;
16464640cde1SColin Riley     hook->bp_sp = target.CreateBreakpoint(addr, true, false);
16474640cde1SColin Riley     hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
16484640cde1SColin Riley     m_runtimeHooks[addr] = hook;
1649b9c1b51eSKate Stone     if (log) {
1650b9c1b51eSKate Stone       log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64
1651b9c1b51eSKate Stone                   " at 0x%" PRIx64 ".",
1652b9c1b51eSKate Stone                   __FUNCTION__, hook_defn->name,
1653b9c1b51eSKate Stone                   module->GetFileSpec().GetFilename().AsCString(),
1654b3f7f69dSAidan Dodds                   (uint64_t)hook_defn->version, (uint64_t)addr);
16554640cde1SColin Riley     }
165621fed052SAidan Dodds     hook_placed[idx] = true;
165721fed052SAidan Dodds   }
165821fed052SAidan Dodds 
165921fed052SAidan Dodds   // log any unhooked function
166021fed052SAidan Dodds   if (log) {
166121fed052SAidan Dodds     for (size_t i = 0; i < hook_placed.size(); ++i) {
166221fed052SAidan Dodds       if (hook_placed[i])
166321fed052SAidan Dodds         continue;
166421fed052SAidan Dodds       const HookDefn &hook_defn = s_runtimeHookDefns[i];
166521fed052SAidan Dodds       if (hook_defn.kind != kind)
166621fed052SAidan Dodds         continue;
166721fed052SAidan Dodds       log->Printf("%s - function %s was not hooked", __FUNCTION__,
166821fed052SAidan Dodds                   hook_defn.name);
166921fed052SAidan Dodds     }
16704640cde1SColin Riley   }
16714640cde1SColin Riley }
16724640cde1SColin Riley 
1673b9c1b51eSKate Stone void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
16744640cde1SColin Riley   if (!rsmodule_sp)
16754640cde1SColin Riley     return;
16764640cde1SColin Riley 
16774640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
16784640cde1SColin Riley 
16794640cde1SColin Riley   const ModuleSP module = rsmodule_sp->m_module;
16804640cde1SColin Riley   const FileSpec &file = module->GetPlatformFileSpec();
16814640cde1SColin Riley 
168205097246SAdrian Prantl   // Iterate over all of the scripts that we currently know of. Note: We cant
168305097246SAdrian Prantl   // push or pop to m_scripts here or it may invalidate rs_script.
1684b9c1b51eSKate Stone   for (const auto &rs_script : m_scripts) {
168578f339d1SEwan Crawford     // Extract the expected .so file path for this script.
168680af0b9eSLuke Drummond     std::string shared_lib;
168780af0b9eSLuke Drummond     if (!rs_script->shared_lib.get(shared_lib))
168878f339d1SEwan Crawford       continue;
168978f339d1SEwan Crawford 
169078f339d1SEwan Crawford     // Only proceed if the module that has loaded corresponds to this script.
169180af0b9eSLuke Drummond     if (file.GetFilename() != ConstString(shared_lib.c_str()))
169278f339d1SEwan Crawford       continue;
169378f339d1SEwan Crawford 
169478f339d1SEwan Crawford     // Obtain the script address which we use as a key.
169578f339d1SEwan Crawford     lldb::addr_t script;
169678f339d1SEwan Crawford     if (!rs_script->script.get(script))
169778f339d1SEwan Crawford       continue;
169878f339d1SEwan Crawford 
169978f339d1SEwan Crawford     // If we have a script mapping for the current script.
1700b9c1b51eSKate Stone     if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
170178f339d1SEwan Crawford       // if the module we have stored is different to the one we just received.
1702b9c1b51eSKate Stone       if (m_scriptMappings[script] != rsmodule_sp) {
17034640cde1SColin Riley         if (log)
1704b9c1b51eSKate Stone           log->Printf(
1705b9c1b51eSKate Stone               "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1706b9c1b51eSKate Stone               __FUNCTION__, (uint64_t)script,
1707b9c1b51eSKate Stone               rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
17084640cde1SColin Riley       }
17094640cde1SColin Riley     }
171078f339d1SEwan Crawford     // We don't have a script mapping for the current script.
1711b9c1b51eSKate Stone     else {
171278f339d1SEwan Crawford       // Obtain the script resource name.
171380af0b9eSLuke Drummond       std::string res_name;
171480af0b9eSLuke Drummond       if (rs_script->res_name.get(res_name))
171578f339d1SEwan Crawford         // Set the modules resource name.
171680af0b9eSLuke Drummond         rsmodule_sp->m_resname = res_name;
171778f339d1SEwan Crawford       // Add Script/Module pair to map.
171878f339d1SEwan Crawford       m_scriptMappings[script] = rsmodule_sp;
17194640cde1SColin Riley       if (log)
1720b9c1b51eSKate Stone         log->Printf(
1721b9c1b51eSKate Stone             "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1722b9c1b51eSKate Stone             __FUNCTION__, (uint64_t)script,
1723b9c1b51eSKate Stone             rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
17244640cde1SColin Riley     }
17254640cde1SColin Riley   }
17264640cde1SColin Riley }
17274640cde1SColin Riley 
1728b9c1b51eSKate Stone // Uses the Target API to evaluate the expression passed as a parameter to the
172980af0b9eSLuke Drummond // function The result of that expression is returned an unsigned 64 bit int,
173080af0b9eSLuke Drummond // via the result* parameter. Function returns true on success, and false on
173180af0b9eSLuke Drummond // failure
173280af0b9eSLuke Drummond bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1733b9c1b51eSKate Stone                                            StackFrame *frame_ptr,
1734b9c1b51eSKate Stone                                            uint64_t *result) {
173515f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
173615f2bd95SEwan Crawford   if (log)
173780af0b9eSLuke Drummond     log->Printf("%s(%s)", __FUNCTION__, expr);
173815f2bd95SEwan Crawford 
173915f2bd95SEwan Crawford   ValueObjectSP expr_result;
17408433fdbeSAidan Dodds   EvaluateExpressionOptions options;
17418433fdbeSAidan Dodds   options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
174215f2bd95SEwan Crawford   // Perform the actual expression evaluation
174380af0b9eSLuke Drummond   auto &target = GetProcess()->GetTarget();
174480af0b9eSLuke Drummond   target.EvaluateExpression(expr, frame_ptr, expr_result, options);
174515f2bd95SEwan Crawford 
1746b9c1b51eSKate Stone   if (!expr_result) {
174715f2bd95SEwan Crawford     if (log)
1748b3f7f69dSAidan Dodds       log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
174915f2bd95SEwan Crawford     return false;
175015f2bd95SEwan Crawford   }
175115f2bd95SEwan Crawford 
175215f2bd95SEwan Crawford   // The result of the expression is invalid
1753b9c1b51eSKate Stone   if (!expr_result->GetError().Success()) {
175497206d57SZachary Turner     Status err = expr_result->GetError();
175580af0b9eSLuke Drummond     // Expression returned is void, so this is actually a success
1756a35912daSKrasimir Georgiev     if (err.GetError() == UserExpression::kNoResult) {
175715f2bd95SEwan Crawford       if (log)
1758b3f7f69dSAidan Dodds         log->Printf("%s - expression returned void.", __FUNCTION__);
175915f2bd95SEwan Crawford 
176015f2bd95SEwan Crawford       result = nullptr;
176115f2bd95SEwan Crawford       return true;
176215f2bd95SEwan Crawford     }
176315f2bd95SEwan Crawford 
176415f2bd95SEwan Crawford     if (log)
1765b3f7f69dSAidan Dodds       log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1766b3f7f69dSAidan Dodds                   err.AsCString());
176715f2bd95SEwan Crawford     return false;
176815f2bd95SEwan Crawford   }
176915f2bd95SEwan Crawford 
177015f2bd95SEwan Crawford   bool success = false;
177180af0b9eSLuke Drummond   // We only read the result as an uint32_t.
177280af0b9eSLuke Drummond   *result = expr_result->GetValueAsUnsigned(0, &success);
177315f2bd95SEwan Crawford 
1774b9c1b51eSKate Stone   if (!success) {
177515f2bd95SEwan Crawford     if (log)
1776b9c1b51eSKate Stone       log->Printf("%s - couldn't convert expression result to uint32_t",
1777b9c1b51eSKate Stone                   __FUNCTION__);
177815f2bd95SEwan Crawford     return false;
177915f2bd95SEwan Crawford   }
178015f2bd95SEwan Crawford 
178115f2bd95SEwan Crawford   return true;
178215f2bd95SEwan Crawford }
178315f2bd95SEwan Crawford 
1784b9c1b51eSKate Stone namespace {
1785836d9651SEwan Crawford // Used to index expression format strings
1786b9c1b51eSKate Stone enum ExpressionStrings {
1787836d9651SEwan Crawford   eExprGetOffsetPtr = 0,
1788836d9651SEwan Crawford   eExprAllocGetType,
1789836d9651SEwan Crawford   eExprTypeDimX,
1790836d9651SEwan Crawford   eExprTypeDimY,
1791836d9651SEwan Crawford   eExprTypeDimZ,
1792836d9651SEwan Crawford   eExprTypeElemPtr,
1793836d9651SEwan Crawford   eExprElementType,
1794836d9651SEwan Crawford   eExprElementKind,
1795836d9651SEwan Crawford   eExprElementVec,
1796836d9651SEwan Crawford   eExprElementFieldCount,
1797836d9651SEwan Crawford   eExprSubelementsId,
1798836d9651SEwan Crawford   eExprSubelementsName,
1799ea0636b5SEwan Crawford   eExprSubelementsArrSize,
1800ea0636b5SEwan Crawford 
180180af0b9eSLuke Drummond   _eExprLast // keep at the end, implicit size of the array runtime_expressions
1802836d9651SEwan Crawford };
180315f2bd95SEwan Crawford 
1804ea0636b5SEwan Crawford // max length of an expanded expression
1805ea0636b5SEwan Crawford const int jit_max_expr_size = 512;
1806ea0636b5SEwan Crawford 
1807ea0636b5SEwan Crawford // Retrieve the string to JIT for the given expression
180836d783ebSDavid Gross #define JIT_TEMPLATE_CONTEXT "void* ctxt = (void*)rsDebugGetContextWrapper(0x%" PRIx64 "); "
1809b9c1b51eSKate Stone const char *JITTemplate(ExpressionStrings e) {
1810ea0636b5SEwan Crawford   // Format strings containing the expressions we may need to evaluate.
181180af0b9eSLuke Drummond   static std::array<const char *, _eExprLast> runtime_expressions = {
1812b9c1b51eSKate Stone       {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1813b9c1b51eSKate Stone        "(int*)_"
1814b9c1b51eSKate Stone        "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1815b9c1b51eSKate Stone        "CubemapFace"
181636d783ebSDavid Gross        "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)", // eExprGetOffsetPtr
181715f2bd95SEwan Crawford 
181815f2bd95SEwan Crawford        // Type* rsaAllocationGetType(Context*, Allocation*)
181936d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "(void*)rsaAllocationGetType(ctxt, 0x%" PRIx64 ")", // eExprAllocGetType
182015f2bd95SEwan Crawford 
182180af0b9eSLuke Drummond        // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
182280af0b9eSLuke Drummond        // data in the following way mHal.state.dimX; mHal.state.dimY;
182305097246SAdrian Prantl        // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement;
182405097246SAdrian Prantl        // into typeData Need to specify 32 or 64 bit for uint_t since this
182505097246SAdrian Prantl        // differs between devices
182636d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
182736d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
182836d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[0]", // eExprTypeDimX
182936d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
183036d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
183136d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[1]", // eExprTypeDimY
183236d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
183336d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
183436d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[2]", // eExprTypeDimZ
183536d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
183636d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
183736d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[5]", // eExprTypeElemPtr
183815f2bd95SEwan Crawford 
183915f2bd95SEwan Crawford        // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1840b9c1b51eSKate Stone        // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1841b9c1b51eSKate Stone        // elemData
184236d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
184336d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
184436d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[0]", // eExprElementType
184536d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
184636d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
184736d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[1]", // eExprElementKind
184836d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
184936d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
185036d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[3]", // eExprElementVec
185136d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
185236d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
185336d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[4]", // eExprElementFieldCount
18548b244e21SEwan Crawford 
1855b9c1b51eSKate Stone        // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
185680af0b9eSLuke Drummond        // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1857b9c1b51eSKate Stone        // Needed for Allocations of structs to gather details about
185880af0b9eSLuke Drummond        // fields/Subelements Element* of field
185936d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1860b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
186136d783ebSDavid Gross        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
186236d783ebSDavid Gross        ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]", // eExprSubelementsId
18638b244e21SEwan Crawford 
1864577570b4SAidan Dodds        // Name of field
186536d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1866b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
186736d783ebSDavid Gross        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
186836d783ebSDavid Gross        ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]", // eExprSubelementsName
18698b244e21SEwan Crawford 
1870577570b4SAidan Dodds        // Array size of field
187136d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1872b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
187336d783ebSDavid Gross        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
187436d783ebSDavid Gross        ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}}; // eExprSubelementsArrSize
1875ea0636b5SEwan Crawford 
187680af0b9eSLuke Drummond   return runtime_expressions[e];
1877ea0636b5SEwan Crawford }
1878ea0636b5SEwan Crawford } // end of the anonymous namespace
1879ea0636b5SEwan Crawford 
188005097246SAdrian Prantl // JITs the RS runtime for the internal data pointer of an allocation. Is
188105097246SAdrian Prantl // passed x,y,z coordinates for the pointer to a specific element. Then sets
188205097246SAdrian Prantl // the data_ptr member in Allocation with the result. Returns true on success,
188305097246SAdrian Prantl // false otherwise
188480af0b9eSLuke Drummond bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1885b9c1b51eSKate Stone                                          StackFrame *frame_ptr, uint32_t x,
1886b9c1b51eSKate Stone                                          uint32_t y, uint32_t z) {
188715f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
188815f2bd95SEwan Crawford 
188980af0b9eSLuke Drummond   if (!alloc->address.isValid()) {
189015f2bd95SEwan Crawford     if (log)
1891b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
189215f2bd95SEwan Crawford     return false;
189315f2bd95SEwan Crawford   }
189415f2bd95SEwan Crawford 
189580af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
189680af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
189715f2bd95SEwan Crawford 
189880af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
189980af0b9eSLuke Drummond                          *alloc->address.get(), x, y, z);
190080af0b9eSLuke Drummond   if (written < 0) {
190115f2bd95SEwan Crawford     if (log)
1902b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
190315f2bd95SEwan Crawford     return false;
190480af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
190515f2bd95SEwan Crawford     if (log)
1906b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
190715f2bd95SEwan Crawford     return false;
190815f2bd95SEwan Crawford   }
190915f2bd95SEwan Crawford 
191015f2bd95SEwan Crawford   uint64_t result = 0;
191180af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
191215f2bd95SEwan Crawford     return false;
191315f2bd95SEwan Crawford 
191480af0b9eSLuke Drummond   addr_t data_ptr = static_cast<lldb::addr_t>(result);
191580af0b9eSLuke Drummond   alloc->data_ptr = data_ptr;
191615f2bd95SEwan Crawford 
191715f2bd95SEwan Crawford   return true;
191815f2bd95SEwan Crawford }
191915f2bd95SEwan Crawford 
192015f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
192180af0b9eSLuke Drummond // Then sets the type_ptr member in Allocation with the result. Returns true on
192280af0b9eSLuke Drummond // success, false otherwise
192380af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1924b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
192515f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
192615f2bd95SEwan Crawford 
192780af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->context.isValid()) {
192815f2bd95SEwan Crawford     if (log)
1929b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
193015f2bd95SEwan Crawford     return false;
193115f2bd95SEwan Crawford   }
193215f2bd95SEwan Crawford 
193380af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprAllocGetType);
193480af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
193515f2bd95SEwan Crawford 
193680af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
193780af0b9eSLuke Drummond                          *alloc->context.get(), *alloc->address.get());
193880af0b9eSLuke Drummond   if (written < 0) {
193915f2bd95SEwan Crawford     if (log)
1940b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
194115f2bd95SEwan Crawford     return false;
194280af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
194315f2bd95SEwan Crawford     if (log)
1944b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
194515f2bd95SEwan Crawford     return false;
194615f2bd95SEwan Crawford   }
194715f2bd95SEwan Crawford 
194815f2bd95SEwan Crawford   uint64_t result = 0;
194980af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
195015f2bd95SEwan Crawford     return false;
195115f2bd95SEwan Crawford 
195215f2bd95SEwan Crawford   addr_t type_ptr = static_cast<lldb::addr_t>(result);
195380af0b9eSLuke Drummond   alloc->type_ptr = type_ptr;
195415f2bd95SEwan Crawford 
195515f2bd95SEwan Crawford   return true;
195615f2bd95SEwan Crawford }
195715f2bd95SEwan Crawford 
1958b9c1b51eSKate Stone // JITs the RS runtime for information about the dimensions and type of an
195905097246SAdrian Prantl // allocation Then sets dimension and element_ptr members in Allocation with
196005097246SAdrian Prantl // the result. Returns true on success, false otherwise
196180af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1962b9c1b51eSKate Stone                                         StackFrame *frame_ptr) {
196315f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
196415f2bd95SEwan Crawford 
196580af0b9eSLuke Drummond   if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
196615f2bd95SEwan Crawford     if (log)
1967b3f7f69dSAidan Dodds       log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
196815f2bd95SEwan Crawford     return false;
196915f2bd95SEwan Crawford   }
197015f2bd95SEwan Crawford 
197115f2bd95SEwan Crawford   // Expression is different depending on if device is 32 or 64 bit
197280af0b9eSLuke Drummond   uint32_t target_ptr_size =
1973b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
197480af0b9eSLuke Drummond   const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
197515f2bd95SEwan Crawford 
197615f2bd95SEwan Crawford   // We want 4 elements from packed data
1977b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
1978b9c1b51eSKate Stone   assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) &&
1979b9c1b51eSKate Stone          "Invalid number of expressions");
198015f2bd95SEwan Crawford 
198180af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
198215f2bd95SEwan Crawford   uint64_t results[num_exprs];
198315f2bd95SEwan Crawford 
1984b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; ++i) {
198580af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
198636d783ebSDavid Gross     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str,
198736d783ebSDavid Gross                            *alloc->context.get(), bits, *alloc->type_ptr.get());
198880af0b9eSLuke Drummond     if (written < 0) {
198915f2bd95SEwan Crawford       if (log)
1990b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
199115f2bd95SEwan Crawford       return false;
199280af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
199315f2bd95SEwan Crawford       if (log)
1994b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
199515f2bd95SEwan Crawford       return false;
199615f2bd95SEwan Crawford     }
199715f2bd95SEwan Crawford 
199815f2bd95SEwan Crawford     // Perform expression evaluation
199980af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
200015f2bd95SEwan Crawford       return false;
200115f2bd95SEwan Crawford   }
200215f2bd95SEwan Crawford 
200315f2bd95SEwan Crawford   // Assign results to allocation members
200415f2bd95SEwan Crawford   AllocationDetails::Dimension dims;
200515f2bd95SEwan Crawford   dims.dim_1 = static_cast<uint32_t>(results[0]);
200615f2bd95SEwan Crawford   dims.dim_2 = static_cast<uint32_t>(results[1]);
200715f2bd95SEwan Crawford   dims.dim_3 = static_cast<uint32_t>(results[2]);
200880af0b9eSLuke Drummond   alloc->dimension = dims;
200915f2bd95SEwan Crawford 
201080af0b9eSLuke Drummond   addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
201180af0b9eSLuke Drummond   alloc->element.element_ptr = element_ptr;
201215f2bd95SEwan Crawford 
201315f2bd95SEwan Crawford   if (log)
2014b9c1b51eSKate Stone     log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
2015b9c1b51eSKate Stone                 ") Element*: 0x%" PRIx64 ".",
201680af0b9eSLuke Drummond                 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
201715f2bd95SEwan Crawford 
201815f2bd95SEwan Crawford   return true;
201915f2bd95SEwan Crawford }
202015f2bd95SEwan Crawford 
202180af0b9eSLuke Drummond // JITs the RS runtime for information about the Element of an allocation Then
202280af0b9eSLuke Drummond // sets type, type_vec_size, field_count and type_kind members in Element with
202380af0b9eSLuke Drummond // the result. Returns true on success, false otherwise
2024b9c1b51eSKate Stone bool RenderScriptRuntime::JITElementPacked(Element &elem,
2025b9c1b51eSKate Stone                                            const lldb::addr_t context,
2026b9c1b51eSKate Stone                                            StackFrame *frame_ptr) {
202715f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
202815f2bd95SEwan Crawford 
2029b9c1b51eSKate Stone   if (!elem.element_ptr.isValid()) {
203015f2bd95SEwan Crawford     if (log)
2031b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
203215f2bd95SEwan Crawford     return false;
203315f2bd95SEwan Crawford   }
203415f2bd95SEwan Crawford 
20358b244e21SEwan Crawford   // We want 4 elements from packed data
2036b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
2037b9c1b51eSKate Stone   assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) &&
2038b9c1b51eSKate Stone          "Invalid number of expressions");
203915f2bd95SEwan Crawford 
204080af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
204115f2bd95SEwan Crawford   uint64_t results[num_exprs];
204215f2bd95SEwan Crawford 
2043b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; i++) {
204480af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
204580af0b9eSLuke Drummond     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
204680af0b9eSLuke Drummond                            *elem.element_ptr.get());
204780af0b9eSLuke Drummond     if (written < 0) {
204815f2bd95SEwan Crawford       if (log)
2049b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
205015f2bd95SEwan Crawford       return false;
205180af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
205215f2bd95SEwan Crawford       if (log)
2053b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
205415f2bd95SEwan Crawford       return false;
205515f2bd95SEwan Crawford     }
205615f2bd95SEwan Crawford 
205715f2bd95SEwan Crawford     // Perform expression evaluation
205880af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
205915f2bd95SEwan Crawford       return false;
206015f2bd95SEwan Crawford   }
206115f2bd95SEwan Crawford 
206215f2bd95SEwan Crawford   // Assign results to allocation members
20638b244e21SEwan Crawford   elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
2064b9c1b51eSKate Stone   elem.type_kind =
2065b9c1b51eSKate Stone       static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
20668b244e21SEwan Crawford   elem.type_vec_size = static_cast<uint32_t>(results[2]);
20678b244e21SEwan Crawford   elem.field_count = static_cast<uint32_t>(results[3]);
206815f2bd95SEwan Crawford 
206915f2bd95SEwan Crawford   if (log)
2070b9c1b51eSKate Stone     log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32
2071b9c1b51eSKate Stone                 ", vector size %" PRIu32 ", field count %" PRIu32,
2072b9c1b51eSKate Stone                 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
2073b9c1b51eSKate Stone                 *elem.type_vec_size.get(), *elem.field_count.get());
20748b244e21SEwan Crawford 
2075b9c1b51eSKate Stone   // If this Element has subelements then JIT rsaElementGetSubElements() for
2076b9c1b51eSKate Stone   // details about its fields
20778b244e21SEwan Crawford   if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
20788b244e21SEwan Crawford     return false;
20798b244e21SEwan Crawford 
20808b244e21SEwan Crawford   return true;
20818b244e21SEwan Crawford }
20828b244e21SEwan Crawford 
2083b9c1b51eSKate Stone // JITs the RS runtime for information about the subelements/fields of a struct
208480af0b9eSLuke Drummond // allocation This is necessary for infering the struct type so we can pretty
208580af0b9eSLuke Drummond // print the allocation's contents. Returns true on success, false otherwise
2086b9c1b51eSKate Stone bool RenderScriptRuntime::JITSubelements(Element &elem,
2087b9c1b51eSKate Stone                                          const lldb::addr_t context,
2088b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
20898b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
20908b244e21SEwan Crawford 
2091b9c1b51eSKate Stone   if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
20928b244e21SEwan Crawford     if (log)
2093b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
20948b244e21SEwan Crawford     return false;
20958b244e21SEwan Crawford   }
20968b244e21SEwan Crawford 
20978b244e21SEwan Crawford   const short num_exprs = 3;
2098b9c1b51eSKate Stone   assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) &&
2099b9c1b51eSKate Stone          "Invalid number of expressions");
21008b244e21SEwan Crawford 
2101ea0636b5SEwan Crawford   char expr_buffer[jit_max_expr_size];
21028b244e21SEwan Crawford   uint64_t results;
21038b244e21SEwan Crawford 
21048b244e21SEwan Crawford   // Iterate over struct fields.
21058b244e21SEwan Crawford   const uint32_t field_count = *elem.field_count.get();
2106b9c1b51eSKate Stone   for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
21078b244e21SEwan Crawford     Element child;
2108b9c1b51eSKate Stone     for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
210980af0b9eSLuke Drummond       const char *fmt_str =
2110b9c1b51eSKate Stone           JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
211180af0b9eSLuke Drummond       int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
211236d783ebSDavid Gross                              context, field_count, field_count, field_count,
211380af0b9eSLuke Drummond                              *elem.element_ptr.get(), field_count, field_index);
211480af0b9eSLuke Drummond       if (written < 0) {
21158b244e21SEwan Crawford         if (log)
2116b3f7f69dSAidan Dodds           log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
21178b244e21SEwan Crawford         return false;
211880af0b9eSLuke Drummond       } else if (written >= jit_max_expr_size) {
21198b244e21SEwan Crawford         if (log)
2120b3f7f69dSAidan Dodds           log->Printf("%s - expression too long.", __FUNCTION__);
21218b244e21SEwan Crawford         return false;
21228b244e21SEwan Crawford       }
21238b244e21SEwan Crawford 
21248b244e21SEwan Crawford       // Perform expression evaluation
21258b244e21SEwan Crawford       if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
21268b244e21SEwan Crawford         return false;
21278b244e21SEwan Crawford 
21288b244e21SEwan Crawford       if (log)
2129b3f7f69dSAidan Dodds         log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
21308b244e21SEwan Crawford 
2131b9c1b51eSKate Stone       switch (expr_index) {
21328b244e21SEwan Crawford       case 0: // Element* of child
21338b244e21SEwan Crawford         child.element_ptr = static_cast<addr_t>(results);
21348b244e21SEwan Crawford         break;
21358b244e21SEwan Crawford       case 1: // Name of child
21368b244e21SEwan Crawford       {
21378b244e21SEwan Crawford         lldb::addr_t address = static_cast<addr_t>(results);
213897206d57SZachary Turner         Status err;
21398b244e21SEwan Crawford         std::string name;
21408b244e21SEwan Crawford         GetProcess()->ReadCStringFromMemory(address, name, err);
21418b244e21SEwan Crawford         if (!err.Fail())
21428b244e21SEwan Crawford           child.type_name = ConstString(name);
2143b9c1b51eSKate Stone         else {
21448b244e21SEwan Crawford           if (log)
2145b9c1b51eSKate Stone             log->Printf("%s - warning: Couldn't read field name.",
2146b9c1b51eSKate Stone                         __FUNCTION__);
21478b244e21SEwan Crawford         }
21488b244e21SEwan Crawford         break;
21498b244e21SEwan Crawford       }
21508b244e21SEwan Crawford       case 2: // Array size of child
21518b244e21SEwan Crawford         child.array_size = static_cast<uint32_t>(results);
21528b244e21SEwan Crawford         break;
21538b244e21SEwan Crawford       }
21548b244e21SEwan Crawford     }
21558b244e21SEwan Crawford 
21568b244e21SEwan Crawford     // We need to recursively JIT each Element field of the struct since
21578b244e21SEwan Crawford     // structs can be nested inside structs.
21588b244e21SEwan Crawford     if (!JITElementPacked(child, context, frame_ptr))
21598b244e21SEwan Crawford       return false;
21608b244e21SEwan Crawford     elem.children.push_back(child);
21618b244e21SEwan Crawford   }
21628b244e21SEwan Crawford 
2163b9c1b51eSKate Stone   // Try to infer the name of the struct type so we can pretty print the
2164b9c1b51eSKate Stone   // allocation contents.
21658b244e21SEwan Crawford   FindStructTypeName(elem, frame_ptr);
216615f2bd95SEwan Crawford 
216715f2bd95SEwan Crawford   return true;
216815f2bd95SEwan Crawford }
216915f2bd95SEwan Crawford 
2170a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
2171b9c1b51eSKate Stone // The `elem_size` parameter represents the size of a single element, including
217280af0b9eSLuke Drummond // padding. Which is needed as an offset from the last element pointer. Using
217380af0b9eSLuke Drummond // this offset minus the starting address we can calculate the size of the
217480af0b9eSLuke Drummond // allocation. Returns true on success, false otherwise
217580af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
2176b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
2177a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2178a0f08674SEwan Crawford 
217980af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
218080af0b9eSLuke Drummond       !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
2181a0f08674SEwan Crawford     if (log)
2182b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2183a0f08674SEwan Crawford     return false;
2184a0f08674SEwan Crawford   }
2185a0f08674SEwan Crawford 
2186a0f08674SEwan Crawford   // Find dimensions
218780af0b9eSLuke Drummond   uint32_t dim_x = alloc->dimension.get()->dim_1;
218880af0b9eSLuke Drummond   uint32_t dim_y = alloc->dimension.get()->dim_2;
218980af0b9eSLuke Drummond   uint32_t dim_z = alloc->dimension.get()->dim_3;
2190a0f08674SEwan Crawford 
2191b9c1b51eSKate Stone   // Our plan of jitting the last element address doesn't seem to work for
219280af0b9eSLuke Drummond   // struct Allocations` Instead try to infer the size ourselves without any
219380af0b9eSLuke Drummond   // inter element padding.
219480af0b9eSLuke Drummond   if (alloc->element.children.size() > 0) {
2195b9c1b51eSKate Stone     if (dim_x == 0)
2196b9c1b51eSKate Stone       dim_x = 1;
2197b9c1b51eSKate Stone     if (dim_y == 0)
2198b9c1b51eSKate Stone       dim_y = 1;
2199b9c1b51eSKate Stone     if (dim_z == 0)
2200b9c1b51eSKate Stone       dim_z = 1;
22018b244e21SEwan Crawford 
220280af0b9eSLuke Drummond     alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
22038b244e21SEwan Crawford 
22048b244e21SEwan Crawford     if (log)
2205b9c1b51eSKate Stone       log->Printf("%s - inferred size of struct allocation %" PRIu32 ".",
220680af0b9eSLuke Drummond                   __FUNCTION__, *alloc->size.get());
22078b244e21SEwan Crawford     return true;
22088b244e21SEwan Crawford   }
22098b244e21SEwan Crawford 
221080af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
221180af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
22128b244e21SEwan Crawford 
2213a0f08674SEwan Crawford   // Calculate last element
2214a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 0 : dim_x - 1;
2215a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 0 : dim_y - 1;
2216a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 0 : dim_z - 1;
2217a0f08674SEwan Crawford 
221880af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
221980af0b9eSLuke Drummond                          *alloc->address.get(), dim_x, dim_y, dim_z);
222080af0b9eSLuke Drummond   if (written < 0) {
2221a0f08674SEwan Crawford     if (log)
2222b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2223a0f08674SEwan Crawford     return false;
222480af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
2225a0f08674SEwan Crawford     if (log)
2226b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
2227a0f08674SEwan Crawford     return false;
2228a0f08674SEwan Crawford   }
2229a0f08674SEwan Crawford 
2230a0f08674SEwan Crawford   uint64_t result = 0;
223180af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2232a0f08674SEwan Crawford     return false;
2233a0f08674SEwan Crawford 
2234a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2235a0f08674SEwan Crawford   // Find pointer to last element and add on size of an element
223680af0b9eSLuke Drummond   alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
223780af0b9eSLuke Drummond                 *alloc->element.datum_size.get();
2238a0f08674SEwan Crawford 
2239a0f08674SEwan Crawford   return true;
2240a0f08674SEwan Crawford }
2241a0f08674SEwan Crawford 
2242b9c1b51eSKate Stone // JITs the RS runtime for information about the stride between rows in the
224305097246SAdrian Prantl // allocation. This is done to detect padding, since allocated memory is
224405097246SAdrian Prantl // 16-byte aligned. Returns true on success, false otherwise
224580af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
2246b9c1b51eSKate Stone                                               StackFrame *frame_ptr) {
2247a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2248a0f08674SEwan Crawford 
224980af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
2250a0f08674SEwan Crawford     if (log)
2251b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2252a0f08674SEwan Crawford     return false;
2253a0f08674SEwan Crawford   }
2254a0f08674SEwan Crawford 
225580af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
225680af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
2257a0f08674SEwan Crawford 
225880af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
225980af0b9eSLuke Drummond                          *alloc->address.get(), 0, 1, 0);
226080af0b9eSLuke Drummond   if (written < 0) {
2261a0f08674SEwan Crawford     if (log)
2262b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2263a0f08674SEwan Crawford     return false;
226480af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
2265a0f08674SEwan Crawford     if (log)
2266b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
2267a0f08674SEwan Crawford     return false;
2268a0f08674SEwan Crawford   }
2269a0f08674SEwan Crawford 
2270a0f08674SEwan Crawford   uint64_t result = 0;
227180af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2272a0f08674SEwan Crawford     return false;
2273a0f08674SEwan Crawford 
2274a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
227580af0b9eSLuke Drummond   alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
2276a0f08674SEwan Crawford 
2277a0f08674SEwan Crawford   return true;
2278a0f08674SEwan Crawford }
2279a0f08674SEwan Crawford 
228015f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
228180af0b9eSLuke Drummond bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2282b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
228315f2bd95SEwan Crawford   // GetOffsetPointer()
228480af0b9eSLuke Drummond   if (!JITDataPointer(alloc, frame_ptr))
228515f2bd95SEwan Crawford     return false;
228615f2bd95SEwan Crawford 
228715f2bd95SEwan Crawford   // rsaAllocationGetType()
228880af0b9eSLuke Drummond   if (!JITTypePointer(alloc, frame_ptr))
228915f2bd95SEwan Crawford     return false;
229015f2bd95SEwan Crawford 
229115f2bd95SEwan Crawford   // rsaTypeGetNativeData()
229280af0b9eSLuke Drummond   if (!JITTypePacked(alloc, frame_ptr))
229315f2bd95SEwan Crawford     return false;
229415f2bd95SEwan Crawford 
229515f2bd95SEwan Crawford   // rsaElementGetNativeData()
229680af0b9eSLuke Drummond   if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
229715f2bd95SEwan Crawford     return false;
229815f2bd95SEwan Crawford 
22998b244e21SEwan Crawford   // Sets the datum_size member in Element
230080af0b9eSLuke Drummond   SetElementSize(alloc->element);
23018b244e21SEwan Crawford 
230255232f09SEwan Crawford   // Use GetOffsetPointer() to infer size of the allocation
230380af0b9eSLuke Drummond   if (!JITAllocationSize(alloc, frame_ptr))
230455232f09SEwan Crawford     return false;
230555232f09SEwan Crawford 
230655232f09SEwan Crawford   return true;
230755232f09SEwan Crawford }
230855232f09SEwan Crawford 
2309b9c1b51eSKate Stone // Function attempts to set the type_name member of the paramaterised Element
231005097246SAdrian Prantl // object. This string should be the name of the struct type the Element
231105097246SAdrian Prantl // represents. We need this string for pretty printing the Element to users.
2312b9c1b51eSKate Stone void RenderScriptRuntime::FindStructTypeName(Element &elem,
2313b9c1b51eSKate Stone                                              StackFrame *frame_ptr) {
23148b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
23158b244e21SEwan Crawford 
23168b244e21SEwan Crawford   if (!elem.type_name.IsEmpty()) // Name already set
23178b244e21SEwan Crawford     return;
23188b244e21SEwan Crawford   else
2319b9c1b51eSKate Stone     elem.type_name = Element::GetFallbackStructName(); // Default type name if
2320b9c1b51eSKate Stone                                                        // we don't succeed
23218b244e21SEwan Crawford 
23228b244e21SEwan Crawford   // Find all the global variables from the script rs modules
232380af0b9eSLuke Drummond   VariableList var_list;
23248b244e21SEwan Crawford   for (auto module_sp : m_rsmodules)
232595eae423SZachary Turner     module_sp->m_module->FindGlobalVariables(
232634cda14bSPavel Labath         RegularExpression(llvm::StringRef(".")), UINT32_MAX, var_list);
23278b244e21SEwan Crawford 
2328b9c1b51eSKate Stone   // Iterate over all the global variables looking for one with a matching type
232905097246SAdrian Prantl   // to the Element. We make the assumption a match exists since there needs to
233005097246SAdrian Prantl   // be a global variable to reflect the struct type back into java host code.
233180af0b9eSLuke Drummond   for (uint32_t i = 0; i < var_list.GetSize(); ++i) {
233280af0b9eSLuke Drummond     const VariableSP var_sp(var_list.GetVariableAtIndex(i));
23338b244e21SEwan Crawford     if (!var_sp)
23348b244e21SEwan Crawford       continue;
23358b244e21SEwan Crawford 
23368b244e21SEwan Crawford     ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
23378b244e21SEwan Crawford     if (!valobj_sp)
23388b244e21SEwan Crawford       continue;
23398b244e21SEwan Crawford 
23408b244e21SEwan Crawford     // Find the number of variable fields.
2341b9c1b51eSKate Stone     // If it has no fields, or more fields than our Element, then it can't be
234205097246SAdrian Prantl     // the struct we're looking for. Don't check for equality since RS can add
234305097246SAdrian Prantl     // extra struct members for padding.
23448b244e21SEwan Crawford     size_t num_children = valobj_sp->GetNumChildren();
23458b244e21SEwan Crawford     if (num_children > elem.children.size() || num_children == 0)
23468b244e21SEwan Crawford       continue;
23478b244e21SEwan Crawford 
234805097246SAdrian Prantl     // Iterate over children looking for members with matching field names. If
234905097246SAdrian Prantl     // all the field names match, this is likely the struct we want.
2350b9c1b51eSKate Stone     //   TODO: This could be made more robust by also checking children data
2351b9c1b51eSKate Stone     //   sizes, or array size
23528b244e21SEwan Crawford     bool found = true;
235380af0b9eSLuke Drummond     for (size_t i = 0; i < num_children; ++i) {
235480af0b9eSLuke Drummond       ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
235580af0b9eSLuke Drummond       if (!child || (child->GetName() != elem.children[i].type_name)) {
23568b244e21SEwan Crawford         found = false;
23578b244e21SEwan Crawford         break;
23588b244e21SEwan Crawford       }
23598b244e21SEwan Crawford     }
23608b244e21SEwan Crawford 
2361b9c1b51eSKate Stone     // RS can add extra struct members for padding in the format
2362b9c1b51eSKate Stone     // '#rs_padding_[0-9]+'
2363b9c1b51eSKate Stone     if (found && num_children < elem.children.size()) {
2364b3f7f69dSAidan Dodds       const uint32_t size_diff = elem.children.size() - num_children;
23658b244e21SEwan Crawford       if (log)
2366b9c1b51eSKate Stone         log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2367b9c1b51eSKate Stone                     size_diff);
23688b244e21SEwan Crawford 
236980af0b9eSLuke Drummond       for (uint32_t i = 0; i < size_diff; ++i) {
237080af0b9eSLuke Drummond         const ConstString &name = elem.children[num_children + i].type_name;
23718b244e21SEwan Crawford         if (strcmp(name.AsCString(), "#rs_padding") < 0)
23728b244e21SEwan Crawford           found = false;
23738b244e21SEwan Crawford       }
23748b244e21SEwan Crawford     }
23758b244e21SEwan Crawford 
237680af0b9eSLuke Drummond     // We've found a global variable with matching type
2377b9c1b51eSKate Stone     if (found) {
23788b244e21SEwan Crawford       // Dereference since our Element type isn't a pointer.
2379b9c1b51eSKate Stone       if (valobj_sp->IsPointerType()) {
238097206d57SZachary Turner         Status err;
23818b244e21SEwan Crawford         ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
23828b244e21SEwan Crawford         if (!err.Fail())
23838b244e21SEwan Crawford           valobj_sp = deref_valobj;
23848b244e21SEwan Crawford       }
23858b244e21SEwan Crawford 
23868b244e21SEwan Crawford       // Save name of variable in Element.
23878b244e21SEwan Crawford       elem.type_name = valobj_sp->GetTypeName();
23888b244e21SEwan Crawford       if (log)
2389b9c1b51eSKate Stone         log->Printf("%s - element name set to %s", __FUNCTION__,
2390b9c1b51eSKate Stone                     elem.type_name.AsCString());
23918b244e21SEwan Crawford 
23928b244e21SEwan Crawford       return;
23938b244e21SEwan Crawford     }
23948b244e21SEwan Crawford   }
23958b244e21SEwan Crawford }
23968b244e21SEwan Crawford 
2397b9c1b51eSKate Stone // Function sets the datum_size member of Element. Representing the size of a
239805097246SAdrian Prantl // single instance including padding. Assumes the relevant allocation
239905097246SAdrian Prantl // information has already been jitted.
2400b9c1b51eSKate Stone void RenderScriptRuntime::SetElementSize(Element &elem) {
24018b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
24028b244e21SEwan Crawford   const Element::DataType type = *elem.type.get();
2403b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2404b9c1b51eSKate Stone          "Invalid allocation type");
240555232f09SEwan Crawford 
2406b3f7f69dSAidan Dodds   const uint32_t vec_size = *elem.type_vec_size.get();
2407b3f7f69dSAidan Dodds   uint32_t data_size = 0;
2408b3f7f69dSAidan Dodds   uint32_t padding = 0;
240955232f09SEwan Crawford 
24108b244e21SEwan Crawford   // Element is of a struct type, calculate size recursively.
2411b9c1b51eSKate Stone   if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2412b9c1b51eSKate Stone     for (Element &child : elem.children) {
24138b244e21SEwan Crawford       SetElementSize(child);
2414b9c1b51eSKate Stone       const uint32_t array_size =
2415b9c1b51eSKate Stone           child.array_size.isValid() ? *child.array_size.get() : 1;
24168b244e21SEwan Crawford       data_size += *child.datum_size.get() * array_size;
24178b244e21SEwan Crawford     }
24188b244e21SEwan Crawford   }
2419b3f7f69dSAidan Dodds   // These have been packed already
2420b3f7f69dSAidan Dodds   else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2421b3f7f69dSAidan Dodds            type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2422b9c1b51eSKate Stone            type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
24232e920715SEwan Crawford     data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2424b9c1b51eSKate Stone   } else if (type < Element::RS_TYPE_ELEMENT) {
2425b9c1b51eSKate Stone     data_size =
2426b9c1b51eSKate Stone         vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
24272e920715SEwan Crawford     if (vec_size == 3)
24282e920715SEwan Crawford       padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2429b9c1b51eSKate Stone   } else
2430b9c1b51eSKate Stone     data_size =
2431b9c1b51eSKate Stone         GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
24328b244e21SEwan Crawford 
24338b244e21SEwan Crawford   elem.padding = padding;
24348b244e21SEwan Crawford   elem.datum_size = data_size + padding;
24358b244e21SEwan Crawford   if (log)
2436b9c1b51eSKate Stone     log->Printf("%s - element size set to %" PRIu32, __FUNCTION__,
2437b9c1b51eSKate Stone                 data_size + padding);
243855232f09SEwan Crawford }
243955232f09SEwan Crawford 
244005097246SAdrian Prantl // Given an allocation, this function copies the allocation contents from
244105097246SAdrian Prantl // device into a buffer on the heap. Returning a shared pointer to the buffer
244205097246SAdrian Prantl // containing the data.
244355232f09SEwan Crawford std::shared_ptr<uint8_t>
244480af0b9eSLuke Drummond RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2445b9c1b51eSKate Stone                                        StackFrame *frame_ptr) {
244655232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
244755232f09SEwan Crawford 
244855232f09SEwan Crawford   // JIT all the allocation details
244980af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
245055232f09SEwan Crawford     if (log)
2451b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info",
2452b9c1b51eSKate Stone                   __FUNCTION__);
245355232f09SEwan Crawford 
245480af0b9eSLuke Drummond     if (!RefreshAllocation(alloc, frame_ptr)) {
245555232f09SEwan Crawford       if (log)
2456b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
245755232f09SEwan Crawford       return nullptr;
245855232f09SEwan Crawford     }
245955232f09SEwan Crawford   }
246055232f09SEwan Crawford 
246180af0b9eSLuke Drummond   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
246280af0b9eSLuke Drummond          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
246380af0b9eSLuke Drummond          "Allocation information not available");
246455232f09SEwan Crawford 
246555232f09SEwan Crawford   // Allocate a buffer to copy data into
246680af0b9eSLuke Drummond   const uint32_t size = *alloc->size.get();
246755232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2468b9c1b51eSKate Stone   if (!buffer) {
246955232f09SEwan Crawford     if (log)
2470b9c1b51eSKate Stone       log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer",
2471b9c1b51eSKate Stone                   __FUNCTION__, size);
247255232f09SEwan Crawford     return nullptr;
247355232f09SEwan Crawford   }
247455232f09SEwan Crawford 
247555232f09SEwan Crawford   // Read the inferior memory
247697206d57SZachary Turner   Status err;
247780af0b9eSLuke Drummond   lldb::addr_t data_ptr = *alloc->data_ptr.get();
247880af0b9eSLuke Drummond   GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
247980af0b9eSLuke Drummond   if (err.Fail()) {
248055232f09SEwan Crawford     if (log)
2481b9c1b51eSKate Stone       log->Printf("%s - '%s' Couldn't read %" PRIu32
2482b9c1b51eSKate Stone                   " bytes of allocation data from 0x%" PRIx64,
248380af0b9eSLuke Drummond                   __FUNCTION__, err.AsCString(), size, data_ptr);
248455232f09SEwan Crawford     return nullptr;
248555232f09SEwan Crawford   }
248655232f09SEwan Crawford 
248755232f09SEwan Crawford   return buffer;
248855232f09SEwan Crawford }
248955232f09SEwan Crawford 
249005097246SAdrian Prantl // Function copies data from a binary file into an allocation. There is a
249105097246SAdrian Prantl // header at the start of the file, FileHeader, before the data content itself.
2492b9c1b51eSKate Stone // Information from this header is used to display warnings to the user about
2493b9c1b51eSKate Stone // incompatibilities
2494b9c1b51eSKate Stone bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
249580af0b9eSLuke Drummond                                          const char *path,
2496b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
249755232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
249855232f09SEwan Crawford 
249955232f09SEwan Crawford   // Find allocation with the given id
250055232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
250155232f09SEwan Crawford   if (!alloc)
250255232f09SEwan Crawford     return false;
250355232f09SEwan Crawford 
250455232f09SEwan Crawford   if (log)
2505b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2506b9c1b51eSKate Stone                 *alloc->address.get());
250755232f09SEwan Crawford 
250855232f09SEwan Crawford   // JIT all the allocation details
250980af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
251055232f09SEwan Crawford     if (log)
2511b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2512b9c1b51eSKate Stone                   __FUNCTION__);
251355232f09SEwan Crawford 
2514b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
251555232f09SEwan Crawford       if (log)
2516b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
25174cfc9198SSylvestre Ledru       return false;
251855232f09SEwan Crawford     }
251955232f09SEwan Crawford   }
252055232f09SEwan Crawford 
2521b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2522b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2523b9c1b51eSKate Stone          alloc->element.datum_size.isValid() &&
2524b9c1b51eSKate Stone          "Allocation information not available");
252555232f09SEwan Crawford 
252655232f09SEwan Crawford   // Check we can read from file
25278f3be7a3SJonas Devlieghere   FileSpec file(path);
25288f3be7a3SJonas Devlieghere   FileSystem::Instance().Resolve(file);
2529dbd7fabaSJonas Devlieghere   if (!FileSystem::Instance().Exists(file)) {
253080af0b9eSLuke Drummond     strm.Printf("Error: File %s does not exist", path);
253155232f09SEwan Crawford     strm.EOL();
253255232f09SEwan Crawford     return false;
253355232f09SEwan Crawford   }
253455232f09SEwan Crawford 
25357c5310bbSJonas Devlieghere   if (!FileSystem::Instance().Readable(file)) {
253680af0b9eSLuke Drummond     strm.Printf("Error: File %s does not have readable permissions", path);
253755232f09SEwan Crawford     strm.EOL();
253855232f09SEwan Crawford     return false;
253955232f09SEwan Crawford   }
254055232f09SEwan Crawford 
254155232f09SEwan Crawford   // Read file into data buffer
2542*87e403aaSJonas Devlieghere   auto data_sp = FileSystem::Instance().CreateDataBuffer(file.GetPath());
254355232f09SEwan Crawford 
254455232f09SEwan Crawford   // Cast start of buffer to FileHeader and use pointer to read metadata
254580af0b9eSLuke Drummond   void *file_buf = data_sp->GetBytes();
254680af0b9eSLuke Drummond   if (file_buf == nullptr ||
2547b9c1b51eSKate Stone       data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2548b9c1b51eSKate Stone                                 sizeof(AllocationDetails::ElementHeader))) {
254980af0b9eSLuke Drummond     strm.Printf("Error: File %s does not contain enough data for header", path);
255026e52a70SEwan Crawford     strm.EOL();
255126e52a70SEwan Crawford     return false;
255226e52a70SEwan Crawford   }
2553b9c1b51eSKate Stone   const AllocationDetails::FileHeader *file_header =
255480af0b9eSLuke Drummond       static_cast<AllocationDetails::FileHeader *>(file_buf);
255555232f09SEwan Crawford 
255626e52a70SEwan Crawford   // Check file starts with ascii characters "RSAD"
2557b9c1b51eSKate Stone   if (memcmp(file_header->ident, "RSAD", 4)) {
2558b9c1b51eSKate Stone     strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2559b9c1b51eSKate Stone                 "dump. Are you sure this is the correct file?");
256026e52a70SEwan Crawford     strm.EOL();
256126e52a70SEwan Crawford     return false;
256226e52a70SEwan Crawford   }
256326e52a70SEwan Crawford 
256426e52a70SEwan Crawford   // Look at the type of the root element in the header
256580af0b9eSLuke Drummond   AllocationDetails::ElementHeader root_el_hdr;
256680af0b9eSLuke Drummond   memcpy(&root_el_hdr, static_cast<uint8_t *>(file_buf) +
2567b9c1b51eSKate Stone                            sizeof(AllocationDetails::FileHeader),
256826e52a70SEwan Crawford          sizeof(AllocationDetails::ElementHeader));
256955232f09SEwan Crawford 
257055232f09SEwan Crawford   if (log)
2571b9c1b51eSKate Stone     log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32,
257280af0b9eSLuke Drummond                 __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
257355232f09SEwan Crawford 
2574b9c1b51eSKate Stone   // Check if the target allocation and file both have the same number of bytes
2575b9c1b51eSKate Stone   // for an Element
257680af0b9eSLuke Drummond   if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2577b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2578b9c1b51eSKate Stone                 " bytes, allocation %" PRIu32 " bytes",
257980af0b9eSLuke Drummond                 root_el_hdr.element_size, *alloc->element.datum_size.get());
258055232f09SEwan Crawford     strm.EOL();
258155232f09SEwan Crawford   }
258255232f09SEwan Crawford 
258326e52a70SEwan Crawford   // Check if the target allocation and file both have the same type
2584b3f7f69dSAidan Dodds   const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
258580af0b9eSLuke Drummond   const uint32_t file_type = root_el_hdr.type;
258626e52a70SEwan Crawford 
2587b9c1b51eSKate Stone   if (file_type > Element::RS_TYPE_FONT) {
258826e52a70SEwan Crawford     strm.Printf("Warning: File has unknown allocation type");
258926e52a70SEwan Crawford     strm.EOL();
2590b9c1b51eSKate Stone   } else if (alloc_type != file_type) {
2591b9c1b51eSKate Stone     // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2592b9c1b51eSKate Stone     // array
259380af0b9eSLuke Drummond     uint32_t target_type_name_idx = alloc_type;
259480af0b9eSLuke Drummond     uint32_t head_type_name_idx = file_type;
2595b9c1b51eSKate Stone     if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2596b9c1b51eSKate Stone         alloc_type <= Element::RS_TYPE_FONT)
259780af0b9eSLuke Drummond       target_type_name_idx = static_cast<Element::DataType>(
2598b9c1b51eSKate Stone           (alloc_type - Element::RS_TYPE_ELEMENT) +
2599b3f7f69dSAidan Dodds           Element::RS_TYPE_MATRIX_2X2 + 1);
26002e920715SEwan Crawford 
2601b9c1b51eSKate Stone     if (file_type >= Element::RS_TYPE_ELEMENT &&
2602b9c1b51eSKate Stone         file_type <= Element::RS_TYPE_FONT)
260380af0b9eSLuke Drummond       head_type_name_idx = static_cast<Element::DataType>(
2604b9c1b51eSKate Stone           (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2605b9c1b51eSKate Stone           1);
26062e920715SEwan Crawford 
260780af0b9eSLuke Drummond     const char *head_type_name =
260880af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
260980af0b9eSLuke Drummond     const char *target_type_name =
261080af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
261155232f09SEwan Crawford 
2612b9c1b51eSKate Stone     strm.Printf(
2613b9c1b51eSKate Stone         "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
261480af0b9eSLuke Drummond         head_type_name, target_type_name);
261555232f09SEwan Crawford     strm.EOL();
261655232f09SEwan Crawford   }
261755232f09SEwan Crawford 
261826e52a70SEwan Crawford   // Advance buffer past header
261980af0b9eSLuke Drummond   file_buf = static_cast<uint8_t *>(file_buf) + file_header->hdr_size;
262026e52a70SEwan Crawford 
262155232f09SEwan Crawford   // Calculate size of allocation data in file
262280af0b9eSLuke Drummond   size_t size = data_sp->GetByteSize() - file_header->hdr_size;
262355232f09SEwan Crawford 
262405097246SAdrian Prantl   // Check if the target allocation and file both have the same total data
262505097246SAdrian Prantl   // size.
2626b3f7f69dSAidan Dodds   const uint32_t alloc_size = *alloc->size.get();
262780af0b9eSLuke Drummond   if (alloc_size != size) {
2628b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2629b9c1b51eSKate Stone                 " bytes, allocation 0x%" PRIx32 " bytes",
263080af0b9eSLuke Drummond                 (uint64_t)size, alloc_size);
263155232f09SEwan Crawford     strm.EOL();
263280af0b9eSLuke Drummond     // Set length to copy to minimum
263380af0b9eSLuke Drummond     size = alloc_size < size ? alloc_size : size;
263455232f09SEwan Crawford   }
263555232f09SEwan Crawford 
263655232f09SEwan Crawford   // Copy file data from our buffer into the target allocation.
263755232f09SEwan Crawford   lldb::addr_t alloc_data = *alloc->data_ptr.get();
263897206d57SZachary Turner   Status err;
263980af0b9eSLuke Drummond   size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
264080af0b9eSLuke Drummond   if (!err.Success() || written != size) {
264180af0b9eSLuke Drummond     strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
264255232f09SEwan Crawford     strm.EOL();
264355232f09SEwan Crawford     return false;
264455232f09SEwan Crawford   }
264555232f09SEwan Crawford 
264680af0b9eSLuke Drummond   strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2647b9c1b51eSKate Stone               alloc->id);
264855232f09SEwan Crawford   strm.EOL();
264955232f09SEwan Crawford 
265055232f09SEwan Crawford   return true;
265155232f09SEwan Crawford }
265255232f09SEwan Crawford 
2653b9c1b51eSKate Stone // Function takes as parameters a byte buffer, which will eventually be written
265480af0b9eSLuke Drummond // to file as the element header, an offset into that buffer, and an Element
265505097246SAdrian Prantl // that will be saved into the buffer at the parametrised offset. Return value
265605097246SAdrian Prantl // is the new offset after writing the element into the buffer. Elements are
265705097246SAdrian Prantl // saved to the file as the ElementHeader struct followed by offsets to the
265805097246SAdrian Prantl // structs of all the element's children.
2659b9c1b51eSKate Stone size_t RenderScriptRuntime::PopulateElementHeaders(
2660b9c1b51eSKate Stone     const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2661b9c1b51eSKate Stone     const Element &elem) {
266205097246SAdrian Prantl   // File struct for an element header with all the relevant details copied
266305097246SAdrian Prantl   // from elem. We assume members are valid already.
266426e52a70SEwan Crawford   AllocationDetails::ElementHeader elem_header;
266526e52a70SEwan Crawford   elem_header.type = *elem.type.get();
266626e52a70SEwan Crawford   elem_header.kind = *elem.type_kind.get();
266726e52a70SEwan Crawford   elem_header.element_size = *elem.datum_size.get();
266826e52a70SEwan Crawford   elem_header.vector_size = *elem.type_vec_size.get();
2669b9c1b51eSKate Stone   elem_header.array_size =
2670b9c1b51eSKate Stone       elem.array_size.isValid() ? *elem.array_size.get() : 0;
267126e52a70SEwan Crawford   const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
267226e52a70SEwan Crawford 
267305097246SAdrian Prantl   // Copy struct into buffer and advance offset We assume that header_buffer
267405097246SAdrian Prantl   // has been checked for nullptr before this method is called
267526e52a70SEwan Crawford   memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
267626e52a70SEwan Crawford   offset += elem_header_size;
267726e52a70SEwan Crawford 
267826e52a70SEwan Crawford   // Starting offset of child ElementHeader struct
2679b9c1b51eSKate Stone   size_t child_offset =
2680b9c1b51eSKate Stone       offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2681b9c1b51eSKate Stone   for (const RenderScriptRuntime::Element &child : elem.children) {
2682b9c1b51eSKate Stone     // Recursively populate the buffer with the element header structs of
268380af0b9eSLuke Drummond     // children. Then save the offsets where they were set after the parent
268480af0b9eSLuke Drummond     // element header.
268526e52a70SEwan Crawford     memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
268626e52a70SEwan Crawford     offset += sizeof(uint32_t);
268726e52a70SEwan Crawford 
268826e52a70SEwan Crawford     child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
268926e52a70SEwan Crawford   }
269026e52a70SEwan Crawford 
269126e52a70SEwan Crawford   // Zero indicates no more children
269226e52a70SEwan Crawford   memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
269326e52a70SEwan Crawford 
269426e52a70SEwan Crawford   return child_offset;
269526e52a70SEwan Crawford }
269626e52a70SEwan Crawford 
2697b9c1b51eSKate Stone // Given an Element object this function returns the total size needed in the
269880af0b9eSLuke Drummond // file header to store the element's details. Taking into account the size of
269980af0b9eSLuke Drummond // the element header struct, plus the offsets to all the element's children.
2700b9c1b51eSKate Stone // Function is recursive so that the size of all ancestors is taken into
2701b9c1b51eSKate Stone // account.
2702b9c1b51eSKate Stone size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
270380af0b9eSLuke Drummond   // Offsets to children plus zero terminator
270480af0b9eSLuke Drummond   size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
270580af0b9eSLuke Drummond   // Size of header struct with type details
270680af0b9eSLuke Drummond   size += sizeof(AllocationDetails::ElementHeader);
270726e52a70SEwan Crawford 
270826e52a70SEwan Crawford   // Calculate recursively for all descendants
270926e52a70SEwan Crawford   for (const Element &child : elem.children)
271026e52a70SEwan Crawford     size += CalculateElementHeaderSize(child);
271126e52a70SEwan Crawford 
271226e52a70SEwan Crawford   return size;
271326e52a70SEwan Crawford }
271426e52a70SEwan Crawford 
271505097246SAdrian Prantl // Function copies allocation contents into a binary file. This file can then
271605097246SAdrian Prantl // be loaded later into a different allocation. There is a header, FileHeader,
271780af0b9eSLuke Drummond // before the allocation data containing meta-data.
2718b9c1b51eSKate Stone bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
271980af0b9eSLuke Drummond                                          const char *path,
2720b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
272155232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
272255232f09SEwan Crawford 
272355232f09SEwan Crawford   // Find allocation with the given id
272455232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
272555232f09SEwan Crawford   if (!alloc)
272655232f09SEwan Crawford     return false;
272755232f09SEwan Crawford 
272855232f09SEwan Crawford   if (log)
2729b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2730b9c1b51eSKate Stone                 *alloc->address.get());
273155232f09SEwan Crawford 
273255232f09SEwan Crawford   // JIT all the allocation details
273380af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
273455232f09SEwan Crawford     if (log)
2735b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2736b9c1b51eSKate Stone                   __FUNCTION__);
273755232f09SEwan Crawford 
2738b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
273955232f09SEwan Crawford       if (log)
2740b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
27414cfc9198SSylvestre Ledru       return false;
274255232f09SEwan Crawford     }
274355232f09SEwan Crawford   }
274455232f09SEwan Crawford 
2745b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2746b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() &&
2747b9c1b51eSKate Stone          alloc->element.datum_size.get() &&
2748b9c1b51eSKate Stone          alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2749b3f7f69dSAidan Dodds          "Allocation information not available");
275055232f09SEwan Crawford 
275155232f09SEwan Crawford   // Check we can create writable file
27528f3be7a3SJonas Devlieghere   FileSpec file_spec(path);
27538f3be7a3SJonas Devlieghere   FileSystem::Instance().Resolve(file_spec);
275450bc1ed2SJonas Devlieghere   File file;
275550bc1ed2SJonas Devlieghere   FileSystem::Instance().Open(file, file_spec,
275650bc1ed2SJonas Devlieghere                               File::eOpenOptionWrite |
275750bc1ed2SJonas Devlieghere                                   File::eOpenOptionCanCreate |
2758b9c1b51eSKate Stone                                   File::eOpenOptionTruncate);
275950bc1ed2SJonas Devlieghere 
2760b9c1b51eSKate Stone   if (!file) {
276180af0b9eSLuke Drummond     strm.Printf("Error: Failed to open '%s' for writing", path);
276255232f09SEwan Crawford     strm.EOL();
276355232f09SEwan Crawford     return false;
276455232f09SEwan Crawford   }
276555232f09SEwan Crawford 
276655232f09SEwan Crawford   // Read allocation into buffer of heap memory
276755232f09SEwan Crawford   const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2768b9c1b51eSKate Stone   if (!buffer) {
276955232f09SEwan Crawford     strm.Printf("Error: Couldn't read allocation data into buffer");
277055232f09SEwan Crawford     strm.EOL();
277155232f09SEwan Crawford     return false;
277255232f09SEwan Crawford   }
277355232f09SEwan Crawford 
277455232f09SEwan Crawford   // Create the file header
277555232f09SEwan Crawford   AllocationDetails::FileHeader head;
2776b3f7f69dSAidan Dodds   memcpy(head.ident, "RSAD", 4);
27772d62328aSEwan Crawford   head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
27782d62328aSEwan Crawford   head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
27792d62328aSEwan Crawford   head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
278026e52a70SEwan Crawford 
278126e52a70SEwan Crawford   const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2782b9c1b51eSKate Stone   assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2783b9c1b51eSKate Stone              UINT16_MAX &&
2784b9c1b51eSKate Stone          "Element header too large");
2785b9c1b51eSKate Stone   head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2786b9c1b51eSKate Stone                                         element_header_size);
278755232f09SEwan Crawford 
278855232f09SEwan Crawford   // Write the file header
278955232f09SEwan Crawford   size_t num_bytes = sizeof(AllocationDetails::FileHeader);
279026e52a70SEwan Crawford   if (log)
2791b9c1b51eSKate Stone     log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2792b9c1b51eSKate Stone                 (uint64_t)num_bytes);
279326e52a70SEwan Crawford 
279497206d57SZachary Turner   Status err = file.Write(&head, num_bytes);
2795b9c1b51eSKate Stone   if (!err.Success()) {
279680af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
279726e52a70SEwan Crawford     strm.EOL();
279826e52a70SEwan Crawford     return false;
279926e52a70SEwan Crawford   }
280026e52a70SEwan Crawford 
280126e52a70SEwan Crawford   // Create the headers describing the element type of the allocation.
2802b9c1b51eSKate Stone   std::shared_ptr<uint8_t> element_header_buffer(
2803b9c1b51eSKate Stone       new uint8_t[element_header_size]);
2804b9c1b51eSKate Stone   if (element_header_buffer == nullptr) {
2805b9c1b51eSKate Stone     strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2806b9c1b51eSKate Stone                 " bytes on the heap",
2807b9c1b51eSKate Stone                 (uint64_t)element_header_size);
280826e52a70SEwan Crawford     strm.EOL();
280926e52a70SEwan Crawford     return false;
281026e52a70SEwan Crawford   }
281126e52a70SEwan Crawford 
281226e52a70SEwan Crawford   PopulateElementHeaders(element_header_buffer, 0, alloc->element);
281326e52a70SEwan Crawford 
281426e52a70SEwan Crawford   // Write headers for allocation element type to file
281526e52a70SEwan Crawford   num_bytes = element_header_size;
281626e52a70SEwan Crawford   if (log)
2817b9c1b51eSKate Stone     log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.",
2818b9c1b51eSKate Stone                 __FUNCTION__, (uint64_t)num_bytes);
281926e52a70SEwan Crawford 
282026e52a70SEwan Crawford   err = file.Write(element_header_buffer.get(), num_bytes);
2821b9c1b51eSKate Stone   if (!err.Success()) {
282280af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
282355232f09SEwan Crawford     strm.EOL();
282455232f09SEwan Crawford     return false;
282555232f09SEwan Crawford   }
282655232f09SEwan Crawford 
282755232f09SEwan Crawford   // Write allocation data to file
282855232f09SEwan Crawford   num_bytes = static_cast<size_t>(*alloc->size.get());
282955232f09SEwan Crawford   if (log)
2830b9c1b51eSKate Stone     log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2831b9c1b51eSKate Stone                 (uint64_t)num_bytes);
283255232f09SEwan Crawford 
283355232f09SEwan Crawford   err = file.Write(buffer.get(), num_bytes);
2834b9c1b51eSKate Stone   if (!err.Success()) {
283580af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
283655232f09SEwan Crawford     strm.EOL();
283755232f09SEwan Crawford     return false;
283855232f09SEwan Crawford   }
283955232f09SEwan Crawford 
284080af0b9eSLuke Drummond   strm.Printf("Allocation written to file '%s'", path);
284155232f09SEwan Crawford   strm.EOL();
284215f2bd95SEwan Crawford   return true;
284315f2bd95SEwan Crawford }
284415f2bd95SEwan Crawford 
2845b9c1b51eSKate Stone bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
28464640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
28474640cde1SColin Riley 
2848b9c1b51eSKate Stone   if (module_sp) {
2849b9c1b51eSKate Stone     for (const auto &rs_module : m_rsmodules) {
2850b9c1b51eSKate Stone       if (rs_module->m_module == module_sp) {
285105097246SAdrian Prantl         // Check if the user has enabled automatically breaking on all RS
285205097246SAdrian Prantl         // kernels.
28537dc7771cSEwan Crawford         if (m_breakAllKernels)
28547dc7771cSEwan Crawford           BreakOnModuleKernels(rs_module);
28557dc7771cSEwan Crawford 
28565ec532a9SColin Riley         return false;
28575ec532a9SColin Riley       }
28587dc7771cSEwan Crawford     }
2859ef20b08fSColin Riley     bool module_loaded = false;
2860b9c1b51eSKate Stone     switch (GetModuleKind(module_sp)) {
2861b9c1b51eSKate Stone     case eModuleKindKernelObj: {
28624640cde1SColin Riley       RSModuleDescriptorSP module_desc;
28634640cde1SColin Riley       module_desc.reset(new RSModuleDescriptor(module_sp));
2864b9c1b51eSKate Stone       if (module_desc->ParseRSInfo()) {
28655ec532a9SColin Riley         m_rsmodules.push_back(module_desc);
286647d64161SLuke Drummond         module_desc->WarnIfVersionMismatch(GetProcess()
286747d64161SLuke Drummond                                                ->GetTarget()
286847d64161SLuke Drummond                                                .GetDebugger()
286947d64161SLuke Drummond                                                .GetAsyncOutputStream()
287047d64161SLuke Drummond                                                .get());
2871ef20b08fSColin Riley         module_loaded = true;
28725ec532a9SColin Riley       }
2873b9c1b51eSKate Stone       if (module_loaded) {
28744640cde1SColin Riley         FixupScriptDetails(module_desc);
28754640cde1SColin Riley       }
2876ef20b08fSColin Riley       break;
2877ef20b08fSColin Riley     }
2878b9c1b51eSKate Stone     case eModuleKindDriver: {
2879b9c1b51eSKate Stone       if (!m_libRSDriver) {
28804640cde1SColin Riley         m_libRSDriver = module_sp;
28814640cde1SColin Riley         LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
28824640cde1SColin Riley       }
28834640cde1SColin Riley       break;
28844640cde1SColin Riley     }
2885b9c1b51eSKate Stone     case eModuleKindImpl: {
288621fed052SAidan Dodds       if (!m_libRSCpuRef) {
28874640cde1SColin Riley         m_libRSCpuRef = module_sp;
288821fed052SAidan Dodds         LoadRuntimeHooks(m_libRSCpuRef, RenderScriptRuntime::eModuleKindImpl);
288921fed052SAidan Dodds       }
28904640cde1SColin Riley       break;
28914640cde1SColin Riley     }
2892b9c1b51eSKate Stone     case eModuleKindLibRS: {
2893b9c1b51eSKate Stone       if (!m_libRS) {
28944640cde1SColin Riley         m_libRS = module_sp;
28954640cde1SColin Riley         static ConstString gDbgPresentStr("gDebuggerPresent");
2896b9c1b51eSKate Stone         const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2897b9c1b51eSKate Stone             gDbgPresentStr, eSymbolTypeData);
2898b9c1b51eSKate Stone         if (debug_present) {
289997206d57SZachary Turner           Status err;
29004640cde1SColin Riley           uint32_t flag = 0x00000001U;
29014640cde1SColin Riley           Target &target = GetProcess()->GetTarget();
2902358cf1eaSGreg Clayton           addr_t addr = debug_present->GetLoadAddress(&target);
290380af0b9eSLuke Drummond           GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
290480af0b9eSLuke Drummond           if (err.Success()) {
29054640cde1SColin Riley             if (log)
2906b9c1b51eSKate Stone               log->Printf("%s - debugger present flag set on debugee.",
2907b9c1b51eSKate Stone                           __FUNCTION__);
29084640cde1SColin Riley 
29094640cde1SColin Riley             m_debuggerPresentFlagged = true;
2910b9c1b51eSKate Stone           } else if (log) {
2911b9c1b51eSKate Stone             log->Printf("%s - error writing debugger present flags '%s' ",
291280af0b9eSLuke Drummond                         __FUNCTION__, err.AsCString());
29134640cde1SColin Riley           }
2914b9c1b51eSKate Stone         } else if (log) {
2915b9c1b51eSKate Stone           log->Printf(
2916b9c1b51eSKate Stone               "%s - error writing debugger present flags - symbol not found",
2917b9c1b51eSKate Stone               __FUNCTION__);
29184640cde1SColin Riley         }
29194640cde1SColin Riley       }
29204640cde1SColin Riley       break;
29214640cde1SColin Riley     }
2922ef20b08fSColin Riley     default:
2923ef20b08fSColin Riley       break;
2924ef20b08fSColin Riley     }
2925ef20b08fSColin Riley     if (module_loaded)
2926ef20b08fSColin Riley       Update();
2927ef20b08fSColin Riley     return module_loaded;
29285ec532a9SColin Riley   }
29295ec532a9SColin Riley   return false;
29305ec532a9SColin Riley }
29315ec532a9SColin Riley 
2932b9c1b51eSKate Stone void RenderScriptRuntime::Update() {
2933b9c1b51eSKate Stone   if (m_rsmodules.size() > 0) {
2934b9c1b51eSKate Stone     if (!m_initiated) {
2935ef20b08fSColin Riley       Initiate();
2936ef20b08fSColin Riley     }
2937ef20b08fSColin Riley   }
2938ef20b08fSColin Riley }
2939ef20b08fSColin Riley 
294047d64161SLuke Drummond void RSModuleDescriptor::WarnIfVersionMismatch(lldb_private::Stream *s) const {
294147d64161SLuke Drummond   if (!s)
294247d64161SLuke Drummond     return;
294347d64161SLuke Drummond 
294447d64161SLuke Drummond   if (m_slang_version.empty() || m_bcc_version.empty()) {
294547d64161SLuke Drummond     s->PutCString("WARNING: Unknown bcc or slang (llvm-rs-cc) version; debug "
294647d64161SLuke Drummond                   "experience may be unreliable");
294747d64161SLuke Drummond     s->EOL();
294847d64161SLuke Drummond   } else if (m_slang_version != m_bcc_version) {
294947d64161SLuke Drummond     s->Printf("WARNING: The debug info emitted by the slang frontend "
295047d64161SLuke Drummond               "(llvm-rs-cc) used to build this module (%s) does not match the "
295147d64161SLuke Drummond               "version of bcc used to generate the debug information (%s). "
295247d64161SLuke Drummond               "This is an unsupported configuration and may result in a poor "
295347d64161SLuke Drummond               "debugging experience; proceed with caution",
295447d64161SLuke Drummond               m_slang_version.c_str(), m_bcc_version.c_str());
295547d64161SLuke Drummond     s->EOL();
295647d64161SLuke Drummond   }
295747d64161SLuke Drummond }
295847d64161SLuke Drummond 
29597f193d69SLuke Drummond bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
29607f193d69SLuke Drummond                                           size_t n_lines) {
29617f193d69SLuke Drummond   // Skip the pragma prototype line
29627f193d69SLuke Drummond   ++lines;
29637f193d69SLuke Drummond   for (; n_lines--; ++lines) {
29647f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
29657f193d69SLuke Drummond     m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
29667f193d69SLuke Drummond   }
29677f193d69SLuke Drummond   return true;
29687f193d69SLuke Drummond }
29697f193d69SLuke Drummond 
29707f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
29717f193d69SLuke Drummond                                                 size_t n_lines) {
29727f193d69SLuke Drummond   // The list of reduction kernels in the `.rs.info` symbol is of the form
29737f193d69SLuke Drummond   // "signature - accumulatordatasize - reduction_name - initializer_name -
297405097246SAdrian Prantl   // accumulator_name - combiner_name - outconverter_name - halter_name" Where
297505097246SAdrian Prantl   // a function is not explicitly named by the user, or is not generated by the
297605097246SAdrian Prantl   // compiler, it is named "." so the dash separated list should always be 8
297705097246SAdrian Prantl   // items long
29787f193d69SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
29797f193d69SLuke Drummond   // Skip the exportReduceCount line
29807f193d69SLuke Drummond   ++lines;
29817f193d69SLuke Drummond   for (; n_lines--; ++lines) {
29827f193d69SLuke Drummond     llvm::SmallVector<llvm::StringRef, 8> spec;
29837f193d69SLuke Drummond     lines->split(spec, " - ");
29847f193d69SLuke Drummond     if (spec.size() != 8) {
29857f193d69SLuke Drummond       if (spec.size() < 8) {
29867f193d69SLuke Drummond         if (log)
29877f193d69SLuke Drummond           log->Error("Error parsing RenderScript reduction spec. wrong number "
29887f193d69SLuke Drummond                      "of fields");
29897f193d69SLuke Drummond         return false;
29907f193d69SLuke Drummond       } else if (log)
29917f193d69SLuke Drummond         log->Warning("Extraneous members in reduction spec: '%s'",
29927f193d69SLuke Drummond                      lines->str().c_str());
29937f193d69SLuke Drummond     }
29947f193d69SLuke Drummond 
29957f193d69SLuke Drummond     const auto sig_s = spec[0];
29967f193d69SLuke Drummond     uint32_t sig;
29977f193d69SLuke Drummond     if (sig_s.getAsInteger(10, sig)) {
29987f193d69SLuke Drummond       if (log)
29997f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid kernel "
30007f193d69SLuke Drummond                    "signature: '%s'",
30017f193d69SLuke Drummond                    sig_s.str().c_str());
30027f193d69SLuke Drummond       return false;
30037f193d69SLuke Drummond     }
30047f193d69SLuke Drummond 
30057f193d69SLuke Drummond     const auto accum_data_size_s = spec[1];
30067f193d69SLuke Drummond     uint32_t accum_data_size;
30077f193d69SLuke Drummond     if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
30087f193d69SLuke Drummond       if (log)
30097f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid "
30107f193d69SLuke Drummond                    "accumulator data size %s",
30117f193d69SLuke Drummond                    accum_data_size_s.str().c_str());
30127f193d69SLuke Drummond       return false;
30137f193d69SLuke Drummond     }
30147f193d69SLuke Drummond 
30157f193d69SLuke Drummond     if (log)
30167f193d69SLuke Drummond       log->Printf("Found RenderScript reduction '%s'", spec[2].str().c_str());
30177f193d69SLuke Drummond 
30187f193d69SLuke Drummond     m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
30197f193d69SLuke Drummond                                                  spec[2], spec[3], spec[4],
30207f193d69SLuke Drummond                                                  spec[5], spec[6], spec[7]));
30217f193d69SLuke Drummond   }
30227f193d69SLuke Drummond   return true;
30237f193d69SLuke Drummond }
30247f193d69SLuke Drummond 
302547d64161SLuke Drummond bool RSModuleDescriptor::ParseVersionInfo(llvm::StringRef *lines,
302647d64161SLuke Drummond                                           size_t n_lines) {
302747d64161SLuke Drummond   // Skip the versionInfo line
302847d64161SLuke Drummond   ++lines;
302947d64161SLuke Drummond   for (; n_lines--; ++lines) {
303047d64161SLuke Drummond     // We're only interested in bcc and slang versions, and ignore all other
303147d64161SLuke Drummond     // versionInfo lines
303247d64161SLuke Drummond     const auto kv_pair = lines->split(" - ");
303347d64161SLuke Drummond     if (kv_pair.first == "slang")
303447d64161SLuke Drummond       m_slang_version = kv_pair.second.str();
303547d64161SLuke Drummond     else if (kv_pair.first == "bcc")
303647d64161SLuke Drummond       m_bcc_version = kv_pair.second.str();
303747d64161SLuke Drummond   }
303847d64161SLuke Drummond   return true;
303947d64161SLuke Drummond }
304047d64161SLuke Drummond 
30417f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
30427f193d69SLuke Drummond                                                  size_t n_lines) {
30437f193d69SLuke Drummond   // Skip the exportForeachCount line
30447f193d69SLuke Drummond   ++lines;
30457f193d69SLuke Drummond   for (; n_lines--; ++lines) {
30467f193d69SLuke Drummond     uint32_t slot;
30477f193d69SLuke Drummond     // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
30487f193d69SLuke Drummond     // pair per line
30497f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
30507f193d69SLuke Drummond     if (kv_pair.first.getAsInteger(10, slot))
30517f193d69SLuke Drummond       return false;
30527f193d69SLuke Drummond     m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
30537f193d69SLuke Drummond   }
30547f193d69SLuke Drummond   return true;
30557f193d69SLuke Drummond }
30567f193d69SLuke Drummond 
30577f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
30587f193d69SLuke Drummond                                              size_t n_lines) {
30597f193d69SLuke Drummond   // Skip the ExportVarCount line
30607f193d69SLuke Drummond   ++lines;
30617f193d69SLuke Drummond   for (; n_lines--; ++lines)
30627f193d69SLuke Drummond     m_globals.push_back(RSGlobalDescriptor(this, *lines));
30637f193d69SLuke Drummond   return true;
30647f193d69SLuke Drummond }
30655ec532a9SColin Riley 
3066b9c1b51eSKate Stone // The .rs.info symbol in renderscript modules contains a string which needs to
306705097246SAdrian Prantl // be parsed. The string is basic and is parsed on a line by line basis.
3068b9c1b51eSKate Stone bool RSModuleDescriptor::ParseRSInfo() {
3069b0be30f7SAidan Dodds   assert(m_module);
30707f193d69SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3071b9c1b51eSKate Stone   const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
3072b9c1b51eSKate Stone       ConstString(".rs.info"), eSymbolTypeData);
3073b0be30f7SAidan Dodds   if (!info_sym)
3074b0be30f7SAidan Dodds     return false;
3075b0be30f7SAidan Dodds 
3076358cf1eaSGreg Clayton   const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
3077b0be30f7SAidan Dodds   if (addr == LLDB_INVALID_ADDRESS)
3078b0be30f7SAidan Dodds     return false;
3079b0be30f7SAidan Dodds 
30805ec532a9SColin Riley   const addr_t size = info_sym->GetByteSize();
30815ec532a9SColin Riley   const FileSpec fs = m_module->GetFileSpec();
30825ec532a9SColin Riley 
3083*87e403aaSJonas Devlieghere   auto buffer =
3084*87e403aaSJonas Devlieghere       FileSystem::Instance().CreateDataBuffer(fs.GetPath(), size, addr);
30855ec532a9SColin Riley   if (!buffer)
30865ec532a9SColin Riley     return false;
30875ec532a9SColin Riley 
3088b0be30f7SAidan Dodds   // split rs.info. contents into lines
30897f193d69SLuke Drummond   llvm::SmallVector<llvm::StringRef, 128> info_lines;
30905ec532a9SColin Riley   {
30917f193d69SLuke Drummond     const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
30927f193d69SLuke Drummond     raw_rs_info.split(info_lines, '\n');
30937f193d69SLuke Drummond     if (log)
30947f193d69SLuke Drummond       log->Printf("'.rs.info symbol for '%s':\n%s",
30957f193d69SLuke Drummond                   m_module->GetFileSpec().GetCString(),
30967f193d69SLuke Drummond                   raw_rs_info.str().c_str());
3097b0be30f7SAidan Dodds   }
3098b0be30f7SAidan Dodds 
30997f193d69SLuke Drummond   enum {
31007f193d69SLuke Drummond     eExportVar,
31017f193d69SLuke Drummond     eExportForEach,
31027f193d69SLuke Drummond     eExportReduce,
31037f193d69SLuke Drummond     ePragma,
31047f193d69SLuke Drummond     eBuildChecksum,
310547d64161SLuke Drummond     eObjectSlot,
310647d64161SLuke Drummond     eVersionInfo,
31077f193d69SLuke Drummond   };
31087f193d69SLuke Drummond 
3109b3bbcb12SLuke Drummond   const auto rs_info_handler = [](llvm::StringRef name) -> int {
3110b3bbcb12SLuke Drummond     return llvm::StringSwitch<int>(name)
3111b3bbcb12SLuke Drummond         // The number of visible global variables in the script
3112b3bbcb12SLuke Drummond         .Case("exportVarCount", eExportVar)
31137f193d69SLuke Drummond         // The number of RenderScrip `forEach` kernels __attribute__((kernel))
3114b3bbcb12SLuke Drummond         .Case("exportForEachCount", eExportForEach)
3115b3bbcb12SLuke Drummond         // The number of generalreductions: This marked in the script by
3116b3bbcb12SLuke Drummond         // `#pragma reduce()`
3117b3bbcb12SLuke Drummond         .Case("exportReduceCount", eExportReduce)
3118b3bbcb12SLuke Drummond         // Total count of all RenderScript specific `#pragmas` used in the
3119b3bbcb12SLuke Drummond         // script
3120b3bbcb12SLuke Drummond         .Case("pragmaCount", ePragma)
3121b3bbcb12SLuke Drummond         .Case("objectSlotCount", eObjectSlot)
312247d64161SLuke Drummond         .Case("versionInfo", eVersionInfo)
3123b3bbcb12SLuke Drummond         .Default(-1);
3124b3bbcb12SLuke Drummond   };
3125b0be30f7SAidan Dodds 
3126b0be30f7SAidan Dodds   // parse all text lines of .rs.info
3127b9c1b51eSKate Stone   for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
31287f193d69SLuke Drummond     const auto kv_pair = line->split(": ");
31297f193d69SLuke Drummond     const auto key = kv_pair.first;
31307f193d69SLuke Drummond     const auto val = kv_pair.second.trim();
31315ec532a9SColin Riley 
3132b3bbcb12SLuke Drummond     const auto handler = rs_info_handler(key);
3133b3bbcb12SLuke Drummond     if (handler == -1)
31347f193d69SLuke Drummond       continue;
313505097246SAdrian Prantl     // getAsInteger returns `true` on an error condition - we're only
313605097246SAdrian Prantl     // interested in numeric fields at the moment
31377f193d69SLuke Drummond     uint64_t n_lines;
31387f193d69SLuke Drummond     if (val.getAsInteger(10, n_lines)) {
31396302bf6aSPavel Labath       LLDB_LOGV(log, "Failed to parse non-numeric '.rs.info' section {0}",
31406302bf6aSPavel Labath                 line->str());
31417f193d69SLuke Drummond       continue;
31427f193d69SLuke Drummond     }
31437f193d69SLuke Drummond     if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
31447f193d69SLuke Drummond       return false;
31457f193d69SLuke Drummond 
31467f193d69SLuke Drummond     bool success = false;
3147b3bbcb12SLuke Drummond     switch (handler) {
31487f193d69SLuke Drummond     case eExportVar:
31497f193d69SLuke Drummond       success = ParseExportVarCount(line, n_lines);
31507f193d69SLuke Drummond       break;
31517f193d69SLuke Drummond     case eExportForEach:
31527f193d69SLuke Drummond       success = ParseExportForeachCount(line, n_lines);
31537f193d69SLuke Drummond       break;
31547f193d69SLuke Drummond     case eExportReduce:
31557f193d69SLuke Drummond       success = ParseExportReduceCount(line, n_lines);
31567f193d69SLuke Drummond       break;
31577f193d69SLuke Drummond     case ePragma:
31587f193d69SLuke Drummond       success = ParsePragmaCount(line, n_lines);
31597f193d69SLuke Drummond       break;
316047d64161SLuke Drummond     case eVersionInfo:
316147d64161SLuke Drummond       success = ParseVersionInfo(line, n_lines);
316247d64161SLuke Drummond       break;
31637f193d69SLuke Drummond     default: {
31647f193d69SLuke Drummond       if (log)
31657f193d69SLuke Drummond         log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__,
31667f193d69SLuke Drummond                     line->str().c_str());
31677f193d69SLuke Drummond       continue;
31687f193d69SLuke Drummond     }
31697f193d69SLuke Drummond     }
31707f193d69SLuke Drummond     if (!success)
31717f193d69SLuke Drummond       return false;
31727f193d69SLuke Drummond     line += n_lines;
31737f193d69SLuke Drummond   }
31747f193d69SLuke Drummond   return info_lines.size() > 0;
31755ec532a9SColin Riley }
31765ec532a9SColin Riley 
317797206d57SZachary Turner void RenderScriptRuntime::DumpStatus(Stream &strm) const {
3178b9c1b51eSKate Stone   if (m_libRS) {
31794640cde1SColin Riley     strm.Printf("Runtime Library discovered.");
31804640cde1SColin Riley     strm.EOL();
31814640cde1SColin Riley   }
3182b9c1b51eSKate Stone   if (m_libRSDriver) {
31834640cde1SColin Riley     strm.Printf("Runtime Driver discovered.");
31844640cde1SColin Riley     strm.EOL();
31854640cde1SColin Riley   }
3186b9c1b51eSKate Stone   if (m_libRSCpuRef) {
31874640cde1SColin Riley     strm.Printf("CPU Reference Implementation discovered.");
31884640cde1SColin Riley     strm.EOL();
31894640cde1SColin Riley   }
31904640cde1SColin Riley 
3191b9c1b51eSKate Stone   if (m_runtimeHooks.size()) {
31924640cde1SColin Riley     strm.Printf("Runtime functions hooked:");
31934640cde1SColin Riley     strm.EOL();
3194b9c1b51eSKate Stone     for (auto b : m_runtimeHooks) {
31954640cde1SColin Riley       strm.Indent(b.second->defn->name);
31964640cde1SColin Riley       strm.EOL();
31974640cde1SColin Riley     }
3198b9c1b51eSKate Stone   } else {
31994640cde1SColin Riley     strm.Printf("Runtime is not hooked.");
32004640cde1SColin Riley     strm.EOL();
32014640cde1SColin Riley   }
32024640cde1SColin Riley }
32034640cde1SColin Riley 
3204b9c1b51eSKate Stone void RenderScriptRuntime::DumpContexts(Stream &strm) const {
32054640cde1SColin Riley   strm.Printf("Inferred RenderScript Contexts:");
32064640cde1SColin Riley   strm.EOL();
32074640cde1SColin Riley   strm.IndentMore();
32084640cde1SColin Riley 
32094640cde1SColin Riley   std::map<addr_t, uint64_t> contextReferences;
32104640cde1SColin Riley 
321105097246SAdrian Prantl   // Iterate over all of the currently discovered scripts. Note: We cant push
321205097246SAdrian Prantl   // or pop from m_scripts inside this loop or it may invalidate script.
3213b9c1b51eSKate Stone   for (const auto &script : m_scripts) {
321478f339d1SEwan Crawford     if (!script->context.isValid())
321578f339d1SEwan Crawford       continue;
321678f339d1SEwan Crawford     lldb::addr_t context = *script->context;
321778f339d1SEwan Crawford 
3218b9c1b51eSKate Stone     if (contextReferences.find(context) != contextReferences.end()) {
321978f339d1SEwan Crawford       contextReferences[context]++;
3220b9c1b51eSKate Stone     } else {
322178f339d1SEwan Crawford       contextReferences[context] = 1;
32224640cde1SColin Riley     }
32234640cde1SColin Riley   }
32244640cde1SColin Riley 
3225b9c1b51eSKate Stone   for (const auto &cRef : contextReferences) {
3226b9c1b51eSKate Stone     strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
3227b9c1b51eSKate Stone                 cRef.first, cRef.second);
32284640cde1SColin Riley     strm.EOL();
32294640cde1SColin Riley   }
32304640cde1SColin Riley   strm.IndentLess();
32314640cde1SColin Riley }
32324640cde1SColin Riley 
3233b9c1b51eSKate Stone void RenderScriptRuntime::DumpKernels(Stream &strm) const {
32344640cde1SColin Riley   strm.Printf("RenderScript Kernels:");
32354640cde1SColin Riley   strm.EOL();
32364640cde1SColin Riley   strm.IndentMore();
3237b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
32384640cde1SColin Riley     strm.Printf("Resource '%s':", module->m_resname.c_str());
32394640cde1SColin Riley     strm.EOL();
3240b9c1b51eSKate Stone     for (const auto &kernel : module->m_kernels) {
32414640cde1SColin Riley       strm.Indent(kernel.m_name.AsCString());
32424640cde1SColin Riley       strm.EOL();
32434640cde1SColin Riley     }
32444640cde1SColin Riley   }
32454640cde1SColin Riley   strm.IndentLess();
32464640cde1SColin Riley }
32474640cde1SColin Riley 
3248a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails *
3249b9c1b51eSKate Stone RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
3250a0f08674SEwan Crawford   AllocationDetails *alloc = nullptr;
3251a0f08674SEwan Crawford 
3252a0f08674SEwan Crawford   // See if we can find allocation using id as an index;
3253b9c1b51eSKate Stone   if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
3254b9c1b51eSKate Stone       m_allocations[alloc_id - 1]->id == alloc_id) {
3255a0f08674SEwan Crawford     alloc = m_allocations[alloc_id - 1].get();
3256a0f08674SEwan Crawford     return alloc;
3257a0f08674SEwan Crawford   }
3258a0f08674SEwan Crawford 
3259a0f08674SEwan Crawford   // Fallback to searching
3260b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
3261b9c1b51eSKate Stone     if (a->id == alloc_id) {
3262a0f08674SEwan Crawford       alloc = a.get();
3263a0f08674SEwan Crawford       break;
3264a0f08674SEwan Crawford     }
3265a0f08674SEwan Crawford   }
3266a0f08674SEwan Crawford 
3267b9c1b51eSKate Stone   if (alloc == nullptr) {
3268b9c1b51eSKate Stone     strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
3269b9c1b51eSKate Stone                 alloc_id);
3270a0f08674SEwan Crawford     strm.EOL();
3271a0f08674SEwan Crawford   }
3272a0f08674SEwan Crawford 
3273a0f08674SEwan Crawford   return alloc;
3274a0f08674SEwan Crawford }
3275a0f08674SEwan Crawford 
3276b9c1b51eSKate Stone // Prints the contents of an allocation to the output stream, which may be a
3277b9c1b51eSKate Stone // file
3278b9c1b51eSKate Stone bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
3279b9c1b51eSKate Stone                                          const uint32_t id) {
3280a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3281a0f08674SEwan Crawford 
3282a0f08674SEwan Crawford   // Check we can find the desired allocation
3283a0f08674SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, id);
3284a0f08674SEwan Crawford   if (!alloc)
3285a0f08674SEwan Crawford     return false; // FindAllocByID() will print error message for us here
3286a0f08674SEwan Crawford 
3287a0f08674SEwan Crawford   if (log)
3288b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
3289b9c1b51eSKate Stone                 *alloc->address.get());
3290a0f08674SEwan Crawford 
3291a0f08674SEwan Crawford   // Check we have information about the allocation, if not calculate it
329280af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
3293a0f08674SEwan Crawford     if (log)
3294b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
3295b9c1b51eSKate Stone                   __FUNCTION__);
3296a0f08674SEwan Crawford 
3297a0f08674SEwan Crawford     // JIT all the allocation information
3298b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
3299a0f08674SEwan Crawford       strm.Printf("Error: Couldn't JIT allocation details");
3300a0f08674SEwan Crawford       strm.EOL();
3301a0f08674SEwan Crawford       return false;
3302a0f08674SEwan Crawford     }
3303a0f08674SEwan Crawford   }
3304a0f08674SEwan Crawford 
3305a0f08674SEwan Crawford   // Establish format and size of each data element
3306b3f7f69dSAidan Dodds   const uint32_t vec_size = *alloc->element.type_vec_size.get();
33078b244e21SEwan Crawford   const Element::DataType type = *alloc->element.type.get();
3308a0f08674SEwan Crawford 
3309b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
3310b9c1b51eSKate Stone          "Invalid allocation type");
3311a0f08674SEwan Crawford 
33122e920715SEwan Crawford   lldb::Format format;
33132e920715SEwan Crawford   if (type >= Element::RS_TYPE_ELEMENT)
33142e920715SEwan Crawford     format = eFormatHex;
33152e920715SEwan Crawford   else
3316b9c1b51eSKate Stone     format = vec_size == 1
3317b9c1b51eSKate Stone                  ? static_cast<lldb::Format>(
3318b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatSingle])
3319b9c1b51eSKate Stone                  : static_cast<lldb::Format>(
3320b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatVector]);
3321a0f08674SEwan Crawford 
3322b3f7f69dSAidan Dodds   const uint32_t data_size = *alloc->element.datum_size.get();
3323a0f08674SEwan Crawford 
3324a0f08674SEwan Crawford   if (log)
3325b9c1b51eSKate Stone     log->Printf("%s - element size %" PRIu32 " bytes, including padding",
3326b9c1b51eSKate Stone                 __FUNCTION__, data_size);
3327a0f08674SEwan Crawford 
332855232f09SEwan Crawford   // Allocate a buffer to copy data into
332955232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3330b9c1b51eSKate Stone   if (!buffer) {
33312e920715SEwan Crawford     strm.Printf("Error: Couldn't read allocation data");
333255232f09SEwan Crawford     strm.EOL();
333355232f09SEwan Crawford     return false;
333455232f09SEwan Crawford   }
333555232f09SEwan Crawford 
3336a0f08674SEwan Crawford   // Calculate stride between rows as there may be padding at end of rows since
3337a0f08674SEwan Crawford   // allocated memory is 16-byte aligned
3338b9c1b51eSKate Stone   if (!alloc->stride.isValid()) {
3339a0f08674SEwan Crawford     if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
3340a0f08674SEwan Crawford       alloc->stride = 0;
3341b9c1b51eSKate Stone     else if (!JITAllocationStride(alloc, frame_ptr)) {
3342a0f08674SEwan Crawford       strm.Printf("Error: Couldn't calculate allocation row stride");
3343a0f08674SEwan Crawford       strm.EOL();
3344a0f08674SEwan Crawford       return false;
3345a0f08674SEwan Crawford     }
3346a0f08674SEwan Crawford   }
3347b3f7f69dSAidan Dodds   const uint32_t stride = *alloc->stride.get();
3348b3f7f69dSAidan Dodds   const uint32_t size = *alloc->size.get(); // Size of whole allocation
3349b9c1b51eSKate Stone   const uint32_t padding =
3350b9c1b51eSKate Stone       alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3351a0f08674SEwan Crawford   if (log)
3352b9c1b51eSKate Stone     log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32
3353b9c1b51eSKate Stone                 " bytes, padding %" PRIu32,
3354b3f7f69dSAidan Dodds                 __FUNCTION__, stride, size, padding);
3355a0f08674SEwan Crawford 
3356a0f08674SEwan Crawford   // Find dimensions used to index loops, so need to be non-zero
3357b3f7f69dSAidan Dodds   uint32_t dim_x = alloc->dimension.get()->dim_1;
3358a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 1 : dim_x;
3359a0f08674SEwan Crawford 
3360b3f7f69dSAidan Dodds   uint32_t dim_y = alloc->dimension.get()->dim_2;
3361a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 1 : dim_y;
3362a0f08674SEwan Crawford 
3363b3f7f69dSAidan Dodds   uint32_t dim_z = alloc->dimension.get()->dim_3;
3364a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 1 : dim_z;
3365a0f08674SEwan Crawford 
336655232f09SEwan Crawford   // Use data extractor to format output
336780af0b9eSLuke Drummond   const uint32_t target_ptr_size =
3368b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3369b9c1b51eSKate Stone   DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
337080af0b9eSLuke Drummond                            target_ptr_size);
337155232f09SEwan Crawford 
3372b3f7f69dSAidan Dodds   uint32_t offset = 0;   // Offset in buffer to next element to be printed
3373b3f7f69dSAidan Dodds   uint32_t prev_row = 0; // Offset to the start of the previous row
3374a0f08674SEwan Crawford 
3375a0f08674SEwan Crawford   // Iterate over allocation dimensions, printing results to user
3376a0f08674SEwan Crawford   strm.Printf("Data (X, Y, Z):");
3377b9c1b51eSKate Stone   for (uint32_t z = 0; z < dim_z; ++z) {
3378b9c1b51eSKate Stone     for (uint32_t y = 0; y < dim_y; ++y) {
3379a0f08674SEwan Crawford       // Use stride to index start of next row.
3380a0f08674SEwan Crawford       if (!(y == 0 && z == 0))
3381a0f08674SEwan Crawford         offset = prev_row + stride;
3382a0f08674SEwan Crawford       prev_row = offset;
3383a0f08674SEwan Crawford 
3384a0f08674SEwan Crawford       // Print each element in the row individually
3385b9c1b51eSKate Stone       for (uint32_t x = 0; x < dim_x; ++x) {
3386b3f7f69dSAidan Dodds         strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3387b9c1b51eSKate Stone         if ((type == Element::RS_TYPE_NONE) &&
3388b9c1b51eSKate Stone             (alloc->element.children.size() > 0) &&
3389b9c1b51eSKate Stone             (alloc->element.type_name != Element::GetFallbackStructName())) {
339005097246SAdrian Prantl           // Here we are dumping an Element of struct type. This is done using
339105097246SAdrian Prantl           // expression evaluation with the name of the struct type and pointer
339205097246SAdrian Prantl           // to element. Don't print the name of the resulting expression,
339305097246SAdrian Prantl           // since this will be '$[0-9]+'
33948b244e21SEwan Crawford           DumpValueObjectOptions expr_options;
33958b244e21SEwan Crawford           expr_options.SetHideName(true);
33968b244e21SEwan Crawford 
33974ebdee0aSBruce Mitchener           // Setup expression as dereferencing a pointer cast to element
339805097246SAdrian Prantl           // address.
3399ea0636b5SEwan Crawford           char expr_char_buffer[jit_max_expr_size];
340080af0b9eSLuke Drummond           int written =
3401b9c1b51eSKate Stone               snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3402b9c1b51eSKate Stone                        alloc->element.type_name.AsCString(),
3403b9c1b51eSKate Stone                        *alloc->data_ptr.get() + offset);
34048b244e21SEwan Crawford 
340580af0b9eSLuke Drummond           if (written < 0 || written >= jit_max_expr_size) {
34068b244e21SEwan Crawford             if (log)
3407b3f7f69dSAidan Dodds               log->Printf("%s - error in snprintf().", __FUNCTION__);
34088b244e21SEwan Crawford             continue;
34098b244e21SEwan Crawford           }
34108b244e21SEwan Crawford 
34118b244e21SEwan Crawford           // Evaluate expression
34128b244e21SEwan Crawford           ValueObjectSP expr_result;
3413b9c1b51eSKate Stone           GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3414b9c1b51eSKate Stone                                                        frame_ptr, expr_result);
34158b244e21SEwan Crawford 
34168b244e21SEwan Crawford           // Print the results to our stream.
34178b244e21SEwan Crawford           expr_result->Dump(strm, expr_options);
3418b9c1b51eSKate Stone         } else {
341929cb868aSZachary Turner           DumpDataExtractor(alloc_data, &strm, offset, format,
342029cb868aSZachary Turner                             data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0,
342129cb868aSZachary Turner                             0);
34228b244e21SEwan Crawford         }
34238b244e21SEwan Crawford         offset += data_size;
3424a0f08674SEwan Crawford       }
3425a0f08674SEwan Crawford     }
3426a0f08674SEwan Crawford   }
3427a0f08674SEwan Crawford   strm.EOL();
3428a0f08674SEwan Crawford 
3429a0f08674SEwan Crawford   return true;
3430a0f08674SEwan Crawford }
3431a0f08674SEwan Crawford 
343205097246SAdrian Prantl // Function recalculates all our cached information about allocations by
343305097246SAdrian Prantl // jitting the RS runtime regarding each allocation we know about. Returns true
343405097246SAdrian Prantl // if all allocations could be recomputed, false otherwise.
3435b9c1b51eSKate Stone bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3436b9c1b51eSKate Stone                                                   StackFrame *frame_ptr) {
34370d2bfcfbSEwan Crawford   bool success = true;
3438b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
34390d2bfcfbSEwan Crawford     // JIT current allocation information
3440b9c1b51eSKate Stone     if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3441b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3442b9c1b51eSKate Stone                   "\n",
3443b9c1b51eSKate Stone                   alloc->id);
34440d2bfcfbSEwan Crawford       success = false;
34450d2bfcfbSEwan Crawford     }
34460d2bfcfbSEwan Crawford   }
34470d2bfcfbSEwan Crawford 
34480d2bfcfbSEwan Crawford   if (success)
34490d2bfcfbSEwan Crawford     strm.Printf("All allocations successfully recomputed");
34500d2bfcfbSEwan Crawford   strm.EOL();
34510d2bfcfbSEwan Crawford 
34520d2bfcfbSEwan Crawford   return success;
34530d2bfcfbSEwan Crawford }
34540d2bfcfbSEwan Crawford 
345580af0b9eSLuke Drummond // Prints information regarding currently loaded allocations. These details are
345680af0b9eSLuke Drummond // gathered by jitting the runtime, which has as latency. Index parameter
345780af0b9eSLuke Drummond // specifies a single allocation ID to print, or a zero value to print them all
3458b9c1b51eSKate Stone void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3459b9c1b51eSKate Stone                                           const uint32_t index) {
346015f2bd95SEwan Crawford   strm.Printf("RenderScript Allocations:");
346115f2bd95SEwan Crawford   strm.EOL();
346215f2bd95SEwan Crawford   strm.IndentMore();
346315f2bd95SEwan Crawford 
3464b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
3465b649b005SEwan Crawford     // index will only be zero if we want to print all allocations
3466b649b005SEwan Crawford     if (index != 0 && index != alloc->id)
3467b649b005SEwan Crawford       continue;
346815f2bd95SEwan Crawford 
346915f2bd95SEwan Crawford     // JIT current allocation information
347080af0b9eSLuke Drummond     if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3471b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3472b9c1b51eSKate Stone                   alloc->id);
3473b3f7f69dSAidan Dodds       strm.EOL();
347415f2bd95SEwan Crawford       continue;
347515f2bd95SEwan Crawford     }
347615f2bd95SEwan Crawford 
3477b3f7f69dSAidan Dodds     strm.Printf("%" PRIu32 ":", alloc->id);
3478b3f7f69dSAidan Dodds     strm.EOL();
347915f2bd95SEwan Crawford     strm.IndentMore();
348015f2bd95SEwan Crawford 
348115f2bd95SEwan Crawford     strm.Indent("Context: ");
348215f2bd95SEwan Crawford     if (!alloc->context.isValid())
348315f2bd95SEwan Crawford       strm.Printf("unknown\n");
348415f2bd95SEwan Crawford     else
348515f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
348615f2bd95SEwan Crawford 
348715f2bd95SEwan Crawford     strm.Indent("Address: ");
348815f2bd95SEwan Crawford     if (!alloc->address.isValid())
348915f2bd95SEwan Crawford       strm.Printf("unknown\n");
349015f2bd95SEwan Crawford     else
349115f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
349215f2bd95SEwan Crawford 
349315f2bd95SEwan Crawford     strm.Indent("Data pointer: ");
349415f2bd95SEwan Crawford     if (!alloc->data_ptr.isValid())
349515f2bd95SEwan Crawford       strm.Printf("unknown\n");
349615f2bd95SEwan Crawford     else
349715f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
349815f2bd95SEwan Crawford 
349915f2bd95SEwan Crawford     strm.Indent("Dimensions: ");
350015f2bd95SEwan Crawford     if (!alloc->dimension.isValid())
350115f2bd95SEwan Crawford       strm.Printf("unknown\n");
350215f2bd95SEwan Crawford     else
3503b3f7f69dSAidan Dodds       strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3504b9c1b51eSKate Stone                   alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3505b9c1b51eSKate Stone                   alloc->dimension.get()->dim_3);
350615f2bd95SEwan Crawford 
350715f2bd95SEwan Crawford     strm.Indent("Data Type: ");
3508b9c1b51eSKate Stone     if (!alloc->element.type.isValid() ||
3509b9c1b51eSKate Stone         !alloc->element.type_vec_size.isValid())
351015f2bd95SEwan Crawford       strm.Printf("unknown\n");
3511b9c1b51eSKate Stone     else {
35128b244e21SEwan Crawford       const int vector_size = *alloc->element.type_vec_size.get();
35132e920715SEwan Crawford       Element::DataType type = *alloc->element.type.get();
351415f2bd95SEwan Crawford 
35158b244e21SEwan Crawford       if (!alloc->element.type_name.IsEmpty())
35168b244e21SEwan Crawford         strm.Printf("%s\n", alloc->element.type_name.AsCString());
3517b9c1b51eSKate Stone       else {
3518b9c1b51eSKate Stone         // Enum value isn't monotonous, so doesn't always index
3519b9c1b51eSKate Stone         // RsDataTypeToString array
35202e920715SEwan Crawford         if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3521b9c1b51eSKate Stone           type =
3522b9c1b51eSKate Stone               static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3523b3f7f69dSAidan Dodds                                              Element::RS_TYPE_MATRIX_2X2 + 1);
35242e920715SEwan Crawford 
3525b3f7f69dSAidan Dodds         if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3526b3f7f69dSAidan Dodds                      sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3527b3f7f69dSAidan Dodds             vector_size > 4 || vector_size < 1)
352815f2bd95SEwan Crawford           strm.Printf("invalid type\n");
352915f2bd95SEwan Crawford         else
3530b9c1b51eSKate Stone           strm.Printf(
3531b9c1b51eSKate Stone               "%s\n",
3532b9c1b51eSKate Stone               AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3533b3f7f69dSAidan Dodds                                                    [vector_size - 1]);
353415f2bd95SEwan Crawford       }
35352e920715SEwan Crawford     }
353615f2bd95SEwan Crawford 
353715f2bd95SEwan Crawford     strm.Indent("Data Kind: ");
35388b244e21SEwan Crawford     if (!alloc->element.type_kind.isValid())
353915f2bd95SEwan Crawford       strm.Printf("unknown\n");
3540b9c1b51eSKate Stone     else {
35418b244e21SEwan Crawford       const Element::DataKind kind = *alloc->element.type_kind.get();
35428b244e21SEwan Crawford       if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
354315f2bd95SEwan Crawford         strm.Printf("invalid kind\n");
354415f2bd95SEwan Crawford       else
3545b9c1b51eSKate Stone         strm.Printf(
3546b9c1b51eSKate Stone             "%s\n",
3547b9c1b51eSKate Stone             AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
354815f2bd95SEwan Crawford     }
354915f2bd95SEwan Crawford 
355015f2bd95SEwan Crawford     strm.EOL();
355115f2bd95SEwan Crawford     strm.IndentLess();
355215f2bd95SEwan Crawford   }
355315f2bd95SEwan Crawford   strm.IndentLess();
355415f2bd95SEwan Crawford }
355515f2bd95SEwan Crawford 
35567dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
3557b9c1b51eSKate Stone void RenderScriptRuntime::BreakOnModuleKernels(
3558b9c1b51eSKate Stone     const RSModuleDescriptorSP rsmodule_sp) {
3559b9c1b51eSKate Stone   for (const auto &kernel : rsmodule_sp->m_kernels) {
35607dc7771cSEwan Crawford     // Don't set breakpoint on 'root' kernel
35617dc7771cSEwan Crawford     if (strcmp(kernel.m_name.AsCString(), "root") == 0)
35627dc7771cSEwan Crawford       continue;
35637dc7771cSEwan Crawford 
35647dc7771cSEwan Crawford     CreateKernelBreakpoint(kernel.m_name);
35657dc7771cSEwan Crawford   }
35667dc7771cSEwan Crawford }
35677dc7771cSEwan Crawford 
356880af0b9eSLuke Drummond // Method is internally called by the 'kernel breakpoint all' command to enable
356980af0b9eSLuke Drummond // or disable breaking on all kernels. When do_break is true we want to enable
357080af0b9eSLuke Drummond // this functionality. When do_break is false we want to disable it.
3571b9c1b51eSKate Stone void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3572b9c1b51eSKate Stone   Log *log(
3573b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
35747dc7771cSEwan Crawford 
35757dc7771cSEwan Crawford   InitSearchFilter(target);
35767dc7771cSEwan Crawford 
35777dc7771cSEwan Crawford   // Set breakpoints on all the kernels
3578b9c1b51eSKate Stone   if (do_break && !m_breakAllKernels) {
35797dc7771cSEwan Crawford     m_breakAllKernels = true;
35807dc7771cSEwan Crawford 
35817dc7771cSEwan Crawford     for (const auto &module : m_rsmodules)
35827dc7771cSEwan Crawford       BreakOnModuleKernels(module);
35837dc7771cSEwan Crawford 
35847dc7771cSEwan Crawford     if (log)
3585b9c1b51eSKate Stone       log->Printf("%s(True) - breakpoints set on all currently loaded kernels.",
3586b9c1b51eSKate Stone                   __FUNCTION__);
3587b9c1b51eSKate Stone   } else if (!do_break &&
3588b9c1b51eSKate Stone              m_breakAllKernels) // Breakpoints won't be set on any new kernels.
35897dc7771cSEwan Crawford   {
35907dc7771cSEwan Crawford     m_breakAllKernels = false;
35917dc7771cSEwan Crawford 
35927dc7771cSEwan Crawford     if (log)
3593b9c1b51eSKate Stone       log->Printf("%s(False) - breakpoints no longer automatically set.",
3594b9c1b51eSKate Stone                   __FUNCTION__);
35957dc7771cSEwan Crawford   }
35967dc7771cSEwan Crawford }
35977dc7771cSEwan Crawford 
359805097246SAdrian Prantl // Given the name of a kernel this function creates a breakpoint using our own
359905097246SAdrian Prantl // breakpoint resolver, and returns the Breakpoint shared pointer.
36007dc7771cSEwan Crawford BreakpointSP
3601b9c1b51eSKate Stone RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) {
3602b9c1b51eSKate Stone   Log *log(
3603b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
36047dc7771cSEwan Crawford 
3605b9c1b51eSKate Stone   if (!m_filtersp) {
36067dc7771cSEwan Crawford     if (log)
3607b3f7f69dSAidan Dodds       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
36087dc7771cSEwan Crawford     return nullptr;
36097dc7771cSEwan Crawford   }
36107dc7771cSEwan Crawford 
36117dc7771cSEwan Crawford   BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3612b842f2ecSJim Ingham   Target &target = GetProcess()->GetTarget();
3613b842f2ecSJim Ingham   BreakpointSP bp = target.CreateBreakpoint(
3614b9c1b51eSKate Stone       m_filtersp, resolver_sp, false, false, false);
36157dc7771cSEwan Crawford 
3616b9c1b51eSKate Stone   // Give RS breakpoints a specific name, so the user can manipulate them as a
3617b9c1b51eSKate Stone   // group.
361897206d57SZachary Turner   Status err;
3619b842f2ecSJim Ingham   target.AddNameToBreakpoint(bp, "RenderScriptKernel", err);
3620b842f2ecSJim Ingham   if (err.Fail() && log)
3621b3bbcb12SLuke Drummond     if (log)
3622b3bbcb12SLuke Drummond       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3623b3bbcb12SLuke Drummond                   err.AsCString());
3624b3bbcb12SLuke Drummond 
3625b3bbcb12SLuke Drummond   return bp;
3626b3bbcb12SLuke Drummond }
3627b3bbcb12SLuke Drummond 
3628b3bbcb12SLuke Drummond BreakpointSP
3629b3bbcb12SLuke Drummond RenderScriptRuntime::CreateReductionBreakpoint(const ConstString &name,
3630b3bbcb12SLuke Drummond                                                int kernel_types) {
3631b3bbcb12SLuke Drummond   Log *log(
3632b3bbcb12SLuke Drummond       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3633b3bbcb12SLuke Drummond 
3634b3bbcb12SLuke Drummond   if (!m_filtersp) {
3635b3bbcb12SLuke Drummond     if (log)
3636b3bbcb12SLuke Drummond       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3637b3bbcb12SLuke Drummond     return nullptr;
3638b3bbcb12SLuke Drummond   }
3639b3bbcb12SLuke Drummond 
3640b3bbcb12SLuke Drummond   BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3641b3bbcb12SLuke Drummond       nullptr, name, &m_rsmodules, kernel_types));
3642b842f2ecSJim Ingham   Target &target = GetProcess()->GetTarget();
3643b842f2ecSJim Ingham   BreakpointSP bp = target.CreateBreakpoint(
3644b3bbcb12SLuke Drummond       m_filtersp, resolver_sp, false, false, false);
3645b3bbcb12SLuke Drummond 
3646b3bbcb12SLuke Drummond   // Give RS breakpoints a specific name, so the user can manipulate them as a
3647b3bbcb12SLuke Drummond   // group.
364897206d57SZachary Turner   Status err;
3649b842f2ecSJim Ingham   target.AddNameToBreakpoint(bp, "RenderScriptReduction", err);
3650b842f2ecSJim Ingham   if (err.Fail() && log)
3651b9c1b51eSKate Stone       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3652b9c1b51eSKate Stone                   err.AsCString());
365354782db7SEwan Crawford 
36547dc7771cSEwan Crawford   return bp;
36557dc7771cSEwan Crawford }
36567dc7771cSEwan Crawford 
3657b9c1b51eSKate Stone // Given an expression for a variable this function tries to calculate the
365880af0b9eSLuke Drummond // variable's value. If this is possible it returns true and sets the uint64_t
365980af0b9eSLuke Drummond // parameter to the variables unsigned value. Otherwise function returns false.
3660b9c1b51eSKate Stone bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3661b9c1b51eSKate Stone                                                 const char *var_name,
3662b9c1b51eSKate Stone                                                 uint64_t &val) {
3663018f5a7eSEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
366497206d57SZachary Turner   Status err;
3665018f5a7eSEwan Crawford   VariableSP var_sp;
3666018f5a7eSEwan Crawford 
3667018f5a7eSEwan Crawford   // Find variable in stack frame
3668b3f7f69dSAidan Dodds   ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3669b3f7f69dSAidan Dodds       var_name, eNoDynamicValues,
3670b9c1b51eSKate Stone       StackFrame::eExpressionPathOptionCheckPtrVsMember |
3671b9c1b51eSKate Stone           StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
367280af0b9eSLuke Drummond       var_sp, err));
367380af0b9eSLuke Drummond   if (!err.Success()) {
3674018f5a7eSEwan Crawford     if (log)
3675b9c1b51eSKate Stone       log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__,
3676b9c1b51eSKate Stone                   var_name);
3677018f5a7eSEwan Crawford     return false;
3678018f5a7eSEwan Crawford   }
3679018f5a7eSEwan Crawford 
3680b3f7f69dSAidan Dodds   // Find the uint32_t value for the variable
3681018f5a7eSEwan Crawford   bool success = false;
3682018f5a7eSEwan Crawford   val = value_sp->GetValueAsUnsigned(0, &success);
3683b9c1b51eSKate Stone   if (!success) {
3684018f5a7eSEwan Crawford     if (log)
3685b9c1b51eSKate Stone       log->Printf("%s - error, couldn't parse '%s' as an uint32_t.",
3686b9c1b51eSKate Stone                   __FUNCTION__, var_name);
3687018f5a7eSEwan Crawford     return false;
3688018f5a7eSEwan Crawford   }
3689018f5a7eSEwan Crawford 
3690018f5a7eSEwan Crawford   return true;
3691018f5a7eSEwan Crawford }
3692018f5a7eSEwan Crawford 
3693b9c1b51eSKate Stone // Function attempts to find the current coordinate of a kernel invocation by
369480af0b9eSLuke Drummond // investigating the values of frame variables in the .expand function. These
369580af0b9eSLuke Drummond // coordinates are returned via the coord array reference parameter. Returns
369680af0b9eSLuke Drummond // true if the coordinates could be found, and false otherwise.
3697b9c1b51eSKate Stone bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3698b9c1b51eSKate Stone                                               Thread *thread_ptr) {
369900f56eebSLuke Drummond   static const char *const x_expr = "rsIndex";
370000f56eebSLuke Drummond   static const char *const y_expr = "p->current.y";
370100f56eebSLuke Drummond   static const char *const z_expr = "p->current.z";
37021e05c3bcSGreg Clayton 
37034f8817c2SEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
37044f8817c2SEwan Crawford 
3705b9c1b51eSKate Stone   if (!thread_ptr) {
37064f8817c2SEwan Crawford     if (log)
37074f8817c2SEwan Crawford       log->Printf("%s - Error, No thread pointer", __FUNCTION__);
37084f8817c2SEwan Crawford 
37094f8817c2SEwan Crawford     return false;
37104f8817c2SEwan Crawford   }
37114f8817c2SEwan Crawford 
3712b9c1b51eSKate Stone   // Walk the call stack looking for a function whose name has the suffix
371380af0b9eSLuke Drummond   // '.expand' and contains the variables we're looking for.
3714b9c1b51eSKate Stone   for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
37154f8817c2SEwan Crawford     if (!thread_ptr->SetSelectedFrameByIndex(i))
37164f8817c2SEwan Crawford       continue;
37174f8817c2SEwan Crawford 
37184f8817c2SEwan Crawford     StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
37194f8817c2SEwan Crawford     if (!frame_sp)
37204f8817c2SEwan Crawford       continue;
37214f8817c2SEwan Crawford 
37224f8817c2SEwan Crawford     // Find the function name
3723991e4453SZachary Turner     const SymbolContext sym_ctx =
3724991e4453SZachary Turner         frame_sp->GetSymbolContext(eSymbolContextFunction);
372500f56eebSLuke Drummond     const ConstString func_name = sym_ctx.GetFunctionName();
372600f56eebSLuke Drummond     if (!func_name)
37274f8817c2SEwan Crawford       continue;
37284f8817c2SEwan Crawford 
37294f8817c2SEwan Crawford     if (log)
3730b9c1b51eSKate Stone       log->Printf("%s - Inspecting function '%s'", __FUNCTION__,
373100f56eebSLuke Drummond                   func_name.GetCString());
37324f8817c2SEwan Crawford 
37334f8817c2SEwan Crawford     // Check if function name has .expand suffix
373400f56eebSLuke Drummond     if (!func_name.GetStringRef().endswith(".expand"))
37354f8817c2SEwan Crawford       continue;
37364f8817c2SEwan Crawford 
37374f8817c2SEwan Crawford     if (log)
3738b9c1b51eSKate Stone       log->Printf("%s - Found .expand function '%s'", __FUNCTION__,
373900f56eebSLuke Drummond                   func_name.GetCString());
37404f8817c2SEwan Crawford 
374105097246SAdrian Prantl     // Get values for variables in .expand frame that tell us the current
374205097246SAdrian Prantl     // kernel invocation
374300f56eebSLuke Drummond     uint64_t x, y, z;
374400f56eebSLuke Drummond     bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
374500f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
374600f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, z_expr, z);
37474f8817c2SEwan Crawford 
374800f56eebSLuke Drummond     if (found) {
374900f56eebSLuke Drummond       // The RenderScript runtime uses uint32_t for these vars. If they're not
375000f56eebSLuke Drummond       // within bounds, our frame parsing is garbage
375100f56eebSLuke Drummond       assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
375200f56eebSLuke Drummond       coord.x = (uint32_t)x;
375300f56eebSLuke Drummond       coord.y = (uint32_t)y;
375400f56eebSLuke Drummond       coord.z = (uint32_t)z;
37554f8817c2SEwan Crawford       return true;
37564f8817c2SEwan Crawford     }
375700f56eebSLuke Drummond   }
37584f8817c2SEwan Crawford   return false;
37594f8817c2SEwan Crawford }
37604f8817c2SEwan Crawford 
3761b9c1b51eSKate Stone // Callback when a kernel breakpoint hits and we're looking for a specific
376280af0b9eSLuke Drummond // coordinate. Baton parameter contains a pointer to the target coordinate we
376305097246SAdrian Prantl // want to break on. Function then checks the .expand frame for the current
376405097246SAdrian Prantl // coordinate and breaks to user if it matches. Parameter 'break_id' is the id
376505097246SAdrian Prantl // of the Breakpoint which made the callback. Parameter 'break_loc_id' is the
376605097246SAdrian Prantl // id for the BreakpointLocation which was hit, a single logical breakpoint can
376705097246SAdrian Prantl // have multiple addresses.
3768b9c1b51eSKate Stone bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3769b9c1b51eSKate Stone                                               StoppointCallbackContext *ctx,
3770b9c1b51eSKate Stone                                               user_id_t break_id,
3771b9c1b51eSKate Stone                                               user_id_t break_loc_id) {
3772b9c1b51eSKate Stone   Log *log(
3773b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3774018f5a7eSEwan Crawford 
3775b9c1b51eSKate Stone   assert(baton &&
3776b9c1b51eSKate Stone          "Error: null baton in conditional kernel breakpoint callback");
3777018f5a7eSEwan Crawford 
3778018f5a7eSEwan Crawford   // Coordinate we want to stop on
377900f56eebSLuke Drummond   RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3780018f5a7eSEwan Crawford 
3781018f5a7eSEwan Crawford   if (log)
378200f56eebSLuke Drummond     log->Printf("%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__, break_id,
378300f56eebSLuke Drummond                 target_coord.x, target_coord.y, target_coord.z);
3784018f5a7eSEwan Crawford 
37854f8817c2SEwan Crawford   // Select current thread
3786018f5a7eSEwan Crawford   ExecutionContext context(ctx->exe_ctx_ref);
37874f8817c2SEwan Crawford   Thread *thread_ptr = context.GetThreadPtr();
37884f8817c2SEwan Crawford   assert(thread_ptr && "Null thread pointer");
37894f8817c2SEwan Crawford 
37904f8817c2SEwan Crawford   // Find current kernel invocation from .expand frame variables
379100f56eebSLuke Drummond   RSCoordinate current_coord{};
3792b9c1b51eSKate Stone   if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3793018f5a7eSEwan Crawford     if (log)
3794b9c1b51eSKate Stone       log->Printf("%s - Error, couldn't select .expand stack frame",
3795b9c1b51eSKate Stone                   __FUNCTION__);
3796018f5a7eSEwan Crawford     return false;
3797018f5a7eSEwan Crawford   }
3798018f5a7eSEwan Crawford 
3799018f5a7eSEwan Crawford   if (log)
380000f56eebSLuke Drummond     log->Printf("%s - " FMT_COORD, __FUNCTION__, current_coord.x,
380100f56eebSLuke Drummond                 current_coord.y, current_coord.z);
3802018f5a7eSEwan Crawford 
3803b9c1b51eSKate Stone   // Check if the current kernel invocation coordinate matches our target
3804b9c1b51eSKate Stone   // coordinate
380500f56eebSLuke Drummond   if (target_coord == current_coord) {
3806018f5a7eSEwan Crawford     if (log)
380700f56eebSLuke Drummond       log->Printf("%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
380800f56eebSLuke Drummond                   current_coord.y, current_coord.z);
3809018f5a7eSEwan Crawford 
3810b9c1b51eSKate Stone     BreakpointSP breakpoint_sp =
3811b9c1b51eSKate Stone         context.GetTargetPtr()->GetBreakpointByID(break_id);
3812b9c1b51eSKate Stone     assert(breakpoint_sp != nullptr &&
3813b9c1b51eSKate Stone            "Error: Couldn't find breakpoint matching break id for callback");
3814b9c1b51eSKate Stone     breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3815b9c1b51eSKate Stone                                       // should only be hit once.
3816018f5a7eSEwan Crawford     return true;
3817018f5a7eSEwan Crawford   }
3818018f5a7eSEwan Crawford 
3819018f5a7eSEwan Crawford   // No match on coordinate
3820018f5a7eSEwan Crawford   return false;
3821018f5a7eSEwan Crawford }
3822018f5a7eSEwan Crawford 
382300f56eebSLuke Drummond void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
382400f56eebSLuke Drummond                                          const RSCoordinate &coord) {
382500f56eebSLuke Drummond   messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
382600f56eebSLuke Drummond                   coord.x, coord.y, coord.z);
382700f56eebSLuke Drummond   messages.EOL();
382800f56eebSLuke Drummond 
382900f56eebSLuke Drummond   // Allocate memory for the baton, and copy over coordinate
383000f56eebSLuke Drummond   RSCoordinate *baton = new RSCoordinate(coord);
383100f56eebSLuke Drummond 
383200f56eebSLuke Drummond   // Create a callback that will be invoked every time the breakpoint is hit.
383300f56eebSLuke Drummond   // The baton object passed to the handler is the target coordinate we want to
383400f56eebSLuke Drummond   // break on.
383500f56eebSLuke Drummond   bp->SetCallback(KernelBreakpointHit, baton, true);
383600f56eebSLuke Drummond 
383700f56eebSLuke Drummond   // Store a shared pointer to the baton, so the memory will eventually be
383800f56eebSLuke Drummond   // cleaned up after destruction
383900f56eebSLuke Drummond   m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
384000f56eebSLuke Drummond }
384100f56eebSLuke Drummond 
384205097246SAdrian Prantl // Tries to set a breakpoint on the start of a kernel, resolved using the
384305097246SAdrian Prantl // kernel name. Argument 'coords', represents a three dimensional coordinate
384405097246SAdrian Prantl // which can be used to specify a single kernel instance to break on. If this
384505097246SAdrian Prantl // is set then we add a callback to the breakpoint.
384600f56eebSLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
384700f56eebSLuke Drummond                                                   Stream &messages,
384800f56eebSLuke Drummond                                                   const char *name,
384900f56eebSLuke Drummond                                                   const RSCoordinate *coord) {
385000f56eebSLuke Drummond   if (!name)
385100f56eebSLuke Drummond     return false;
38524640cde1SColin Riley 
38537dc7771cSEwan Crawford   InitSearchFilter(target);
385498156583SEwan Crawford 
38554640cde1SColin Riley   ConstString kernel_name(name);
38567dc7771cSEwan Crawford   BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
385700f56eebSLuke Drummond   if (!bp)
385800f56eebSLuke Drummond     return false;
3859018f5a7eSEwan Crawford 
3860018f5a7eSEwan Crawford   // We have a conditional breakpoint on a specific coordinate
386100f56eebSLuke Drummond   if (coord)
386200f56eebSLuke Drummond     SetConditional(bp, messages, *coord);
3863018f5a7eSEwan Crawford 
386400f56eebSLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3865018f5a7eSEwan Crawford 
386600f56eebSLuke Drummond   return true;
38674640cde1SColin Riley }
38684640cde1SColin Riley 
386921fed052SAidan Dodds BreakpointSP
387021fed052SAidan Dodds RenderScriptRuntime::CreateScriptGroupBreakpoint(const ConstString &name,
387121fed052SAidan Dodds                                                  bool stop_on_all) {
387221fed052SAidan Dodds   Log *log(
387321fed052SAidan Dodds       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
387421fed052SAidan Dodds 
387521fed052SAidan Dodds   if (!m_filtersp) {
387621fed052SAidan Dodds     if (log)
387721fed052SAidan Dodds       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
387821fed052SAidan Dodds     return nullptr;
387921fed052SAidan Dodds   }
388021fed052SAidan Dodds 
388121fed052SAidan Dodds   BreakpointResolverSP resolver_sp(new RSScriptGroupBreakpointResolver(
388221fed052SAidan Dodds       nullptr, name, m_scriptGroups, stop_on_all));
3883b842f2ecSJim Ingham   Target &target = GetProcess()->GetTarget();
3884b842f2ecSJim Ingham   BreakpointSP bp = target.CreateBreakpoint(
388521fed052SAidan Dodds       m_filtersp, resolver_sp, false, false, false);
388621fed052SAidan Dodds   // Give RS breakpoints a specific name, so the user can manipulate them as a
388721fed052SAidan Dodds   // group.
388897206d57SZachary Turner   Status err;
3889b842f2ecSJim Ingham   target.AddNameToBreakpoint(bp, name.GetCString(), err);
3890b842f2ecSJim Ingham   if (err.Fail() && log)
389121fed052SAidan Dodds     log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
389221fed052SAidan Dodds                 err.AsCString());
389321fed052SAidan Dodds   // ask the breakpoint to resolve itself
389421fed052SAidan Dodds   bp->ResolveBreakpoint();
389521fed052SAidan Dodds   return bp;
389621fed052SAidan Dodds }
389721fed052SAidan Dodds 
389821fed052SAidan Dodds bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target,
389921fed052SAidan Dodds                                                        Stream &strm,
390021fed052SAidan Dodds                                                        const ConstString &name,
390121fed052SAidan Dodds                                                        bool multi) {
390221fed052SAidan Dodds   InitSearchFilter(target);
390321fed052SAidan Dodds   BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi);
390421fed052SAidan Dodds   if (bp)
390521fed052SAidan Dodds     bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
390621fed052SAidan Dodds   return bool(bp);
390721fed052SAidan Dodds }
390821fed052SAidan Dodds 
3909b3bbcb12SLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3910b3bbcb12SLuke Drummond                                                      Stream &messages,
3911b3bbcb12SLuke Drummond                                                      const char *reduce_name,
3912b3bbcb12SLuke Drummond                                                      const RSCoordinate *coord,
3913b3bbcb12SLuke Drummond                                                      int kernel_types) {
3914b3bbcb12SLuke Drummond   if (!reduce_name)
3915b3bbcb12SLuke Drummond     return false;
3916b3bbcb12SLuke Drummond 
3917b3bbcb12SLuke Drummond   InitSearchFilter(target);
3918b3bbcb12SLuke Drummond   BreakpointSP bp =
3919b3bbcb12SLuke Drummond       CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3920b3bbcb12SLuke Drummond   if (!bp)
3921b3bbcb12SLuke Drummond     return false;
3922b3bbcb12SLuke Drummond 
3923b3bbcb12SLuke Drummond   if (coord)
3924b3bbcb12SLuke Drummond     SetConditional(bp, messages, *coord);
3925b3bbcb12SLuke Drummond 
3926b3bbcb12SLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3927b3bbcb12SLuke Drummond 
3928b3bbcb12SLuke Drummond   return true;
3929b3bbcb12SLuke Drummond }
3930b3bbcb12SLuke Drummond 
3931b9c1b51eSKate Stone void RenderScriptRuntime::DumpModules(Stream &strm) const {
39325ec532a9SColin Riley   strm.Printf("RenderScript Modules:");
39335ec532a9SColin Riley   strm.EOL();
39345ec532a9SColin Riley   strm.IndentMore();
3935b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
39364640cde1SColin Riley     module->Dump(strm);
39375ec532a9SColin Riley   }
39385ec532a9SColin Riley   strm.IndentLess();
39395ec532a9SColin Riley }
39405ec532a9SColin Riley 
394178f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails *
3942b9c1b51eSKate Stone RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3943b9c1b51eSKate Stone   for (const auto &s : m_scripts) {
394478f339d1SEwan Crawford     if (s->script.isValid())
394578f339d1SEwan Crawford       if (*s->script == address)
394678f339d1SEwan Crawford         return s.get();
394778f339d1SEwan Crawford   }
3948b9c1b51eSKate Stone   if (create) {
394978f339d1SEwan Crawford     std::unique_ptr<ScriptDetails> s(new ScriptDetails);
395078f339d1SEwan Crawford     s->script = address;
395178f339d1SEwan Crawford     m_scripts.push_back(std::move(s));
3952d10ca9deSEwan Crawford     return m_scripts.back().get();
395378f339d1SEwan Crawford   }
395478f339d1SEwan Crawford   return nullptr;
395578f339d1SEwan Crawford }
395678f339d1SEwan Crawford 
395778f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails *
3958b9c1b51eSKate Stone RenderScriptRuntime::LookUpAllocation(addr_t address) {
3959b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
396078f339d1SEwan Crawford     if (a->address.isValid())
396178f339d1SEwan Crawford       if (*a->address == address)
396278f339d1SEwan Crawford         return a.get();
396378f339d1SEwan Crawford   }
39645d057637SLuke Drummond   return nullptr;
39655d057637SLuke Drummond }
39665d057637SLuke Drummond 
39675d057637SLuke Drummond RenderScriptRuntime::AllocationDetails *
3968b9c1b51eSKate Stone RenderScriptRuntime::CreateAllocation(addr_t address) {
39695d057637SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
39705d057637SLuke Drummond 
39715d057637SLuke Drummond   // Remove any previous allocation which contains the same address
39725d057637SLuke Drummond   auto it = m_allocations.begin();
3973b9c1b51eSKate Stone   while (it != m_allocations.end()) {
3974b9c1b51eSKate Stone     if (*((*it)->address) == address) {
39755d057637SLuke Drummond       if (log)
3976b9c1b51eSKate Stone         log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64,
3977b9c1b51eSKate Stone                     __FUNCTION__, (*it)->id, address);
39785d057637SLuke Drummond 
39795d057637SLuke Drummond       it = m_allocations.erase(it);
3980b9c1b51eSKate Stone     } else {
39815d057637SLuke Drummond       it++;
39825d057637SLuke Drummond     }
39835d057637SLuke Drummond   }
39845d057637SLuke Drummond 
398578f339d1SEwan Crawford   std::unique_ptr<AllocationDetails> a(new AllocationDetails);
398678f339d1SEwan Crawford   a->address = address;
398778f339d1SEwan Crawford   m_allocations.push_back(std::move(a));
3988d10ca9deSEwan Crawford   return m_allocations.back().get();
398978f339d1SEwan Crawford }
399078f339d1SEwan Crawford 
399121fed052SAidan Dodds bool RenderScriptRuntime::ResolveKernelName(lldb::addr_t kernel_addr,
399221fed052SAidan Dodds                                             ConstString &name) {
399321fed052SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
399421fed052SAidan Dodds 
399521fed052SAidan Dodds   Target &target = GetProcess()->GetTarget();
399621fed052SAidan Dodds   Address resolved;
399721fed052SAidan Dodds   // RenderScript module
399821fed052SAidan Dodds   if (!target.GetSectionLoadList().ResolveLoadAddress(kernel_addr, resolved)) {
399921fed052SAidan Dodds     if (log)
400021fed052SAidan Dodds       log->Printf("%s: unable to resolve 0x%" PRIx64 " to a loaded symbol",
400121fed052SAidan Dodds                   __FUNCTION__, kernel_addr);
400221fed052SAidan Dodds     return false;
400321fed052SAidan Dodds   }
400421fed052SAidan Dodds 
400521fed052SAidan Dodds   Symbol *sym = resolved.CalculateSymbolContextSymbol();
400621fed052SAidan Dodds   if (!sym)
400721fed052SAidan Dodds     return false;
400821fed052SAidan Dodds 
400921fed052SAidan Dodds   name = sym->GetName();
401021fed052SAidan Dodds   assert(IsRenderScriptModule(resolved.CalculateSymbolContextModule()));
401121fed052SAidan Dodds   if (log)
401221fed052SAidan Dodds     log->Printf("%s: 0x%" PRIx64 " resolved to the symbol '%s'", __FUNCTION__,
401321fed052SAidan Dodds                 kernel_addr, name.GetCString());
401421fed052SAidan Dodds   return true;
401521fed052SAidan Dodds }
401621fed052SAidan Dodds 
4017b9c1b51eSKate Stone void RSModuleDescriptor::Dump(Stream &strm) const {
40187f193d69SLuke Drummond   int indent = strm.GetIndentLevel();
40197f193d69SLuke Drummond 
40205ec532a9SColin Riley   strm.Indent();
40215ec532a9SColin Riley   m_module->GetFileSpec().Dump(&strm);
40227f193d69SLuke Drummond   strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
40237f193d69SLuke Drummond                                              : "Debug info does not exist.");
40245ec532a9SColin Riley   strm.EOL();
40255ec532a9SColin Riley   strm.IndentMore();
40267f193d69SLuke Drummond 
40275ec532a9SColin Riley   strm.Indent();
4028189598edSColin Riley   strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
40295ec532a9SColin Riley   strm.EOL();
40305ec532a9SColin Riley   strm.IndentMore();
4031b9c1b51eSKate Stone   for (const auto &global : m_globals) {
40325ec532a9SColin Riley     global.Dump(strm);
40335ec532a9SColin Riley   }
40345ec532a9SColin Riley   strm.IndentLess();
40357f193d69SLuke Drummond 
40365ec532a9SColin Riley   strm.Indent();
4037189598edSColin Riley   strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
40385ec532a9SColin Riley   strm.EOL();
40395ec532a9SColin Riley   strm.IndentMore();
4040b9c1b51eSKate Stone   for (const auto &kernel : m_kernels) {
40415ec532a9SColin Riley     kernel.Dump(strm);
40425ec532a9SColin Riley   }
40437f193d69SLuke Drummond   strm.IndentLess();
40447f193d69SLuke Drummond 
40457f193d69SLuke Drummond   strm.Indent();
40464640cde1SColin Riley   strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
40474640cde1SColin Riley   strm.EOL();
40484640cde1SColin Riley   strm.IndentMore();
4049b9c1b51eSKate Stone   for (const auto &key_val : m_pragmas) {
40507f193d69SLuke Drummond     strm.Indent();
40514640cde1SColin Riley     strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
40524640cde1SColin Riley     strm.EOL();
40534640cde1SColin Riley   }
40547f193d69SLuke Drummond   strm.IndentLess();
40557f193d69SLuke Drummond 
40567f193d69SLuke Drummond   strm.Indent();
40577f193d69SLuke Drummond   strm.Printf("Reductions: %" PRIu64,
40587f193d69SLuke Drummond               static_cast<uint64_t>(m_reductions.size()));
40597f193d69SLuke Drummond   strm.EOL();
40607f193d69SLuke Drummond   strm.IndentMore();
40617f193d69SLuke Drummond   for (const auto &reduction : m_reductions) {
40627f193d69SLuke Drummond     reduction.Dump(strm);
40637f193d69SLuke Drummond   }
40647f193d69SLuke Drummond 
40657f193d69SLuke Drummond   strm.SetIndentLevel(indent);
40665ec532a9SColin Riley }
40675ec532a9SColin Riley 
4068b9c1b51eSKate Stone void RSGlobalDescriptor::Dump(Stream &strm) const {
40695ec532a9SColin Riley   strm.Indent(m_name.AsCString());
40704640cde1SColin Riley   VariableList var_list;
407134cda14bSPavel Labath   m_module->m_module->FindGlobalVariables(m_name, nullptr, 1U, var_list);
4072b9c1b51eSKate Stone   if (var_list.GetSize() == 1) {
40734640cde1SColin Riley     auto var = var_list.GetVariableAtIndex(0);
40744640cde1SColin Riley     auto type = var->GetType();
4075b9c1b51eSKate Stone     if (type) {
40764640cde1SColin Riley       strm.Printf(" - ");
40774640cde1SColin Riley       type->DumpTypeName(&strm);
4078b9c1b51eSKate Stone     } else {
40794640cde1SColin Riley       strm.Printf(" - Unknown Type");
40804640cde1SColin Riley     }
4081b9c1b51eSKate Stone   } else {
40824640cde1SColin Riley     strm.Printf(" - variable identified, but not found in binary");
4083b9c1b51eSKate Stone     const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
4084b9c1b51eSKate Stone         m_name, eSymbolTypeData);
4085b9c1b51eSKate Stone     if (s) {
40864640cde1SColin Riley       strm.Printf(" (symbol exists) ");
40874640cde1SColin Riley     }
40884640cde1SColin Riley   }
40894640cde1SColin Riley 
40905ec532a9SColin Riley   strm.EOL();
40915ec532a9SColin Riley }
40925ec532a9SColin Riley 
4093b9c1b51eSKate Stone void RSKernelDescriptor::Dump(Stream &strm) const {
40945ec532a9SColin Riley   strm.Indent(m_name.AsCString());
40955ec532a9SColin Riley   strm.EOL();
40965ec532a9SColin Riley }
40975ec532a9SColin Riley 
40987f193d69SLuke Drummond void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
40997f193d69SLuke Drummond   stream.Indent(m_reduce_name.AsCString());
41007f193d69SLuke Drummond   stream.IndentMore();
41017f193d69SLuke Drummond   stream.EOL();
41027f193d69SLuke Drummond   stream.Indent();
41037f193d69SLuke Drummond   stream.Printf("accumulator: %s", m_accum_name.AsCString());
41047f193d69SLuke Drummond   stream.EOL();
41057f193d69SLuke Drummond   stream.Indent();
41067f193d69SLuke Drummond   stream.Printf("initializer: %s", m_init_name.AsCString());
41077f193d69SLuke Drummond   stream.EOL();
41087f193d69SLuke Drummond   stream.Indent();
41097f193d69SLuke Drummond   stream.Printf("combiner: %s", m_comb_name.AsCString());
41107f193d69SLuke Drummond   stream.EOL();
41117f193d69SLuke Drummond   stream.Indent();
41127f193d69SLuke Drummond   stream.Printf("outconverter: %s", m_outc_name.AsCString());
41137f193d69SLuke Drummond   stream.EOL();
41147f193d69SLuke Drummond   // XXX This is currently unspecified by RenderScript, and unused
41157f193d69SLuke Drummond   // stream.Indent();
41167f193d69SLuke Drummond   // stream.Printf("halter: '%s'", m_init_name.AsCString());
41177f193d69SLuke Drummond   // stream.EOL();
41187f193d69SLuke Drummond   stream.IndentLess();
41197f193d69SLuke Drummond }
41207f193d69SLuke Drummond 
4121b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
41225ec532a9SColin Riley public:
41235ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
4124b9c1b51eSKate Stone       : CommandObjectParsed(
4125b9c1b51eSKate Stone             interpreter, "renderscript module dump",
4126b9c1b51eSKate Stone             "Dumps renderscript specific information for all modules.",
4127b9c1b51eSKate Stone             "renderscript module dump",
4128b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
41295ec532a9SColin Riley 
4130222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
41315ec532a9SColin Riley 
4132b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
41335ec532a9SColin Riley     RenderScriptRuntime *runtime =
4134b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4135b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
41365ec532a9SColin Riley     runtime->DumpModules(result.GetOutputStream());
41375ec532a9SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
41385ec532a9SColin Riley     return true;
41395ec532a9SColin Riley   }
41405ec532a9SColin Riley };
41415ec532a9SColin Riley 
4142b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
41435ec532a9SColin Riley public:
41445ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
4145b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript module",
4146b9c1b51eSKate Stone                                "Commands that deal with RenderScript modules.",
4147b9c1b51eSKate Stone                                nullptr) {
4148b9c1b51eSKate Stone     LoadSubCommand(
4149b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
4150b9c1b51eSKate Stone                     interpreter)));
41515ec532a9SColin Riley   }
41525ec532a9SColin Riley 
4153222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModule() override = default;
41545ec532a9SColin Riley };
41555ec532a9SColin Riley 
4156b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
41574640cde1SColin Riley public:
41584640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
4159b9c1b51eSKate Stone       : CommandObjectParsed(
4160b9c1b51eSKate Stone             interpreter, "renderscript kernel list",
4161b3f7f69dSAidan Dodds             "Lists renderscript kernel names and associated script resources.",
4162b9c1b51eSKate Stone             "renderscript kernel list",
4163b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
41644640cde1SColin Riley 
4165222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelList() override = default;
41664640cde1SColin Riley 
4167b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
41684640cde1SColin Riley     RenderScriptRuntime *runtime =
4169b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4170b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
41714640cde1SColin Riley     runtime->DumpKernels(result.GetOutputStream());
41724640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
41734640cde1SColin Riley     return true;
41744640cde1SColin Riley   }
41754640cde1SColin Riley };
41764640cde1SColin Riley 
41778fe53c49STatyana Krasnukha static constexpr OptionDefinition g_renderscript_reduction_bp_set_options[] = {
4178b3bbcb12SLuke Drummond     {LLDB_OPT_SET_1, false, "function-role", 't',
41798fe53c49STatyana Krasnukha      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOneLiner,
4180b3bbcb12SLuke Drummond      "Break on a comma separated set of reduction kernel types "
4181b3bbcb12SLuke Drummond      "(accumulator,outcoverter,combiner,initializer"},
4182b3bbcb12SLuke Drummond     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
41838fe53c49STatyana Krasnukha      nullptr, {}, 0, eArgTypeValue,
4184b3bbcb12SLuke Drummond      "Set a breakpoint on a single invocation of the kernel with specified "
4185b3bbcb12SLuke Drummond      "coordinate.\n"
4186b3bbcb12SLuke Drummond      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4187b3bbcb12SLuke Drummond      "integers representing kernel dimensions. "
4188b3bbcb12SLuke Drummond      "Any unset dimensions will be defaulted to zero."}};
4189b3bbcb12SLuke Drummond 
4190b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReductionBreakpointSet
4191b3bbcb12SLuke Drummond     : public CommandObjectParsed {
4192b3bbcb12SLuke Drummond public:
4193b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4194b3bbcb12SLuke Drummond       CommandInterpreter &interpreter)
4195b3bbcb12SLuke Drummond       : CommandObjectParsed(
4196b3bbcb12SLuke Drummond             interpreter, "renderscript reduction breakpoint set",
4197b3bbcb12SLuke Drummond             "Set a breakpoint on named RenderScript general reductions",
4198b3bbcb12SLuke Drummond             "renderscript reduction breakpoint set  <kernel_name> [-t "
4199b3bbcb12SLuke Drummond             "<reduction_kernel_type,...>]",
4200b3bbcb12SLuke Drummond             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4201b3bbcb12SLuke Drummond                 eCommandProcessMustBePaused),
4202b3bbcb12SLuke Drummond         m_options(){};
4203b3bbcb12SLuke Drummond 
4204b3bbcb12SLuke Drummond   class CommandOptions : public Options {
4205b3bbcb12SLuke Drummond   public:
4206b3bbcb12SLuke Drummond     CommandOptions()
4207b3bbcb12SLuke Drummond         : Options(),
4208b3bbcb12SLuke Drummond           m_kernel_types(RSReduceBreakpointResolver::eKernelTypeAll) {}
4209b3bbcb12SLuke Drummond 
4210b3bbcb12SLuke Drummond     ~CommandOptions() override = default;
4211b3bbcb12SLuke Drummond 
421297206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4213b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
421497206d57SZachary Turner       Status err;
4215b3bbcb12SLuke Drummond       StreamString err_str;
4216b3bbcb12SLuke Drummond       const int short_option = m_getopt_table[option_idx].val;
4217b3bbcb12SLuke Drummond       switch (short_option) {
4218b3bbcb12SLuke Drummond       case 't':
4219fe11483bSZachary Turner         if (!ParseReductionTypes(option_arg, err_str))
4220b3bbcb12SLuke Drummond           err.SetErrorStringWithFormat(
4221fe11483bSZachary Turner               "Unable to deduce reduction types for %s: %s",
4222fe11483bSZachary Turner               option_arg.str().c_str(), err_str.GetData());
4223b3bbcb12SLuke Drummond         break;
4224b3bbcb12SLuke Drummond       case 'c': {
4225b3bbcb12SLuke Drummond         auto coord = RSCoordinate{};
4226fe11483bSZachary Turner         if (!ParseCoordinate(option_arg, coord))
4227b3bbcb12SLuke Drummond           err.SetErrorStringWithFormat("unable to parse coordinate for %s",
4228fe11483bSZachary Turner                                        option_arg.str().c_str());
4229b3bbcb12SLuke Drummond         else {
4230b3bbcb12SLuke Drummond           m_have_coord = true;
4231b3bbcb12SLuke Drummond           m_coord = coord;
4232b3bbcb12SLuke Drummond         }
4233b3bbcb12SLuke Drummond         break;
4234b3bbcb12SLuke Drummond       }
4235b3bbcb12SLuke Drummond       default:
4236b3bbcb12SLuke Drummond         err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
4237b3bbcb12SLuke Drummond       }
4238b3bbcb12SLuke Drummond       return err;
4239b3bbcb12SLuke Drummond     }
4240b3bbcb12SLuke Drummond 
4241b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4242b3bbcb12SLuke Drummond       m_have_coord = false;
4243b3bbcb12SLuke Drummond     }
4244b3bbcb12SLuke Drummond 
4245b3bbcb12SLuke Drummond     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4246b3bbcb12SLuke Drummond       return llvm::makeArrayRef(g_renderscript_reduction_bp_set_options);
4247b3bbcb12SLuke Drummond     }
4248b3bbcb12SLuke Drummond 
4249fe11483bSZachary Turner     bool ParseReductionTypes(llvm::StringRef option_val,
4250fe11483bSZachary Turner                              StreamString &err_str) {
4251b3bbcb12SLuke Drummond       m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
4252b3bbcb12SLuke Drummond       const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
4253b3bbcb12SLuke Drummond         return llvm::StringSwitch<int>(name)
4254b3bbcb12SLuke Drummond             .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
4255b3bbcb12SLuke Drummond             .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
4256b3bbcb12SLuke Drummond             .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
4257b3bbcb12SLuke Drummond             .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
4258b3bbcb12SLuke Drummond             .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
4259b3bbcb12SLuke Drummond             // Currently not exposed by the runtime
4260b3bbcb12SLuke Drummond             // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
4261b3bbcb12SLuke Drummond             .Default(0);
4262b3bbcb12SLuke Drummond       };
4263b3bbcb12SLuke Drummond 
4264b3bbcb12SLuke Drummond       // Matching a comma separated list of known words is fairly
426505097246SAdrian Prantl       // straightforward with PCRE, but we're using ERE, so we end up with a
426605097246SAdrian Prantl       // little ugliness...
4267b3bbcb12SLuke Drummond       RegularExpression::Match match(/* max_matches */ 5);
4268b3bbcb12SLuke Drummond       RegularExpression match_type_list(
4269b3bbcb12SLuke Drummond           llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
4270b3bbcb12SLuke Drummond 
4271b3bbcb12SLuke Drummond       assert(match_type_list.IsValid());
4272b3bbcb12SLuke Drummond 
4273fe11483bSZachary Turner       if (!match_type_list.Execute(option_val, &match)) {
4274b3bbcb12SLuke Drummond         err_str.PutCString(
4275b3bbcb12SLuke Drummond             "a comma-separated list of kernel types is required");
4276b3bbcb12SLuke Drummond         return false;
4277b3bbcb12SLuke Drummond       }
4278b3bbcb12SLuke Drummond 
4279b3bbcb12SLuke Drummond       // splitting on commas is much easier with llvm::StringRef than regex
4280b3bbcb12SLuke Drummond       llvm::SmallVector<llvm::StringRef, 5> type_names;
4281b3bbcb12SLuke Drummond       llvm::StringRef(option_val).split(type_names, ',');
4282b3bbcb12SLuke Drummond 
4283b3bbcb12SLuke Drummond       for (const auto &name : type_names) {
4284b3bbcb12SLuke Drummond         const int type = reduce_name_to_type(name);
4285b3bbcb12SLuke Drummond         if (!type) {
4286b3bbcb12SLuke Drummond           err_str.Printf("unknown kernel type name %s", name.str().c_str());
4287b3bbcb12SLuke Drummond           return false;
4288b3bbcb12SLuke Drummond         }
4289b3bbcb12SLuke Drummond         m_kernel_types |= type;
4290b3bbcb12SLuke Drummond       }
4291b3bbcb12SLuke Drummond 
4292b3bbcb12SLuke Drummond       return true;
4293b3bbcb12SLuke Drummond     }
4294b3bbcb12SLuke Drummond 
4295b3bbcb12SLuke Drummond     int m_kernel_types;
4296b3bbcb12SLuke Drummond     llvm::StringRef m_reduce_name;
4297b3bbcb12SLuke Drummond     RSCoordinate m_coord;
4298b3bbcb12SLuke Drummond     bool m_have_coord;
4299b3bbcb12SLuke Drummond   };
4300b3bbcb12SLuke Drummond 
4301b3bbcb12SLuke Drummond   Options *GetOptions() override { return &m_options; }
4302b3bbcb12SLuke Drummond 
4303b3bbcb12SLuke Drummond   bool DoExecute(Args &command, CommandReturnObject &result) override {
4304b3bbcb12SLuke Drummond     const size_t argc = command.GetArgumentCount();
4305b3bbcb12SLuke Drummond     if (argc < 1) {
4306b3bbcb12SLuke Drummond       result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
4307b3bbcb12SLuke Drummond                                    "and an optional kernel type list",
4308b3bbcb12SLuke Drummond                                    m_cmd_name.c_str());
4309b3bbcb12SLuke Drummond       result.SetStatus(eReturnStatusFailed);
4310b3bbcb12SLuke Drummond       return false;
4311b3bbcb12SLuke Drummond     }
4312b3bbcb12SLuke Drummond 
4313b3bbcb12SLuke Drummond     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4314b3bbcb12SLuke Drummond         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4315b3bbcb12SLuke Drummond             eLanguageTypeExtRenderScript));
4316b3bbcb12SLuke Drummond 
4317b3bbcb12SLuke Drummond     auto &outstream = result.GetOutputStream();
4318b3bbcb12SLuke Drummond     auto name = command.GetArgumentAtIndex(0);
4319b3bbcb12SLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
4320b3bbcb12SLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4321b3bbcb12SLuke Drummond     if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
4322b3bbcb12SLuke Drummond                                              m_options.m_kernel_types)) {
4323b3bbcb12SLuke Drummond       result.SetStatus(eReturnStatusFailed);
4324b3bbcb12SLuke Drummond       result.AppendError("Error: unable to place breakpoint on reduction");
4325b3bbcb12SLuke Drummond       return false;
4326b3bbcb12SLuke Drummond     }
4327b3bbcb12SLuke Drummond     result.AppendMessage("Breakpoint(s) created");
4328b3bbcb12SLuke Drummond     result.SetStatus(eReturnStatusSuccessFinishResult);
4329b3bbcb12SLuke Drummond     return true;
4330b3bbcb12SLuke Drummond   }
4331b3bbcb12SLuke Drummond 
4332b3bbcb12SLuke Drummond private:
4333b3bbcb12SLuke Drummond   CommandOptions m_options;
4334b3bbcb12SLuke Drummond };
4335b3bbcb12SLuke Drummond 
43368fe53c49STatyana Krasnukha static constexpr OptionDefinition g_renderscript_kernel_bp_set_options[] = {
43371f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
43388fe53c49STatyana Krasnukha      nullptr, {}, 0, eArgTypeValue,
43391f0f5b5bSZachary Turner      "Set a breakpoint on a single invocation of the kernel with specified "
43401f0f5b5bSZachary Turner      "coordinate.\n"
43411f0f5b5bSZachary Turner      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
43421f0f5b5bSZachary Turner      "integers representing kernel dimensions. "
43431f0f5b5bSZachary Turner      "Any unset dimensions will be defaulted to zero."}};
43441f0f5b5bSZachary Turner 
4345b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointSet
4346b9c1b51eSKate Stone     : public CommandObjectParsed {
43474640cde1SColin Riley public:
4348b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4349b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4350b9c1b51eSKate Stone       : CommandObjectParsed(
4351b9c1b51eSKate Stone             interpreter, "renderscript kernel breakpoint set",
4352b3f7f69dSAidan Dodds             "Sets a breakpoint on a renderscript kernel.",
4353b3f7f69dSAidan Dodds             "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
4354b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4355b9c1b51eSKate Stone                 eCommandProcessMustBePaused),
4356b9c1b51eSKate Stone         m_options() {}
43574640cde1SColin Riley 
4358222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
4359222b937cSEugene Zelenko 
4360b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
4361018f5a7eSEwan Crawford 
4362b9c1b51eSKate Stone   class CommandOptions : public Options {
4363018f5a7eSEwan Crawford   public:
4364e1cfbc79STodd Fiala     CommandOptions() : Options() {}
4365018f5a7eSEwan Crawford 
4366222b937cSEugene Zelenko     ~CommandOptions() override = default;
4367018f5a7eSEwan Crawford 
436897206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4369b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
437097206d57SZachary Turner       Status err;
4371018f5a7eSEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
4372018f5a7eSEwan Crawford 
4373b9c1b51eSKate Stone       switch (short_option) {
437400f56eebSLuke Drummond       case 'c': {
437500f56eebSLuke Drummond         auto coord = RSCoordinate{};
437600f56eebSLuke Drummond         if (!ParseCoordinate(option_arg, coord))
437780af0b9eSLuke Drummond           err.SetErrorStringWithFormat(
4378b9c1b51eSKate Stone               "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
4379fe11483bSZachary Turner               option_arg.str().c_str());
438000f56eebSLuke Drummond         else {
438100f56eebSLuke Drummond           m_have_coord = true;
438200f56eebSLuke Drummond           m_coord = coord;
438300f56eebSLuke Drummond         }
4384018f5a7eSEwan Crawford         break;
438500f56eebSLuke Drummond       }
4386018f5a7eSEwan Crawford       default:
438780af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4388018f5a7eSEwan Crawford         break;
4389018f5a7eSEwan Crawford       }
439080af0b9eSLuke Drummond       return err;
4391018f5a7eSEwan Crawford     }
4392018f5a7eSEwan Crawford 
4393b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
439400f56eebSLuke Drummond       m_have_coord = false;
4395018f5a7eSEwan Crawford     }
4396018f5a7eSEwan Crawford 
43971f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
439870602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
43991f0f5b5bSZachary Turner     }
4400018f5a7eSEwan Crawford 
440100f56eebSLuke Drummond     RSCoordinate m_coord;
440200f56eebSLuke Drummond     bool m_have_coord;
4403018f5a7eSEwan Crawford   };
4404018f5a7eSEwan Crawford 
4405b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
44064640cde1SColin Riley     const size_t argc = command.GetArgumentCount();
4407b9c1b51eSKate Stone     if (argc < 1) {
4408b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4409b9c1b51eSKate Stone           "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4410b3f7f69dSAidan Dodds           m_cmd_name.c_str());
4411018f5a7eSEwan Crawford       result.SetStatus(eReturnStatusFailed);
4412018f5a7eSEwan Crawford       return false;
4413018f5a7eSEwan Crawford     }
4414018f5a7eSEwan Crawford 
44154640cde1SColin Riley     RenderScriptRuntime *runtime =
4416b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4417b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
44184640cde1SColin Riley 
441900f56eebSLuke Drummond     auto &outstream = result.GetOutputStream();
442000f56eebSLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
442100f56eebSLuke Drummond     auto name = command.GetArgumentAtIndex(0);
442200f56eebSLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
442300f56eebSLuke Drummond     if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
442400f56eebSLuke Drummond       result.SetStatus(eReturnStatusFailed);
442500f56eebSLuke Drummond       result.AppendErrorWithFormat(
442600f56eebSLuke Drummond           "Error: unable to set breakpoint on kernel '%s'", name);
442700f56eebSLuke Drummond       return false;
442800f56eebSLuke Drummond     }
44294640cde1SColin Riley 
44304640cde1SColin Riley     result.AppendMessage("Breakpoint(s) created");
44314640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
44324640cde1SColin Riley     return true;
44334640cde1SColin Riley   }
44344640cde1SColin Riley 
4435018f5a7eSEwan Crawford private:
4436018f5a7eSEwan Crawford   CommandOptions m_options;
44374640cde1SColin Riley };
44384640cde1SColin Riley 
4439b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4440b9c1b51eSKate Stone     : public CommandObjectParsed {
44417dc7771cSEwan Crawford public:
4442b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4443b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4444b3f7f69dSAidan Dodds       : CommandObjectParsed(
4445b3f7f69dSAidan Dodds             interpreter, "renderscript kernel breakpoint all",
4446b9c1b51eSKate Stone             "Automatically sets a breakpoint on all renderscript kernels that "
4447b9c1b51eSKate Stone             "are or will be loaded.\n"
4448b9c1b51eSKate Stone             "Disabling option means breakpoints will no longer be set on any "
4449b9c1b51eSKate Stone             "kernels loaded in the future, "
44507dc7771cSEwan Crawford             "but does not remove currently set breakpoints.",
44517dc7771cSEwan Crawford             "renderscript kernel breakpoint all <enable/disable>",
4452b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4453b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
44547dc7771cSEwan Crawford 
4455222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
44567dc7771cSEwan Crawford 
4457b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
44587dc7771cSEwan Crawford     const size_t argc = command.GetArgumentCount();
4459b9c1b51eSKate Stone     if (argc != 1) {
4460b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4461b9c1b51eSKate Stone           "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
44627dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
44637dc7771cSEwan Crawford       return false;
44647dc7771cSEwan Crawford     }
44657dc7771cSEwan Crawford 
4466b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4467b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4468b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
44697dc7771cSEwan Crawford 
44707dc7771cSEwan Crawford     bool do_break = false;
44717dc7771cSEwan Crawford     const char *argument = command.GetArgumentAtIndex(0);
4472b9c1b51eSKate Stone     if (strcmp(argument, "enable") == 0) {
44737dc7771cSEwan Crawford       do_break = true;
44747dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will be set on all kernels.");
4475b9c1b51eSKate Stone     } else if (strcmp(argument, "disable") == 0) {
44767dc7771cSEwan Crawford       do_break = false;
44777dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will not be set on any new kernels.");
4478b9c1b51eSKate Stone     } else {
4479b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4480b9c1b51eSKate Stone           "Argument must be either 'enable' or 'disable'");
44817dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
44827dc7771cSEwan Crawford       return false;
44837dc7771cSEwan Crawford     }
44847dc7771cSEwan Crawford 
44857dc7771cSEwan Crawford     runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
44867dc7771cSEwan Crawford 
44877dc7771cSEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
44887dc7771cSEwan Crawford     return true;
44897dc7771cSEwan Crawford   }
44907dc7771cSEwan Crawford };
44917dc7771cSEwan Crawford 
4492b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReductionBreakpoint
4493b3bbcb12SLuke Drummond     : public CommandObjectMultiword {
4494b3bbcb12SLuke Drummond public:
4495b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReductionBreakpoint(
4496b3bbcb12SLuke Drummond       CommandInterpreter &interpreter)
4497b3bbcb12SLuke Drummond       : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4498b3bbcb12SLuke Drummond                                "Commands that manipulate breakpoints on "
4499b3bbcb12SLuke Drummond                                "renderscript general reductions.",
4500b3bbcb12SLuke Drummond                                nullptr) {
4501b3bbcb12SLuke Drummond     LoadSubCommand(
4502b3bbcb12SLuke Drummond         "set", CommandObjectSP(
4503b3bbcb12SLuke Drummond                    new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4504b3bbcb12SLuke Drummond                        interpreter)));
4505b3bbcb12SLuke Drummond   }
4506b3bbcb12SLuke Drummond 
4507b3bbcb12SLuke Drummond   ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4508b3bbcb12SLuke Drummond };
4509b3bbcb12SLuke Drummond 
4510b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelCoordinate
4511b9c1b51eSKate Stone     : public CommandObjectParsed {
45124f8817c2SEwan Crawford public:
4513b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelCoordinate(
4514b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4515b9c1b51eSKate Stone       : CommandObjectParsed(
4516b9c1b51eSKate Stone             interpreter, "renderscript kernel coordinate",
45174f8817c2SEwan Crawford             "Shows the (x,y,z) coordinate of the current kernel invocation.",
45184f8817c2SEwan Crawford             "renderscript kernel coordinate",
4519b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4520b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
45214f8817c2SEwan Crawford 
45224f8817c2SEwan Crawford   ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
45234f8817c2SEwan Crawford 
4524b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
452500f56eebSLuke Drummond     RSCoordinate coord{};
4526b9c1b51eSKate Stone     bool success = RenderScriptRuntime::GetKernelCoordinate(
4527b9c1b51eSKate Stone         coord, m_exe_ctx.GetThreadPtr());
45284f8817c2SEwan Crawford     Stream &stream = result.GetOutputStream();
45294f8817c2SEwan Crawford 
4530b9c1b51eSKate Stone     if (success) {
453100f56eebSLuke Drummond       stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
45324f8817c2SEwan Crawford       stream.EOL();
45334f8817c2SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4534b9c1b51eSKate Stone     } else {
45354f8817c2SEwan Crawford       stream.Printf("Error: Coordinate could not be found.");
45364f8817c2SEwan Crawford       stream.EOL();
45374f8817c2SEwan Crawford       result.SetStatus(eReturnStatusFailed);
45384f8817c2SEwan Crawford     }
45394f8817c2SEwan Crawford     return true;
45404f8817c2SEwan Crawford   }
45414f8817c2SEwan Crawford };
45424f8817c2SEwan Crawford 
4543b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpoint
4544b9c1b51eSKate Stone     : public CommandObjectMultiword {
45457dc7771cSEwan Crawford public:
4546b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpoint(
4547b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4548b9c1b51eSKate Stone       : CommandObjectMultiword(
4549b9c1b51eSKate Stone             interpreter, "renderscript kernel",
4550b9c1b51eSKate Stone             "Commands that generate breakpoints on renderscript kernels.",
4551b9c1b51eSKate Stone             nullptr) {
4552b9c1b51eSKate Stone     LoadSubCommand(
4553b9c1b51eSKate Stone         "set",
4554b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4555b9c1b51eSKate Stone             interpreter)));
4556b9c1b51eSKate Stone     LoadSubCommand(
4557b9c1b51eSKate Stone         "all",
4558b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4559b9c1b51eSKate Stone             interpreter)));
45607dc7771cSEwan Crawford   }
45617dc7771cSEwan Crawford 
4562222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
45637dc7771cSEwan Crawford };
45647dc7771cSEwan Crawford 
4565b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
45664640cde1SColin Riley public:
45674640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4568b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript kernel",
4569b9c1b51eSKate Stone                                "Commands that deal with RenderScript kernels.",
4570b9c1b51eSKate Stone                                nullptr) {
4571b9c1b51eSKate Stone     LoadSubCommand(
4572b9c1b51eSKate Stone         "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4573b9c1b51eSKate Stone                     interpreter)));
4574b9c1b51eSKate Stone     LoadSubCommand(
4575b9c1b51eSKate Stone         "coordinate",
4576b9c1b51eSKate Stone         CommandObjectSP(
4577b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4578b9c1b51eSKate Stone     LoadSubCommand(
4579b9c1b51eSKate Stone         "breakpoint",
4580b9c1b51eSKate Stone         CommandObjectSP(
4581b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
45824640cde1SColin Riley   }
45834640cde1SColin Riley 
4584222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernel() override = default;
45854640cde1SColin Riley };
45864640cde1SColin Riley 
4587b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
45884640cde1SColin Riley public:
45894640cde1SColin Riley   CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4590b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript context dump",
4591b9c1b51eSKate Stone                             "Dumps renderscript context information.",
4592b9c1b51eSKate Stone                             "renderscript context dump",
4593b9c1b51eSKate Stone                             eCommandRequiresProcess |
4594b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
45954640cde1SColin Riley 
4596222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContextDump() override = default;
45974640cde1SColin Riley 
4598b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
45994640cde1SColin Riley     RenderScriptRuntime *runtime =
4600b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4601b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
46024640cde1SColin Riley     runtime->DumpContexts(result.GetOutputStream());
46034640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
46044640cde1SColin Riley     return true;
46054640cde1SColin Riley   }
46064640cde1SColin Riley };
46074640cde1SColin Riley 
46088fe53c49STatyana Krasnukha static constexpr OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
46091f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
46108fe53c49STatyana Krasnukha      nullptr, {}, 0, eArgTypeFilename,
46111f0f5b5bSZachary Turner      "Print results to specified file instead of command line."}};
46121f0f5b5bSZachary Turner 
4613b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
46144640cde1SColin Riley public:
46154640cde1SColin Riley   CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4616b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript context",
4617b9c1b51eSKate Stone                                "Commands that deal with RenderScript contexts.",
4618b9c1b51eSKate Stone                                nullptr) {
4619b9c1b51eSKate Stone     LoadSubCommand(
4620b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4621b9c1b51eSKate Stone                     interpreter)));
46224640cde1SColin Riley   }
46234640cde1SColin Riley 
4624222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContext() override = default;
46254640cde1SColin Riley };
46264640cde1SColin Riley 
4627b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationDump
4628b9c1b51eSKate Stone     : public CommandObjectParsed {
4629a0f08674SEwan Crawford public:
4630b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationDump(
4631b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4632a0f08674SEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation dump",
4633b9c1b51eSKate Stone                             "Displays the contents of a particular allocation",
4634b9c1b51eSKate Stone                             "renderscript allocation dump <ID>",
4635b9c1b51eSKate Stone                             eCommandRequiresProcess |
4636b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched),
4637b9c1b51eSKate Stone         m_options() {}
4638a0f08674SEwan Crawford 
4639222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4640222b937cSEugene Zelenko 
4641b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
4642a0f08674SEwan Crawford 
4643b9c1b51eSKate Stone   class CommandOptions : public Options {
4644a0f08674SEwan Crawford   public:
4645e1cfbc79STodd Fiala     CommandOptions() : Options() {}
4646a0f08674SEwan Crawford 
4647222b937cSEugene Zelenko     ~CommandOptions() override = default;
4648a0f08674SEwan Crawford 
464997206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4650b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
465197206d57SZachary Turner       Status err;
4652a0f08674SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
4653a0f08674SEwan Crawford 
4654b9c1b51eSKate Stone       switch (short_option) {
4655a0f08674SEwan Crawford       case 'f':
46568f3be7a3SJonas Devlieghere         m_outfile.SetFile(option_arg, FileSpec::Style::native);
46578f3be7a3SJonas Devlieghere         FileSystem::Instance().Resolve(m_outfile);
4658dbd7fabaSJonas Devlieghere         if (FileSystem::Instance().Exists(m_outfile)) {
4659a0f08674SEwan Crawford           m_outfile.Clear();
4660fe11483bSZachary Turner           err.SetErrorStringWithFormat("file already exists: '%s'",
4661fe11483bSZachary Turner                                        option_arg.str().c_str());
4662a0f08674SEwan Crawford         }
4663a0f08674SEwan Crawford         break;
4664a0f08674SEwan Crawford       default:
466580af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4666a0f08674SEwan Crawford         break;
4667a0f08674SEwan Crawford       }
466880af0b9eSLuke Drummond       return err;
4669a0f08674SEwan Crawford     }
4670a0f08674SEwan Crawford 
4671b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4672a0f08674SEwan Crawford       m_outfile.Clear();
4673a0f08674SEwan Crawford     }
4674a0f08674SEwan Crawford 
46751f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
467670602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
46771f0f5b5bSZachary Turner     }
4678a0f08674SEwan Crawford 
4679a0f08674SEwan Crawford     FileSpec m_outfile;
4680a0f08674SEwan Crawford   };
4681a0f08674SEwan Crawford 
4682b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4683a0f08674SEwan Crawford     const size_t argc = command.GetArgumentCount();
4684b9c1b51eSKate Stone     if (argc < 1) {
4685b9c1b51eSKate Stone       result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4686b9c1b51eSKate Stone                                    "As well as an optional -f argument",
4687a0f08674SEwan Crawford                                    m_cmd_name.c_str());
4688a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4689a0f08674SEwan Crawford       return false;
4690a0f08674SEwan Crawford     }
4691a0f08674SEwan Crawford 
4692b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4693b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4694b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4695a0f08674SEwan Crawford 
4696a0f08674SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
469780af0b9eSLuke Drummond     bool success = false;
4698b9c1b51eSKate Stone     const uint32_t id =
469980af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
470080af0b9eSLuke Drummond     if (!success) {
4701b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4702b9c1b51eSKate Stone                                    id_cstr);
4703a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4704a0f08674SEwan Crawford       return false;
4705a0f08674SEwan Crawford     }
4706a0f08674SEwan Crawford 
4707a0f08674SEwan Crawford     Stream *output_strm = nullptr;
4708a0f08674SEwan Crawford     StreamFile outfile_stream;
4709b9c1b51eSKate Stone     const FileSpec &outfile_spec =
4710b9c1b51eSKate Stone         m_options.m_outfile; // Dump allocation to file instead
4711b9c1b51eSKate Stone     if (outfile_spec) {
4712a0f08674SEwan Crawford       // Open output file
471350bc1ed2SJonas Devlieghere       std::string path = outfile_spec.GetPath();
471450bc1ed2SJonas Devlieghere       auto error = FileSystem::Instance().Open(
471550bc1ed2SJonas Devlieghere           outfile_stream.GetFile(), outfile_spec,
471650bc1ed2SJonas Devlieghere           File::eOpenOptionWrite | File::eOpenOptionCanCreate);
471750bc1ed2SJonas Devlieghere       if (error.Success()) {
4718a0f08674SEwan Crawford         output_strm = &outfile_stream;
471950bc1ed2SJonas Devlieghere         result.GetOutputStream().Printf("Results written to '%s'",
472050bc1ed2SJonas Devlieghere                                         path.c_str());
4721a0f08674SEwan Crawford         result.GetOutputStream().EOL();
4722b9c1b51eSKate Stone       } else {
472350bc1ed2SJonas Devlieghere         result.AppendErrorWithFormat("Couldn't open file '%s'", path.c_str());
4724a0f08674SEwan Crawford         result.SetStatus(eReturnStatusFailed);
4725a0f08674SEwan Crawford         return false;
4726a0f08674SEwan Crawford       }
4727b9c1b51eSKate Stone     } else
4728a0f08674SEwan Crawford       output_strm = &result.GetOutputStream();
4729a0f08674SEwan Crawford 
4730a0f08674SEwan Crawford     assert(output_strm != nullptr);
473180af0b9eSLuke Drummond     bool dumped =
4732b9c1b51eSKate Stone         runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4733a0f08674SEwan Crawford 
473480af0b9eSLuke Drummond     if (dumped)
4735a0f08674SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4736a0f08674SEwan Crawford     else
4737a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4738a0f08674SEwan Crawford 
4739a0f08674SEwan Crawford     return true;
4740a0f08674SEwan Crawford   }
4741a0f08674SEwan Crawford 
4742a0f08674SEwan Crawford private:
4743a0f08674SEwan Crawford   CommandOptions m_options;
4744a0f08674SEwan Crawford };
4745a0f08674SEwan Crawford 
47468fe53c49STatyana Krasnukha static constexpr OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
47471f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
47488fe53c49STatyana Krasnukha      {}, 0, eArgTypeIndex,
47491f0f5b5bSZachary Turner      "Only show details of a single allocation with specified id."}};
4750a0f08674SEwan Crawford 
4751b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationList
4752b9c1b51eSKate Stone     : public CommandObjectParsed {
475315f2bd95SEwan Crawford public:
4754b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationList(
4755b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4756b9c1b51eSKate Stone       : CommandObjectParsed(
4757b9c1b51eSKate Stone             interpreter, "renderscript allocation list",
4758b9c1b51eSKate Stone             "List renderscript allocations and their information.",
4759b9c1b51eSKate Stone             "renderscript allocation list",
4760b3f7f69dSAidan Dodds             eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4761b9c1b51eSKate Stone         m_options() {}
476215f2bd95SEwan Crawford 
4763222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4764222b937cSEugene Zelenko 
4765b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
476615f2bd95SEwan Crawford 
4767b9c1b51eSKate Stone   class CommandOptions : public Options {
476815f2bd95SEwan Crawford   public:
4769e1cfbc79STodd Fiala     CommandOptions() : Options(), m_id(0) {}
477015f2bd95SEwan Crawford 
4771222b937cSEugene Zelenko     ~CommandOptions() override = default;
477215f2bd95SEwan Crawford 
477397206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4774b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
477597206d57SZachary Turner       Status err;
477615f2bd95SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
477715f2bd95SEwan Crawford 
4778b9c1b51eSKate Stone       switch (short_option) {
4779b649b005SEwan Crawford       case 'i':
4780fe11483bSZachary Turner         if (option_arg.getAsInteger(0, m_id))
478180af0b9eSLuke Drummond           err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4782b9c1b51eSKate Stone                                        short_option);
478315f2bd95SEwan Crawford         break;
478480af0b9eSLuke Drummond       default:
478580af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
478680af0b9eSLuke Drummond         break;
478715f2bd95SEwan Crawford       }
478880af0b9eSLuke Drummond       return err;
478915f2bd95SEwan Crawford     }
479015f2bd95SEwan Crawford 
4791b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
479215f2bd95SEwan Crawford 
47931f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
479470602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
47951f0f5b5bSZachary Turner     }
479615f2bd95SEwan Crawford 
4797b649b005SEwan Crawford     uint32_t m_id;
479815f2bd95SEwan Crawford   };
479915f2bd95SEwan Crawford 
4800b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4801b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4802b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4803b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4804b9c1b51eSKate Stone     runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4805b9c1b51eSKate Stone                              m_options.m_id);
480615f2bd95SEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
480715f2bd95SEwan Crawford     return true;
480815f2bd95SEwan Crawford   }
480915f2bd95SEwan Crawford 
481015f2bd95SEwan Crawford private:
481115f2bd95SEwan Crawford   CommandOptions m_options;
481215f2bd95SEwan Crawford };
481315f2bd95SEwan Crawford 
4814b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationLoad
4815b9c1b51eSKate Stone     : public CommandObjectParsed {
481655232f09SEwan Crawford public:
4817b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationLoad(
4818b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4819b3f7f69dSAidan Dodds       : CommandObjectParsed(
4820b9c1b51eSKate Stone             interpreter, "renderscript allocation load",
4821b9c1b51eSKate Stone             "Loads renderscript allocation contents from a file.",
4822b9c1b51eSKate Stone             "renderscript allocation load <ID> <filename>",
4823b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
482455232f09SEwan Crawford 
4825222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
482655232f09SEwan Crawford 
4827b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
482855232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4829b9c1b51eSKate Stone     if (argc != 2) {
4830b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4831b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4832b3f7f69dSAidan Dodds           m_cmd_name.c_str());
483355232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
483455232f09SEwan Crawford       return false;
483555232f09SEwan Crawford     }
483655232f09SEwan Crawford 
4837b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4838b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4839b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
484055232f09SEwan Crawford 
484155232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
484280af0b9eSLuke Drummond     bool success = false;
4843b9c1b51eSKate Stone     const uint32_t id =
484480af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
484580af0b9eSLuke Drummond     if (!success) {
4846b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4847b9c1b51eSKate Stone                                    id_cstr);
484855232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
484955232f09SEwan Crawford       return false;
485055232f09SEwan Crawford     }
485155232f09SEwan Crawford 
485280af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
485380af0b9eSLuke Drummond     bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
485480af0b9eSLuke Drummond                                           m_exe_ctx.GetFramePtr());
485555232f09SEwan Crawford 
485680af0b9eSLuke Drummond     if (loaded)
485755232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
485855232f09SEwan Crawford     else
485955232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
486055232f09SEwan Crawford 
486155232f09SEwan Crawford     return true;
486255232f09SEwan Crawford   }
486355232f09SEwan Crawford };
486455232f09SEwan Crawford 
4865b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationSave
4866b9c1b51eSKate Stone     : public CommandObjectParsed {
486755232f09SEwan Crawford public:
4868b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationSave(
4869b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4870b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript allocation save",
4871b9c1b51eSKate Stone                             "Write renderscript allocation contents to a file.",
4872b9c1b51eSKate Stone                             "renderscript allocation save <ID> <filename>",
4873b9c1b51eSKate Stone                             eCommandRequiresProcess |
4874b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
487555232f09SEwan Crawford 
4876222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
487755232f09SEwan Crawford 
4878b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
487955232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4880b9c1b51eSKate Stone     if (argc != 2) {
4881b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4882b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4883b3f7f69dSAidan Dodds           m_cmd_name.c_str());
488455232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
488555232f09SEwan Crawford       return false;
488655232f09SEwan Crawford     }
488755232f09SEwan Crawford 
4888b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4889b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4890b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
489155232f09SEwan Crawford 
489255232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
489380af0b9eSLuke Drummond     bool success = false;
4894b9c1b51eSKate Stone     const uint32_t id =
489580af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
489680af0b9eSLuke Drummond     if (!success) {
4897b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4898b9c1b51eSKate Stone                                    id_cstr);
489955232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
490055232f09SEwan Crawford       return false;
490155232f09SEwan Crawford     }
490255232f09SEwan Crawford 
490380af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
490480af0b9eSLuke Drummond     bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
490580af0b9eSLuke Drummond                                          m_exe_ctx.GetFramePtr());
490655232f09SEwan Crawford 
490780af0b9eSLuke Drummond     if (saved)
490855232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
490955232f09SEwan Crawford     else
491055232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
491155232f09SEwan Crawford 
491255232f09SEwan Crawford     return true;
491355232f09SEwan Crawford   }
491455232f09SEwan Crawford };
491555232f09SEwan Crawford 
4916b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationRefresh
4917b9c1b51eSKate Stone     : public CommandObjectParsed {
49180d2bfcfbSEwan Crawford public:
4919b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationRefresh(
4920b9c1b51eSKate Stone       CommandInterpreter &interpreter)
49210d2bfcfbSEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4922b9c1b51eSKate Stone                             "Recomputes the details of all allocations.",
4923b9c1b51eSKate Stone                             "renderscript allocation refresh",
4924b9c1b51eSKate Stone                             eCommandRequiresProcess |
4925b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
49260d2bfcfbSEwan Crawford 
49270d2bfcfbSEwan Crawford   ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
49280d2bfcfbSEwan Crawford 
4929b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
49300d2bfcfbSEwan Crawford     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4931b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4932b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
49330d2bfcfbSEwan Crawford 
4934b9c1b51eSKate Stone     bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4935b9c1b51eSKate Stone                                                     m_exe_ctx.GetFramePtr());
49360d2bfcfbSEwan Crawford 
4937b9c1b51eSKate Stone     if (success) {
49380d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
49390d2bfcfbSEwan Crawford       return true;
4940b9c1b51eSKate Stone     } else {
49410d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusFailed);
49420d2bfcfbSEwan Crawford       return false;
49430d2bfcfbSEwan Crawford     }
49440d2bfcfbSEwan Crawford   }
49450d2bfcfbSEwan Crawford };
49460d2bfcfbSEwan Crawford 
4947b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocation
4948b9c1b51eSKate Stone     : public CommandObjectMultiword {
494915f2bd95SEwan Crawford public:
495015f2bd95SEwan Crawford   CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4951b9c1b51eSKate Stone       : CommandObjectMultiword(
4952b9c1b51eSKate Stone             interpreter, "renderscript allocation",
4953b9c1b51eSKate Stone             "Commands that deal with RenderScript allocations.", nullptr) {
4954b9c1b51eSKate Stone     LoadSubCommand(
4955b9c1b51eSKate Stone         "list",
4956b9c1b51eSKate Stone         CommandObjectSP(
4957b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4958b9c1b51eSKate Stone     LoadSubCommand(
4959b9c1b51eSKate Stone         "dump",
4960b9c1b51eSKate Stone         CommandObjectSP(
4961b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4962b9c1b51eSKate Stone     LoadSubCommand(
4963b9c1b51eSKate Stone         "save",
4964b9c1b51eSKate Stone         CommandObjectSP(
4965b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4966b9c1b51eSKate Stone     LoadSubCommand(
4967b9c1b51eSKate Stone         "load",
4968b9c1b51eSKate Stone         CommandObjectSP(
4969b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4970b9c1b51eSKate Stone     LoadSubCommand(
4971b9c1b51eSKate Stone         "refresh",
4972b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4973b9c1b51eSKate Stone             interpreter)));
497415f2bd95SEwan Crawford   }
497515f2bd95SEwan Crawford 
4976222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocation() override = default;
497715f2bd95SEwan Crawford };
497815f2bd95SEwan Crawford 
4979b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
49804640cde1SColin Riley public:
49814640cde1SColin Riley   CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4982b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript status",
4983b9c1b51eSKate Stone                             "Displays current RenderScript runtime status.",
4984b9c1b51eSKate Stone                             "renderscript status",
4985b9c1b51eSKate Stone                             eCommandRequiresProcess |
4986b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
49874640cde1SColin Riley 
4988222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeStatus() override = default;
49894640cde1SColin Riley 
4990b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
49914640cde1SColin Riley     RenderScriptRuntime *runtime =
4992b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4993b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
499497206d57SZachary Turner     runtime->DumpStatus(result.GetOutputStream());
49954640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
49964640cde1SColin Riley     return true;
49974640cde1SColin Riley   }
49984640cde1SColin Riley };
49994640cde1SColin Riley 
5000b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReduction
5001b3bbcb12SLuke Drummond     : public CommandObjectMultiword {
5002b3bbcb12SLuke Drummond public:
5003b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
5004b3bbcb12SLuke Drummond       : CommandObjectMultiword(interpreter, "renderscript reduction",
5005b3bbcb12SLuke Drummond                                "Commands that handle general reduction kernels",
5006b3bbcb12SLuke Drummond                                nullptr) {
5007b3bbcb12SLuke Drummond     LoadSubCommand(
5008b3bbcb12SLuke Drummond         "breakpoint",
5009b3bbcb12SLuke Drummond         CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
5010b3bbcb12SLuke Drummond             interpreter)));
5011b3bbcb12SLuke Drummond   }
5012b3bbcb12SLuke Drummond   ~CommandObjectRenderScriptRuntimeReduction() override = default;
5013b3bbcb12SLuke Drummond };
5014b3bbcb12SLuke Drummond 
5015b9c1b51eSKate Stone class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
50165ec532a9SColin Riley public:
50175ec532a9SColin Riley   CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
5018b9c1b51eSKate Stone       : CommandObjectMultiword(
5019b9c1b51eSKate Stone             interpreter, "renderscript",
5020b9c1b51eSKate Stone             "Commands for operating on the RenderScript runtime.",
5021b9c1b51eSKate Stone             "renderscript <subcommand> [<subcommand-options>]") {
5022b9c1b51eSKate Stone     LoadSubCommand(
5023b9c1b51eSKate Stone         "module", CommandObjectSP(
5024b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeModule(interpreter)));
5025b9c1b51eSKate Stone     LoadSubCommand(
5026b9c1b51eSKate Stone         "status", CommandObjectSP(
5027b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeStatus(interpreter)));
5028b9c1b51eSKate Stone     LoadSubCommand(
5029b9c1b51eSKate Stone         "kernel", CommandObjectSP(
5030b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeKernel(interpreter)));
5031b9c1b51eSKate Stone     LoadSubCommand("context",
5032b9c1b51eSKate Stone                    CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
5033b9c1b51eSKate Stone                        interpreter)));
5034b9c1b51eSKate Stone     LoadSubCommand(
5035b9c1b51eSKate Stone         "allocation",
5036b9c1b51eSKate Stone         CommandObjectSP(
5037b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
503821fed052SAidan Dodds     LoadSubCommand("scriptgroup",
503921fed052SAidan Dodds                    NewCommandObjectRenderScriptScriptGroup(interpreter));
5040b3bbcb12SLuke Drummond     LoadSubCommand(
5041b3bbcb12SLuke Drummond         "reduction",
5042b3bbcb12SLuke Drummond         CommandObjectSP(
5043b3bbcb12SLuke Drummond             new CommandObjectRenderScriptRuntimeReduction(interpreter)));
50445ec532a9SColin Riley   }
50455ec532a9SColin Riley 
5046222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntime() override = default;
50475ec532a9SColin Riley };
5048ef20b08fSColin Riley 
5049b9c1b51eSKate Stone void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
5050ef20b08fSColin Riley 
5051ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
5052b9c1b51eSKate Stone     : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
5053b9c1b51eSKate Stone       m_debuggerPresentFlagged(false), m_breakAllKernels(false),
5054b9c1b51eSKate Stone       m_ir_passes(nullptr) {
50554640cde1SColin Riley   ModulesDidLoad(process->GetTarget().GetImages());
5056ef20b08fSColin Riley }
50574640cde1SColin Riley 
5058b9c1b51eSKate Stone lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
5059b9c1b51eSKate Stone     lldb_private::CommandInterpreter &interpreter) {
50600a66e2f1SEnrico Granata   return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
50614640cde1SColin Riley }
50624640cde1SColin Riley 
506378f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
5064