15ec532a9SColin Riley //===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===//
25ec532a9SColin Riley //
35ec532a9SColin Riley //                     The LLVM Compiler Infrastructure
45ec532a9SColin Riley //
55ec532a9SColin Riley // This file is distributed under the University of Illinois Open Source
65ec532a9SColin Riley // License. See LICENSE.TXT for details.
75ec532a9SColin Riley //
85ec532a9SColin Riley //===----------------------------------------------------------------------===//
95ec532a9SColin Riley 
10222b937cSEugene Zelenko // C Includes
11222b937cSEugene Zelenko // C++ Includes
12222b937cSEugene Zelenko // Other libraries and framework includes
13b3bbcb12SLuke Drummond #include "llvm/ADT/StringSwitch.h"
147f193d69SLuke Drummond 
15222b937cSEugene Zelenko // Project includes
165ec532a9SColin Riley #include "RenderScriptRuntime.h"
17*21fed052SAidan Dodds #include "RenderScriptScriptGroup.h"
185ec532a9SColin Riley 
19b3f7f69dSAidan Dodds #include "lldb/Breakpoint/StoppointCallbackContext.h"
205ec532a9SColin Riley #include "lldb/Core/ConstString.h"
215ec532a9SColin Riley #include "lldb/Core/Debugger.h"
225ec532a9SColin Riley #include "lldb/Core/Error.h"
235ec532a9SColin Riley #include "lldb/Core/Log.h"
245ec532a9SColin Riley #include "lldb/Core/PluginManager.h"
25018f5a7eSEwan Crawford #include "lldb/Core/RegularExpression.h"
26b3f7f69dSAidan Dodds #include "lldb/Core/ValueObjectVariable.h"
278b244e21SEwan Crawford #include "lldb/DataFormatters/DumpValueObjectOptions.h"
28b3f7f69dSAidan Dodds #include "lldb/Expression/UserExpression.h"
29a0f08674SEwan Crawford #include "lldb/Host/StringConvert.h"
30b3f7f69dSAidan Dodds #include "lldb/Interpreter/Args.h"
31b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandInterpreter.h"
32b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandObjectMultiword.h"
33b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandReturnObject.h"
34b3f7f69dSAidan Dodds #include "lldb/Interpreter/Options.h"
35*21fed052SAidan Dodds #include "lldb/Symbol/Function.h"
365ec532a9SColin Riley #include "lldb/Symbol/Symbol.h"
374640cde1SColin Riley #include "lldb/Symbol/Type.h"
38b3f7f69dSAidan Dodds #include "lldb/Symbol/VariableList.h"
395ec532a9SColin Riley #include "lldb/Target/Process.h"
40b3f7f69dSAidan Dodds #include "lldb/Target/RegisterContext.h"
41*21fed052SAidan Dodds #include "lldb/Target/SectionLoadList.h"
425ec532a9SColin Riley #include "lldb/Target/Target.h"
43018f5a7eSEwan Crawford #include "lldb/Target/Thread.h"
445ec532a9SColin Riley 
455ec532a9SColin Riley using namespace lldb;
465ec532a9SColin Riley using namespace lldb_private;
4798156583SEwan Crawford using namespace lldb_renderscript;
485ec532a9SColin Riley 
4900f56eebSLuke Drummond #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")"
5000f56eebSLuke Drummond 
51b9c1b51eSKate Stone namespace {
5278f339d1SEwan Crawford 
5378f339d1SEwan Crawford // The empirical_type adds a basic level of validation to arbitrary data
5480af0b9eSLuke Drummond // allowing us to track if data has been discovered and stored or not. An
5580af0b9eSLuke Drummond // empirical_type will be marked as valid only if it has been explicitly
56b9c1b51eSKate Stone // assigned to.
57b9c1b51eSKate Stone template <typename type_t> class empirical_type {
5878f339d1SEwan Crawford public:
5978f339d1SEwan Crawford   // Ctor. Contents is invalid when constructed.
60b3f7f69dSAidan Dodds   empirical_type() : valid(false) {}
6178f339d1SEwan Crawford 
6278f339d1SEwan Crawford   // Return true and copy contents to out if valid, else return false.
63b9c1b51eSKate Stone   bool get(type_t &out) const {
6478f339d1SEwan Crawford     if (valid)
6578f339d1SEwan Crawford       out = data;
6678f339d1SEwan Crawford     return valid;
6778f339d1SEwan Crawford   }
6878f339d1SEwan Crawford 
6978f339d1SEwan Crawford   // Return a pointer to the contents or nullptr if it was not valid.
70b9c1b51eSKate Stone   const type_t *get() const { return valid ? &data : nullptr; }
7178f339d1SEwan Crawford 
7278f339d1SEwan Crawford   // Assign data explicitly.
73b9c1b51eSKate Stone   void set(const type_t in) {
7478f339d1SEwan Crawford     data = in;
7578f339d1SEwan Crawford     valid = true;
7678f339d1SEwan Crawford   }
7778f339d1SEwan Crawford 
7878f339d1SEwan Crawford   // Mark contents as invalid.
79b9c1b51eSKate Stone   void invalidate() { valid = false; }
8078f339d1SEwan Crawford 
8178f339d1SEwan Crawford   // Returns true if this type contains valid data.
82b9c1b51eSKate Stone   bool isValid() const { return valid; }
8378f339d1SEwan Crawford 
8478f339d1SEwan Crawford   // Assignment operator.
85b9c1b51eSKate Stone   empirical_type<type_t> &operator=(const type_t in) {
8678f339d1SEwan Crawford     set(in);
8778f339d1SEwan Crawford     return *this;
8878f339d1SEwan Crawford   }
8978f339d1SEwan Crawford 
9078f339d1SEwan Crawford   // Dereference operator returns contents.
9178f339d1SEwan Crawford   // Warning: Will assert if not valid so use only when you know data is valid.
92b9c1b51eSKate Stone   const type_t &operator*() const {
9378f339d1SEwan Crawford     assert(valid);
9478f339d1SEwan Crawford     return data;
9578f339d1SEwan Crawford   }
9678f339d1SEwan Crawford 
9778f339d1SEwan Crawford protected:
9878f339d1SEwan Crawford   bool valid;
9978f339d1SEwan Crawford   type_t data;
10078f339d1SEwan Crawford };
10178f339d1SEwan Crawford 
102b9c1b51eSKate Stone // ArgItem is used by the GetArgs() function when reading function arguments
103b9c1b51eSKate Stone // from the target.
104b9c1b51eSKate Stone struct ArgItem {
105b9c1b51eSKate Stone   enum { ePointer, eInt32, eInt64, eLong, eBool } type;
106f4786785SAidan Dodds 
107f4786785SAidan Dodds   uint64_t value;
108f4786785SAidan Dodds 
109f4786785SAidan Dodds   explicit operator uint64_t() const { return value; }
110f4786785SAidan Dodds };
111f4786785SAidan Dodds 
112b9c1b51eSKate Stone // Context structure to be passed into GetArgsXXX(), argument reading functions
113b9c1b51eSKate Stone // below.
114b9c1b51eSKate Stone struct GetArgsCtx {
115f4786785SAidan Dodds   RegisterContext *reg_ctx;
116f4786785SAidan Dodds   Process *process;
117f4786785SAidan Dodds };
118f4786785SAidan Dodds 
119b9c1b51eSKate Stone bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
120f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
121f4786785SAidan Dodds 
12280af0b9eSLuke Drummond   Error err;
12367dc3e15SAidan Dodds 
124f4786785SAidan Dodds   // get the current stack pointer
125f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
126f4786785SAidan Dodds 
127b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
128f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
129f4786785SAidan Dodds     // advance up the stack by one argument
130f4786785SAidan Dodds     sp += sizeof(uint32_t);
131f4786785SAidan Dodds     // get the argument type size
132f4786785SAidan Dodds     size_t arg_size = sizeof(uint32_t);
133f4786785SAidan Dodds     // read the argument from memory
134f4786785SAidan Dodds     arg.value = 0;
13580af0b9eSLuke Drummond     Error err;
136b9c1b51eSKate Stone     size_t read =
13780af0b9eSLuke Drummond         ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
13880af0b9eSLuke Drummond     if (read != arg_size || !err.Success()) {
139f4786785SAidan Dodds       if (log)
140b9c1b51eSKate Stone         log->Printf("%s - error reading argument: %" PRIu64 " '%s'",
14180af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString());
142f4786785SAidan Dodds       return false;
143f4786785SAidan Dodds     }
144f4786785SAidan Dodds   }
145f4786785SAidan Dodds   return true;
146f4786785SAidan Dodds }
147f4786785SAidan Dodds 
148b9c1b51eSKate Stone bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
149f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
150f4786785SAidan Dodds 
151f4786785SAidan Dodds   // number of arguments passed in registers
15280af0b9eSLuke Drummond   static const uint32_t args_in_reg = 6;
153f4786785SAidan Dodds   // register passing order
15480af0b9eSLuke Drummond   static const std::array<const char *, args_in_reg> reg_names{
155b9c1b51eSKate Stone       {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
156f4786785SAidan Dodds   // argument type to size mapping
1571ee07253SSaleem Abdulrasool   static const std::array<size_t, 5> arg_size{{
158f4786785SAidan Dodds       8, // ePointer,
159f4786785SAidan Dodds       4, // eInt32,
160f4786785SAidan Dodds       8, // eInt64,
161f4786785SAidan Dodds       8, // eLong,
162f4786785SAidan Dodds       4, // eBool,
1631ee07253SSaleem Abdulrasool   }};
164f4786785SAidan Dodds 
16580af0b9eSLuke Drummond   Error err;
16617e07c0aSAidan Dodds 
167f4786785SAidan Dodds   // get the current stack pointer
168f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
169f4786785SAidan Dodds   // step over the return address
170f4786785SAidan Dodds   sp += sizeof(uint64_t);
171f4786785SAidan Dodds 
172f4786785SAidan Dodds   // check the stack alignment was correct (16 byte aligned)
173b9c1b51eSKate Stone   if ((sp & 0xf) != 0x0) {
174f4786785SAidan Dodds     if (log)
175f4786785SAidan Dodds       log->Printf("%s - stack misaligned", __FUNCTION__);
176f4786785SAidan Dodds     return false;
177f4786785SAidan Dodds   }
178f4786785SAidan Dodds 
179f4786785SAidan Dodds   // find the start of arguments on the stack
180f4786785SAidan Dodds   uint64_t sp_offset = 0;
18180af0b9eSLuke Drummond   for (uint32_t i = args_in_reg; i < num_args; ++i) {
182f4786785SAidan Dodds     sp_offset += arg_size[arg_list[i].type];
183f4786785SAidan Dodds   }
184f4786785SAidan Dodds   // round up to multiple of 16
185f4786785SAidan Dodds   sp_offset = (sp_offset + 0xf) & 0xf;
186f4786785SAidan Dodds   sp += sp_offset;
187f4786785SAidan Dodds 
188b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
189f4786785SAidan Dodds     bool success = false;
190f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
191f4786785SAidan Dodds     // arguments passed in registers
19280af0b9eSLuke Drummond     if (i < args_in_reg) {
19380af0b9eSLuke Drummond       const RegisterInfo *reg =
19480af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoByName(reg_names[i]);
19580af0b9eSLuke Drummond       RegisterValue reg_val;
19680af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
19780af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
198f4786785SAidan Dodds     }
199f4786785SAidan Dodds     // arguments passed on the stack
200b9c1b51eSKate Stone     else {
201f4786785SAidan Dodds       // get the argument type size
202f4786785SAidan Dodds       const size_t size = arg_size[arg_list[i].type];
203f4786785SAidan Dodds       // read the argument from memory
204f4786785SAidan Dodds       arg.value = 0;
205b9c1b51eSKate Stone       // note: due to little endian layout reading 4 or 8 bytes will give the
206b9c1b51eSKate Stone       // correct value.
20780af0b9eSLuke Drummond       size_t read = ctx.process->ReadMemory(sp, &arg.value, size, err);
20880af0b9eSLuke Drummond       success = (err.Success() && read == size);
209f4786785SAidan Dodds       // advance past this argument
210f4786785SAidan Dodds       sp -= size;
211f4786785SAidan Dodds     }
212f4786785SAidan Dodds     // fail if we couldn't read this argument
213b9c1b51eSKate Stone     if (!success) {
214f4786785SAidan Dodds       if (log)
21517e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
21680af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
217f4786785SAidan Dodds       return false;
218f4786785SAidan Dodds     }
219f4786785SAidan Dodds   }
220f4786785SAidan Dodds   return true;
221f4786785SAidan Dodds }
222f4786785SAidan Dodds 
223b9c1b51eSKate Stone bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
224f4786785SAidan Dodds   // number of arguments passed in registers
22580af0b9eSLuke Drummond   static const uint32_t args_in_reg = 4;
226f4786785SAidan Dodds 
227f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
228f4786785SAidan Dodds 
22980af0b9eSLuke Drummond   Error err;
23017e07c0aSAidan Dodds 
231f4786785SAidan Dodds   // get the current stack pointer
232f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
233f4786785SAidan Dodds 
234b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
235f4786785SAidan Dodds     bool success = false;
236f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
237f4786785SAidan Dodds     // arguments passed in registers
23880af0b9eSLuke Drummond     if (i < args_in_reg) {
23980af0b9eSLuke Drummond       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
24080af0b9eSLuke Drummond       RegisterValue reg_val;
24180af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
24280af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt32(0, &success);
243f4786785SAidan Dodds     }
244f4786785SAidan Dodds     // arguments passed on the stack
245b9c1b51eSKate Stone     else {
246f4786785SAidan Dodds       // get the argument type size
247f4786785SAidan Dodds       const size_t arg_size = sizeof(uint32_t);
248f4786785SAidan Dodds       // clear all 64bits
249f4786785SAidan Dodds       arg.value = 0;
250f4786785SAidan Dodds       // read this argument from memory
251b9c1b51eSKate Stone       size_t bytes_read =
25280af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
25380af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
254f4786785SAidan Dodds       // advance the stack pointer
255f4786785SAidan Dodds       sp += sizeof(uint32_t);
256f4786785SAidan Dodds     }
257f4786785SAidan Dodds     // fail if we couldn't read this argument
258b9c1b51eSKate Stone     if (!success) {
259f4786785SAidan Dodds       if (log)
26017e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
26180af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
262f4786785SAidan Dodds       return false;
263f4786785SAidan Dodds     }
264f4786785SAidan Dodds   }
265f4786785SAidan Dodds   return true;
266f4786785SAidan Dodds }
267f4786785SAidan Dodds 
268b9c1b51eSKate Stone bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
269f4786785SAidan Dodds   // number of arguments passed in registers
27080af0b9eSLuke Drummond   static const uint32_t args_in_reg = 8;
271f4786785SAidan Dodds 
272f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
273f4786785SAidan Dodds 
274b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
275f4786785SAidan Dodds     bool success = false;
276f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
277f4786785SAidan Dodds     // arguments passed in registers
27880af0b9eSLuke Drummond     if (i < args_in_reg) {
27980af0b9eSLuke Drummond       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
28080af0b9eSLuke Drummond       RegisterValue reg_val;
28180af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
28280af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
283f4786785SAidan Dodds     }
284f4786785SAidan Dodds     // arguments passed on the stack
285b9c1b51eSKate Stone     else {
286f4786785SAidan Dodds       if (log)
287b9c1b51eSKate Stone         log->Printf("%s - reading arguments spilled to stack not implemented",
288b9c1b51eSKate Stone                     __FUNCTION__);
289f4786785SAidan Dodds     }
290f4786785SAidan Dodds     // fail if we couldn't read this argument
291b9c1b51eSKate Stone     if (!success) {
292f4786785SAidan Dodds       if (log)
293f4786785SAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__,
294f4786785SAidan Dodds                     uint64_t(i));
295f4786785SAidan Dodds       return false;
296f4786785SAidan Dodds     }
297f4786785SAidan Dodds   }
298f4786785SAidan Dodds   return true;
299f4786785SAidan Dodds }
300f4786785SAidan Dodds 
301b9c1b51eSKate Stone bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
302f4786785SAidan Dodds   // number of arguments passed in registers
30380af0b9eSLuke Drummond   static const uint32_t args_in_reg = 4;
304f4786785SAidan Dodds   // register file offset to first argument
30580af0b9eSLuke Drummond   static const uint32_t reg_offset = 4;
306f4786785SAidan Dodds 
307f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
308f4786785SAidan Dodds 
30980af0b9eSLuke Drummond   Error err;
31017e07c0aSAidan Dodds 
31117e07c0aSAidan Dodds   // find offset to arguments on the stack (+16 to skip over a0-a3 shadow 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 
35480af0b9eSLuke Drummond   Error 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) {
44600f56eebSLuke Drummond   // takes an argument of the form 'num[,num][,num]'.
44700f56eebSLuke Drummond   // Where 'coord_s' is a comma separated 1,2 or 3-dimensional coordinate
44800f56eebSLuke Drummond   // with the whitespace trimmed.
44900f56eebSLuke Drummond   // Missing coordinates are defaulted to zero.
45000f56eebSLuke Drummond   // If parsing of any elements fails the contents of &coord are undefined
45100f56eebSLuke Drummond   // and `false` is returned, `true` otherwise
45200f56eebSLuke Drummond 
45300f56eebSLuke Drummond   RegularExpression regex;
45400f56eebSLuke Drummond   RegularExpression::Match regex_match(3);
45500f56eebSLuke Drummond 
45600f56eebSLuke Drummond   bool matched = false;
45700f56eebSLuke Drummond   if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+),([0-9]+)$")) &&
45800f56eebSLuke Drummond       regex.Execute(coord_s, &regex_match))
45900f56eebSLuke Drummond     matched = true;
46000f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+)$")) &&
46100f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
46200f56eebSLuke Drummond     matched = true;
46300f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([0-9]+)$")) &&
46400f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
46500f56eebSLuke Drummond     matched = true;
46600f56eebSLuke Drummond 
46700f56eebSLuke Drummond   if (!matched)
46800f56eebSLuke Drummond     return false;
46900f56eebSLuke Drummond 
47000f56eebSLuke Drummond   auto get_index = [&](int idx, uint32_t &i) -> bool {
47100f56eebSLuke Drummond     std::string group;
47200f56eebSLuke Drummond     errno = 0;
47300f56eebSLuke Drummond     if (regex_match.GetMatchAtIndex(coord_s.str().c_str(), idx + 1, group))
47400f56eebSLuke Drummond       return !llvm::StringRef(group).getAsInteger<uint32_t>(10, i);
47500f56eebSLuke Drummond     return true;
47600f56eebSLuke Drummond   };
47700f56eebSLuke Drummond 
47800f56eebSLuke Drummond   return get_index(0, coord.x) && get_index(1, coord.y) &&
47900f56eebSLuke Drummond          get_index(2, coord.z);
48000f56eebSLuke Drummond }
481*21fed052SAidan Dodds 
482*21fed052SAidan Dodds bool SkipPrologue(lldb::ModuleSP &module, Address &addr) {
483*21fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
484*21fed052SAidan Dodds   SymbolContext sc;
485*21fed052SAidan Dodds   uint32_t resolved_flags =
486*21fed052SAidan Dodds       module->ResolveSymbolContextForAddress(addr, eSymbolContextFunction, sc);
487*21fed052SAidan Dodds   if (resolved_flags & eSymbolContextFunction) {
488*21fed052SAidan Dodds     if (sc.function) {
489*21fed052SAidan Dodds       const uint32_t offset = sc.function->GetPrologueByteSize();
490*21fed052SAidan Dodds       ConstString name = sc.GetFunctionName();
491*21fed052SAidan Dodds       if (offset)
492*21fed052SAidan Dodds         addr.Slide(offset);
493*21fed052SAidan Dodds       if (log)
494*21fed052SAidan Dodds         log->Printf("%s: Prologue offset for %s is %" PRIu32, __FUNCTION__,
495*21fed052SAidan Dodds                     name.AsCString(), offset);
496*21fed052SAidan Dodds     }
497*21fed052SAidan Dodds     return true;
498*21fed052SAidan Dodds   } else
499*21fed052SAidan Dodds     return false;
500*21fed052SAidan Dodds }
501222b937cSEugene Zelenko } // anonymous namespace
50278f339d1SEwan Crawford 
503b9c1b51eSKate Stone // The ScriptDetails class collects data associated with a single script
504b9c1b51eSKate Stone // instance.
505b9c1b51eSKate Stone struct RenderScriptRuntime::ScriptDetails {
506222b937cSEugene Zelenko   ~ScriptDetails() = default;
50778f339d1SEwan Crawford 
508b9c1b51eSKate Stone   enum ScriptType { eScript, eScriptC };
50978f339d1SEwan Crawford 
51078f339d1SEwan Crawford   // The derived type of the script.
51178f339d1SEwan Crawford   empirical_type<ScriptType> type;
51278f339d1SEwan Crawford   // The name of the original source file.
51380af0b9eSLuke Drummond   empirical_type<std::string> res_name;
51478f339d1SEwan Crawford   // Path to script .so file on the device.
51580af0b9eSLuke Drummond   empirical_type<std::string> shared_lib;
51678f339d1SEwan Crawford   // Directory where kernel objects are cached on device.
51780af0b9eSLuke Drummond   empirical_type<std::string> cache_dir;
51878f339d1SEwan Crawford   // Pointer to the context which owns this script.
51978f339d1SEwan Crawford   empirical_type<lldb::addr_t> context;
52078f339d1SEwan Crawford   // Pointer to the script object itself.
52178f339d1SEwan Crawford   empirical_type<lldb::addr_t> script;
52278f339d1SEwan Crawford };
52378f339d1SEwan Crawford 
52480af0b9eSLuke Drummond // This Element class represents the Element object in RS, defining the type
52580af0b9eSLuke Drummond // associated with an Allocation.
526b9c1b51eSKate Stone struct RenderScriptRuntime::Element {
52715f2bd95SEwan Crawford   // Taken from rsDefines.h
528b9c1b51eSKate Stone   enum DataKind {
52915f2bd95SEwan Crawford     RS_KIND_USER,
53015f2bd95SEwan Crawford     RS_KIND_PIXEL_L = 7,
53115f2bd95SEwan Crawford     RS_KIND_PIXEL_A,
53215f2bd95SEwan Crawford     RS_KIND_PIXEL_LA,
53315f2bd95SEwan Crawford     RS_KIND_PIXEL_RGB,
53415f2bd95SEwan Crawford     RS_KIND_PIXEL_RGBA,
53515f2bd95SEwan Crawford     RS_KIND_PIXEL_DEPTH,
53615f2bd95SEwan Crawford     RS_KIND_PIXEL_YUV,
53715f2bd95SEwan Crawford     RS_KIND_INVALID = 100
53815f2bd95SEwan Crawford   };
53978f339d1SEwan Crawford 
54015f2bd95SEwan Crawford   // Taken from rsDefines.h
541b9c1b51eSKate Stone   enum DataType {
54215f2bd95SEwan Crawford     RS_TYPE_NONE = 0,
54315f2bd95SEwan Crawford     RS_TYPE_FLOAT_16,
54415f2bd95SEwan Crawford     RS_TYPE_FLOAT_32,
54515f2bd95SEwan Crawford     RS_TYPE_FLOAT_64,
54615f2bd95SEwan Crawford     RS_TYPE_SIGNED_8,
54715f2bd95SEwan Crawford     RS_TYPE_SIGNED_16,
54815f2bd95SEwan Crawford     RS_TYPE_SIGNED_32,
54915f2bd95SEwan Crawford     RS_TYPE_SIGNED_64,
55015f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_8,
55115f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_16,
55215f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_32,
55315f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_64,
5542e920715SEwan Crawford     RS_TYPE_BOOLEAN,
5552e920715SEwan Crawford 
5562e920715SEwan Crawford     RS_TYPE_UNSIGNED_5_6_5,
5572e920715SEwan Crawford     RS_TYPE_UNSIGNED_5_5_5_1,
5582e920715SEwan Crawford     RS_TYPE_UNSIGNED_4_4_4_4,
5592e920715SEwan Crawford 
5602e920715SEwan Crawford     RS_TYPE_MATRIX_4X4,
5612e920715SEwan Crawford     RS_TYPE_MATRIX_3X3,
5622e920715SEwan Crawford     RS_TYPE_MATRIX_2X2,
5632e920715SEwan Crawford 
5642e920715SEwan Crawford     RS_TYPE_ELEMENT = 1000,
5652e920715SEwan Crawford     RS_TYPE_TYPE,
5662e920715SEwan Crawford     RS_TYPE_ALLOCATION,
5672e920715SEwan Crawford     RS_TYPE_SAMPLER,
5682e920715SEwan Crawford     RS_TYPE_SCRIPT,
5692e920715SEwan Crawford     RS_TYPE_MESH,
5702e920715SEwan Crawford     RS_TYPE_PROGRAM_FRAGMENT,
5712e920715SEwan Crawford     RS_TYPE_PROGRAM_VERTEX,
5722e920715SEwan Crawford     RS_TYPE_PROGRAM_RASTER,
5732e920715SEwan Crawford     RS_TYPE_PROGRAM_STORE,
5742e920715SEwan Crawford     RS_TYPE_FONT,
5752e920715SEwan Crawford 
5762e920715SEwan Crawford     RS_TYPE_INVALID = 10000
57778f339d1SEwan Crawford   };
57878f339d1SEwan Crawford 
5798b244e21SEwan Crawford   std::vector<Element> children; // Child Element fields for structs
580b9c1b51eSKate Stone   empirical_type<lldb::addr_t>
581b9c1b51eSKate Stone       element_ptr; // Pointer to the RS Element of the Type
582b9c1b51eSKate Stone   empirical_type<DataType>
583b9c1b51eSKate Stone       type; // Type of each data pointer stored by the allocation
584b9c1b51eSKate Stone   empirical_type<DataKind>
585b9c1b51eSKate Stone       type_kind; // Defines pixel type if Allocation is created from an image
586b9c1b51eSKate Stone   empirical_type<uint32_t>
587b9c1b51eSKate Stone       type_vec_size; // Vector size of each data point, e.g '4' for uchar4
5888b244e21SEwan Crawford   empirical_type<uint32_t> field_count; // Number of Subelements
5898b244e21SEwan Crawford   empirical_type<uint32_t> datum_size;  // Size of a single Element with padding
5908b244e21SEwan Crawford   empirical_type<uint32_t> padding;     // Number of padding bytes
591b9c1b51eSKate Stone   empirical_type<uint32_t>
592b9c1b51eSKate Stone       array_size;        // Number of items in array, only needed for strucrs
5938b244e21SEwan Crawford   ConstString type_name; // Name of type, only needed for structs
5948b244e21SEwan Crawford 
595b3f7f69dSAidan Dodds   static const ConstString &
596b3f7f69dSAidan Dodds   GetFallbackStructName(); // Print this as the type name of a struct Element
5978b244e21SEwan Crawford                            // If we can't resolve the actual struct name
5988b59062aSEwan Crawford 
59980af0b9eSLuke Drummond   bool ShouldRefresh() const {
6008b59062aSEwan Crawford     const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
601b9c1b51eSKate Stone     const bool valid_type =
602b9c1b51eSKate Stone         type.isValid() && type_vec_size.isValid() && type_kind.isValid();
6038b59062aSEwan Crawford     return !valid_ptr || !valid_type || !datum_size.isValid();
6048b59062aSEwan Crawford   }
6058b244e21SEwan Crawford };
6068b244e21SEwan Crawford 
6078b244e21SEwan Crawford // This AllocationDetails class collects data associated with a single
6088b244e21SEwan Crawford // allocation instance.
609b9c1b51eSKate Stone struct RenderScriptRuntime::AllocationDetails {
610b9c1b51eSKate Stone   struct Dimension {
61115f2bd95SEwan Crawford     uint32_t dim_1;
61215f2bd95SEwan Crawford     uint32_t dim_2;
61315f2bd95SEwan Crawford     uint32_t dim_3;
61480af0b9eSLuke Drummond     uint32_t cube_map;
61515f2bd95SEwan Crawford 
616b9c1b51eSKate Stone     Dimension() {
61715f2bd95SEwan Crawford       dim_1 = 0;
61815f2bd95SEwan Crawford       dim_2 = 0;
61915f2bd95SEwan Crawford       dim_3 = 0;
62080af0b9eSLuke Drummond       cube_map = 0;
62115f2bd95SEwan Crawford     }
62278f339d1SEwan Crawford   };
62378f339d1SEwan Crawford 
624b9c1b51eSKate Stone   // The FileHeader struct specifies the header we use for writing allocations
62580af0b9eSLuke Drummond   // to a binary file. Our format begins with the ASCII characters "RSAD",
62680af0b9eSLuke Drummond   // identifying the file as an allocation dump. Member variables dims and
62780af0b9eSLuke Drummond   // hdr_size are then written consecutively, immediately followed by an
62880af0b9eSLuke Drummond   // instance of the ElementHeader struct. Because Elements can contain
62980af0b9eSLuke Drummond   // subelements, there may be more than one instance of the ElementHeader
63080af0b9eSLuke Drummond   // struct. With this first instance being the root element, and the other
63180af0b9eSLuke Drummond   // instances being the root's descendants. To identify which instances are an
63280af0b9eSLuke Drummond   // ElementHeader's children, each struct is immediately followed by a sequence
63380af0b9eSLuke Drummond   // of consecutive offsets to the start of its child structs. These 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 
65215f2bd95SEwan Crawford   // Maps Allocation DataType enum and vector size to printable strings
65315f2bd95SEwan Crawford   // using 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
843b3bbcb12SLuke Drummond   // reduce names don't actually exist as
844b3bbcb12SLuke Drummond   // symbols in a module. They are only identifiable by parsing the .rs.info
845b3bbcb12SLuke Drummond   // packet, or finding the expand symbol. We
846b3bbcb12SLuke Drummond   // therefore need access to the list of parsed rs modules to properly resolve
847b3bbcb12SLuke Drummond   // reduction names.
848b3bbcb12SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
849b3bbcb12SLuke Drummond   ModuleSP module = context.module_sp;
850b3bbcb12SLuke Drummond 
851b3bbcb12SLuke Drummond   if (!module || !IsRenderScriptScriptModule(module))
852b3bbcb12SLuke Drummond     return Searcher::eCallbackReturnContinue;
853b3bbcb12SLuke Drummond 
854b3bbcb12SLuke Drummond   if (!m_rsmodules)
855b3bbcb12SLuke Drummond     return Searcher::eCallbackReturnContinue;
856b3bbcb12SLuke Drummond 
857b3bbcb12SLuke Drummond   for (const auto &module_desc : *m_rsmodules) {
858b3bbcb12SLuke Drummond     if (module_desc->m_module != module)
859b3bbcb12SLuke Drummond       continue;
860b3bbcb12SLuke Drummond 
861b3bbcb12SLuke Drummond     for (const auto &reduction : module_desc->m_reductions) {
862b3bbcb12SLuke Drummond       if (reduction.m_reduce_name != m_reduce_name)
863b3bbcb12SLuke Drummond         continue;
864b3bbcb12SLuke Drummond 
865b3bbcb12SLuke Drummond       std::array<std::pair<ConstString, int>, 5> funcs{
866b3bbcb12SLuke Drummond           {{reduction.m_init_name, eKernelTypeInit},
867b3bbcb12SLuke Drummond            {reduction.m_accum_name, eKernelTypeAccum},
868b3bbcb12SLuke Drummond            {reduction.m_comb_name, eKernelTypeComb},
869b3bbcb12SLuke Drummond            {reduction.m_outc_name, eKernelTypeOutC},
870b3bbcb12SLuke Drummond            {reduction.m_halter_name, eKernelTypeHalter}}};
871b3bbcb12SLuke Drummond 
872b3bbcb12SLuke Drummond       for (const auto &kernel : funcs) {
873b3bbcb12SLuke Drummond         // Skip constituent functions that don't match our spec
874b3bbcb12SLuke Drummond         if (!(m_kernel_types & kernel.second))
875b3bbcb12SLuke Drummond           continue;
876b3bbcb12SLuke Drummond 
877b3bbcb12SLuke Drummond         const auto kernel_name = kernel.first;
878b3bbcb12SLuke Drummond         const auto symbol = module->FindFirstSymbolWithNameAndType(
879b3bbcb12SLuke Drummond             kernel_name, eSymbolTypeCode);
880b3bbcb12SLuke Drummond         if (!symbol)
881b3bbcb12SLuke Drummond           continue;
882b3bbcb12SLuke Drummond 
883b3bbcb12SLuke Drummond         auto address = symbol->GetAddress();
884b3bbcb12SLuke Drummond         if (filter.AddressPasses(address)) {
885b3bbcb12SLuke Drummond           bool new_bp;
886b3bbcb12SLuke Drummond           m_breakpoint->AddLocation(address, &new_bp);
887b3bbcb12SLuke Drummond           if (log)
888b3bbcb12SLuke Drummond             log->Printf("%s: %s reduction breakpoint on %s in %s", __FUNCTION__,
889b3bbcb12SLuke Drummond                         new_bp ? "new" : "existing", kernel_name.GetCString(),
890b3bbcb12SLuke Drummond                         address.GetModule()->GetFileSpec().GetCString());
891b3bbcb12SLuke Drummond         }
892b3bbcb12SLuke Drummond       }
893b3bbcb12SLuke Drummond     }
894b3bbcb12SLuke Drummond   }
895b3bbcb12SLuke Drummond   return eCallbackReturnContinue;
896b3bbcb12SLuke Drummond }
897b3bbcb12SLuke Drummond 
898*21fed052SAidan Dodds Searcher::CallbackReturn RSScriptGroupBreakpointResolver::SearchCallback(
899*21fed052SAidan Dodds     SearchFilter &filter, SymbolContext &context, Address *addr,
900*21fed052SAidan Dodds     bool containing) {
901*21fed052SAidan Dodds 
902*21fed052SAidan Dodds   if (!m_breakpoint)
903*21fed052SAidan Dodds     return eCallbackReturnContinue;
904*21fed052SAidan Dodds 
905*21fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
906*21fed052SAidan Dodds   ModuleSP &module = context.module_sp;
907*21fed052SAidan Dodds 
908*21fed052SAidan Dodds   if (!module || !IsRenderScriptScriptModule(module))
909*21fed052SAidan Dodds     return Searcher::eCallbackReturnContinue;
910*21fed052SAidan Dodds 
911*21fed052SAidan Dodds   std::vector<std::string> names;
912*21fed052SAidan Dodds   m_breakpoint->GetNames(names);
913*21fed052SAidan Dodds   if (names.empty())
914*21fed052SAidan Dodds     return eCallbackReturnContinue;
915*21fed052SAidan Dodds 
916*21fed052SAidan Dodds   for (auto &name : names) {
917*21fed052SAidan Dodds     const RSScriptGroupDescriptorSP sg = FindScriptGroup(ConstString(name));
918*21fed052SAidan Dodds     if (!sg) {
919*21fed052SAidan Dodds       if (log)
920*21fed052SAidan Dodds         log->Printf("%s: could not find script group for %s", __FUNCTION__,
921*21fed052SAidan Dodds                     name.c_str());
922*21fed052SAidan Dodds       continue;
923*21fed052SAidan Dodds     }
924*21fed052SAidan Dodds 
925*21fed052SAidan Dodds     if (log)
926*21fed052SAidan Dodds       log->Printf("%s: Found ScriptGroup for %s", __FUNCTION__, name.c_str());
927*21fed052SAidan Dodds 
928*21fed052SAidan Dodds     for (const RSScriptGroupDescriptor::Kernel &k : sg->m_kernels) {
929*21fed052SAidan Dodds       if (log) {
930*21fed052SAidan Dodds         log->Printf("%s: Adding breakpoint for %s", __FUNCTION__,
931*21fed052SAidan Dodds                     k.m_name.AsCString());
932*21fed052SAidan Dodds         log->Printf("%s: Kernel address 0x%" PRIx64, __FUNCTION__, k.m_addr);
933*21fed052SAidan Dodds       }
934*21fed052SAidan Dodds 
935*21fed052SAidan Dodds       const lldb_private::Symbol *sym =
936*21fed052SAidan Dodds           module->FindFirstSymbolWithNameAndType(k.m_name, eSymbolTypeCode);
937*21fed052SAidan Dodds       if (!sym) {
938*21fed052SAidan Dodds         if (log)
939*21fed052SAidan Dodds           log->Printf("%s: Unable to find symbol for %s", __FUNCTION__,
940*21fed052SAidan Dodds                       k.m_name.AsCString());
941*21fed052SAidan Dodds         continue;
942*21fed052SAidan Dodds       }
943*21fed052SAidan Dodds 
944*21fed052SAidan Dodds       if (log) {
945*21fed052SAidan Dodds         log->Printf("%s: Found symbol name is %s", __FUNCTION__,
946*21fed052SAidan Dodds                     sym->GetName().AsCString());
947*21fed052SAidan Dodds       }
948*21fed052SAidan Dodds 
949*21fed052SAidan Dodds       auto address = sym->GetAddress();
950*21fed052SAidan Dodds       if (!SkipPrologue(module, address)) {
951*21fed052SAidan Dodds         if (log)
952*21fed052SAidan Dodds           log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
953*21fed052SAidan Dodds       }
954*21fed052SAidan Dodds 
955*21fed052SAidan Dodds       bool new_bp;
956*21fed052SAidan Dodds       m_breakpoint->AddLocation(address, &new_bp);
957*21fed052SAidan Dodds 
958*21fed052SAidan Dodds       if (log)
959*21fed052SAidan Dodds         log->Printf("%s: Placed %sbreakpoint on %s", __FUNCTION__,
960*21fed052SAidan Dodds                     new_bp ? "new " : "", k.m_name.AsCString());
961*21fed052SAidan Dodds 
962*21fed052SAidan Dodds       // exit after placing the first breakpoint if we do not intend to stop
963*21fed052SAidan Dodds       // on all kernels making up this script group
964*21fed052SAidan Dodds       if (!m_stop_on_all)
965*21fed052SAidan Dodds         break;
966*21fed052SAidan Dodds     }
967*21fed052SAidan Dodds   }
968*21fed052SAidan Dodds 
969*21fed052SAidan Dodds   return eCallbackReturnContinue;
970*21fed052SAidan Dodds }
971*21fed052SAidan Dodds 
972b9c1b51eSKate Stone void RenderScriptRuntime::Initialize() {
973b9c1b51eSKate Stone   PluginManager::RegisterPlugin(GetPluginNameStatic(),
974b9c1b51eSKate Stone                                 "RenderScript language support", CreateInstance,
975b3f7f69dSAidan Dodds                                 GetCommandObject);
9765ec532a9SColin Riley }
9775ec532a9SColin Riley 
978b9c1b51eSKate Stone void RenderScriptRuntime::Terminate() {
9795ec532a9SColin Riley   PluginManager::UnregisterPlugin(CreateInstance);
9805ec532a9SColin Riley }
9815ec532a9SColin Riley 
982b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginNameStatic() {
98380af0b9eSLuke Drummond   static ConstString plugin_name("renderscript");
98480af0b9eSLuke Drummond   return plugin_name;
9855ec532a9SColin Riley }
9865ec532a9SColin Riley 
987ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
988b9c1b51eSKate Stone RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
989b9c1b51eSKate Stone   if (module_sp) {
990b3bbcb12SLuke Drummond     if (IsRenderScriptScriptModule(module_sp))
991ef20b08fSColin Riley       return eModuleKindKernelObj;
9924640cde1SColin Riley 
9934640cde1SColin Riley     // Is this the main RS runtime library
9944640cde1SColin Riley     const ConstString rs_lib("libRS.so");
995b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
9964640cde1SColin Riley       return eModuleKindLibRS;
9974640cde1SColin Riley     }
9984640cde1SColin Riley 
9994640cde1SColin Riley     const ConstString rs_driverlib("libRSDriver.so");
1000b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
10014640cde1SColin Riley       return eModuleKindDriver;
10024640cde1SColin Riley     }
10034640cde1SColin Riley 
100415f2bd95SEwan Crawford     const ConstString rs_cpureflib("libRSCpuRef.so");
1005b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
10064640cde1SColin Riley       return eModuleKindImpl;
10074640cde1SColin Riley     }
1008ef20b08fSColin Riley   }
1009ef20b08fSColin Riley   return eModuleKindIgnored;
1010ef20b08fSColin Riley }
1011ef20b08fSColin Riley 
1012b9c1b51eSKate Stone bool RenderScriptRuntime::IsRenderScriptModule(
1013b9c1b51eSKate Stone     const lldb::ModuleSP &module_sp) {
1014ef20b08fSColin Riley   return GetModuleKind(module_sp) != eModuleKindIgnored;
1015ef20b08fSColin Riley }
1016ef20b08fSColin Riley 
1017b9c1b51eSKate Stone void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
1018bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1019ef20b08fSColin Riley 
1020ef20b08fSColin Riley   size_t num_modules = module_list.GetSize();
1021b9c1b51eSKate Stone   for (size_t i = 0; i < num_modules; i++) {
1022ef20b08fSColin Riley     auto mod = module_list.GetModuleAtIndex(i);
1023b9c1b51eSKate Stone     if (IsRenderScriptModule(mod)) {
1024ef20b08fSColin Riley       LoadModule(mod);
1025ef20b08fSColin Riley     }
1026ef20b08fSColin Riley   }
1027ef20b08fSColin Riley }
1028ef20b08fSColin Riley 
10295ec532a9SColin Riley //------------------------------------------------------------------
10305ec532a9SColin Riley // PluginInterface protocol
10315ec532a9SColin Riley //------------------------------------------------------------------
1032b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginName() {
10335ec532a9SColin Riley   return GetPluginNameStatic();
10345ec532a9SColin Riley }
10355ec532a9SColin Riley 
1036b9c1b51eSKate Stone uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; }
10375ec532a9SColin Riley 
1038b9c1b51eSKate Stone bool RenderScriptRuntime::IsVTableName(const char *name) { return false; }
10395ec532a9SColin Riley 
1040b9c1b51eSKate Stone bool RenderScriptRuntime::GetDynamicTypeAndAddress(
1041b9c1b51eSKate Stone     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
10425f57b6eeSEnrico Granata     TypeAndOrName &class_type_or_name, Address &address,
1043b9c1b51eSKate Stone     Value::ValueType &value_type) {
10445ec532a9SColin Riley   return false;
10455ec532a9SColin Riley }
10465ec532a9SColin Riley 
1047c74275bcSEnrico Granata TypeAndOrName
1048b9c1b51eSKate Stone RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
1049b9c1b51eSKate Stone                                       ValueObject &static_value) {
1050c74275bcSEnrico Granata   return type_and_or_name;
1051c74275bcSEnrico Granata }
1052c74275bcSEnrico Granata 
1053b9c1b51eSKate Stone bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
10545ec532a9SColin Riley   return false;
10555ec532a9SColin Riley }
10565ec532a9SColin Riley 
10575ec532a9SColin Riley lldb::BreakpointResolverSP
105880af0b9eSLuke Drummond RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bp, bool catch_bp,
1059b9c1b51eSKate Stone                                              bool throw_bp) {
10605ec532a9SColin Riley   BreakpointResolverSP resolver_sp;
10615ec532a9SColin Riley   return resolver_sp;
10625ec532a9SColin Riley }
10635ec532a9SColin Riley 
1064b9c1b51eSKate Stone const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
1065b9c1b51eSKate Stone     {
10664640cde1SColin Riley         // rsdScript
1067b9c1b51eSKate Stone         {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
1068b9c1b51eSKate Stone                           "NS0_7ScriptCEPKcS7_PKhjj",
1069b9c1b51eSKate Stone          "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
1070b9c1b51eSKate Stone          "7ScriptCEPKcS7_PKhmj",
1071b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1072b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInit},
1073b9c1b51eSKate Stone         {"rsdScriptInvokeForEachMulti",
1074b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1075b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
1076b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1077b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
1078b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1079b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
1080b9c1b51eSKate Stone         {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
1081b9c1b51eSKate Stone                                   "script7ContextEPKNS0_6ScriptEjPvj",
1082b9c1b51eSKate Stone          "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
1083b9c1b51eSKate Stone          "6ScriptEjPvm",
1084b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1085b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
10864640cde1SColin Riley 
10874640cde1SColin Riley         // rsdAllocation
1088b9c1b51eSKate Stone         {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
1089b9c1b51eSKate Stone                               "ontextEPNS0_10AllocationEb",
1090b9c1b51eSKate Stone          "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
1091b9c1b51eSKate Stone          "10AllocationEb",
1092b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1093b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
1094b9c1b51eSKate Stone         {"rsdAllocationRead2D",
1095b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1096b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1097b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1098b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1099b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1100b9c1b51eSKate Stone         {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1101b9c1b51eSKate Stone                                  "ript7ContextEPNS0_10AllocationE",
1102b9c1b51eSKate Stone          "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1103b9c1b51eSKate Stone          "10AllocationE",
1104b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1105b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
1106*21fed052SAidan Dodds 
1107*21fed052SAidan Dodds         // renderscript script groups
1108*21fed052SAidan Dodds         {"rsdDebugHintScriptGroup2", "_ZN7android12renderscript21debugHintScrip"
1109*21fed052SAidan Dodds                                      "tGroup2EPKcjPKPFvPK24RsExpandKernelDriver"
1110*21fed052SAidan Dodds                                      "InfojjjEj",
1111*21fed052SAidan Dodds          "_ZN7android12renderscript21debugHintScriptGroup2EPKcjPKPFvPK24RsExpan"
1112*21fed052SAidan Dodds          "dKernelDriverInfojjjEj",
1113*21fed052SAidan Dodds          0, RenderScriptRuntime::eModuleKindImpl,
1114*21fed052SAidan Dodds          &lldb_private::RenderScriptRuntime::CaptureDebugHintScriptGroup2}};
11154640cde1SColin Riley 
1116b9c1b51eSKate Stone const size_t RenderScriptRuntime::s_runtimeHookCount =
1117b9c1b51eSKate Stone     sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
11184640cde1SColin Riley 
1119b9c1b51eSKate Stone bool RenderScriptRuntime::HookCallback(void *baton,
1120b9c1b51eSKate Stone                                        StoppointCallbackContext *ctx,
1121b9c1b51eSKate Stone                                        lldb::user_id_t break_id,
1122b9c1b51eSKate Stone                                        lldb::user_id_t break_loc_id) {
112380af0b9eSLuke Drummond   RuntimeHook *hook = (RuntimeHook *)baton;
112480af0b9eSLuke Drummond   ExecutionContext exe_ctx(ctx->exe_ctx_ref);
11254640cde1SColin Riley 
1126b3f7f69dSAidan Dodds   RenderScriptRuntime *lang_rt =
112780af0b9eSLuke Drummond       (RenderScriptRuntime *)exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1128b9c1b51eSKate Stone           eLanguageTypeExtRenderScript);
11294640cde1SColin Riley 
113080af0b9eSLuke Drummond   lang_rt->HookCallback(hook, exe_ctx);
11314640cde1SColin Riley 
11324640cde1SColin Riley   return false;
11334640cde1SColin Riley }
11344640cde1SColin Riley 
113580af0b9eSLuke Drummond void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
113680af0b9eSLuke Drummond                                        ExecutionContext &exe_ctx) {
11374640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11384640cde1SColin Riley 
11394640cde1SColin Riley   if (log)
114080af0b9eSLuke Drummond     log->Printf("%s - '%s'", __FUNCTION__, hook->defn->name);
11414640cde1SColin Riley 
114280af0b9eSLuke Drummond   if (hook->defn->grabber) {
114380af0b9eSLuke Drummond     (this->*(hook->defn->grabber))(hook, exe_ctx);
11444640cde1SColin Riley   }
11454640cde1SColin Riley }
11464640cde1SColin Riley 
1147*21fed052SAidan Dodds void RenderScriptRuntime::CaptureDebugHintScriptGroup2(
1148*21fed052SAidan Dodds     RuntimeHook *hook_info, ExecutionContext &context) {
1149*21fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1150*21fed052SAidan Dodds 
1151*21fed052SAidan Dodds   enum {
1152*21fed052SAidan Dodds     eGroupName = 0,
1153*21fed052SAidan Dodds     eGroupNameSize,
1154*21fed052SAidan Dodds     eKernel,
1155*21fed052SAidan Dodds     eKernelCount,
1156*21fed052SAidan Dodds   };
1157*21fed052SAidan Dodds 
1158*21fed052SAidan Dodds   std::array<ArgItem, 4> args{{
1159*21fed052SAidan Dodds       {ArgItem::ePointer, 0}, // const char         *groupName
1160*21fed052SAidan Dodds       {ArgItem::eInt32, 0},   // const uint32_t      groupNameSize
1161*21fed052SAidan Dodds       {ArgItem::ePointer, 0}, // const ExpandFuncTy *kernel
1162*21fed052SAidan Dodds       {ArgItem::eInt32, 0},   // const uint32_t      kernelCount
1163*21fed052SAidan Dodds   }};
1164*21fed052SAidan Dodds 
1165*21fed052SAidan Dodds   if (!GetArgs(context, args.data(), args.size())) {
1166*21fed052SAidan Dodds     if (log)
1167*21fed052SAidan Dodds       log->Printf("%s - Error while reading the function parameters",
1168*21fed052SAidan Dodds                   __FUNCTION__);
1169*21fed052SAidan Dodds     return;
1170*21fed052SAidan Dodds   } else if (log) {
1171*21fed052SAidan Dodds     log->Printf("%s - groupName    : 0x%" PRIx64, __FUNCTION__,
1172*21fed052SAidan Dodds                 addr_t(args[eGroupName]));
1173*21fed052SAidan Dodds     log->Printf("%s - groupNameSize: %" PRIu64, __FUNCTION__,
1174*21fed052SAidan Dodds                 uint64_t(args[eGroupNameSize]));
1175*21fed052SAidan Dodds     log->Printf("%s - kernel       : 0x%" PRIx64, __FUNCTION__,
1176*21fed052SAidan Dodds                 addr_t(args[eKernel]));
1177*21fed052SAidan Dodds     log->Printf("%s - kernelCount  : %" PRIu64, __FUNCTION__,
1178*21fed052SAidan Dodds                 uint64_t(args[eKernelCount]));
1179*21fed052SAidan Dodds   }
1180*21fed052SAidan Dodds 
1181*21fed052SAidan Dodds   // parse script group name
1182*21fed052SAidan Dodds   ConstString group_name;
1183*21fed052SAidan Dodds   {
1184*21fed052SAidan Dodds     Error err;
1185*21fed052SAidan Dodds     const uint64_t len = uint64_t(args[eGroupNameSize]);
1186*21fed052SAidan Dodds     std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]);
1187*21fed052SAidan Dodds     m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err);
1188*21fed052SAidan Dodds     buffer.get()[len] = '\0';
1189*21fed052SAidan Dodds     if (!err.Success()) {
1190*21fed052SAidan Dodds       if (log)
1191*21fed052SAidan Dodds         log->Printf("Error reading scriptgroup name from target");
1192*21fed052SAidan Dodds       return;
1193*21fed052SAidan Dodds     } else {
1194*21fed052SAidan Dodds       if (log)
1195*21fed052SAidan Dodds         log->Printf("Extracted scriptgroup name %s", buffer.get());
1196*21fed052SAidan Dodds     }
1197*21fed052SAidan Dodds     // write back the script group name
1198*21fed052SAidan Dodds     group_name.SetCString(buffer.get());
1199*21fed052SAidan Dodds   }
1200*21fed052SAidan Dodds 
1201*21fed052SAidan Dodds   // create or access existing script group
1202*21fed052SAidan Dodds   RSScriptGroupDescriptorSP group;
1203*21fed052SAidan Dodds   {
1204*21fed052SAidan Dodds     // search for existing script group
1205*21fed052SAidan Dodds     for (auto sg : m_scriptGroups) {
1206*21fed052SAidan Dodds       if (sg->m_name == group_name) {
1207*21fed052SAidan Dodds         group = sg;
1208*21fed052SAidan Dodds         break;
1209*21fed052SAidan Dodds       }
1210*21fed052SAidan Dodds     }
1211*21fed052SAidan Dodds     if (!group) {
1212*21fed052SAidan Dodds       group.reset(new RSScriptGroupDescriptor);
1213*21fed052SAidan Dodds       group->m_name = group_name;
1214*21fed052SAidan Dodds       m_scriptGroups.push_back(group);
1215*21fed052SAidan Dodds     } else {
1216*21fed052SAidan Dodds       // already have this script group
1217*21fed052SAidan Dodds       if (log)
1218*21fed052SAidan Dodds         log->Printf("Attempt to add duplicate script group %s",
1219*21fed052SAidan Dodds                     group_name.AsCString());
1220*21fed052SAidan Dodds       return;
1221*21fed052SAidan Dodds     }
1222*21fed052SAidan Dodds   }
1223*21fed052SAidan Dodds   assert(group);
1224*21fed052SAidan Dodds 
1225*21fed052SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1226*21fed052SAidan Dodds   std::vector<addr_t> kernels;
1227*21fed052SAidan Dodds   // parse kernel addresses in script group
1228*21fed052SAidan Dodds   for (uint64_t i = 0; i < uint64_t(args[eKernelCount]); ++i) {
1229*21fed052SAidan Dodds     RSScriptGroupDescriptor::Kernel kernel;
1230*21fed052SAidan Dodds     // extract script group kernel addresses from the target
1231*21fed052SAidan Dodds     const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size;
1232*21fed052SAidan Dodds     uint64_t kernel_addr = 0;
1233*21fed052SAidan Dodds     Error err;
1234*21fed052SAidan Dodds     size_t read =
1235*21fed052SAidan Dodds         m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err);
1236*21fed052SAidan Dodds     if (!err.Success() || read != target_ptr_size) {
1237*21fed052SAidan Dodds       if (log)
1238*21fed052SAidan Dodds         log->Printf("Error parsing kernel address %" PRIu64 " in script group",
1239*21fed052SAidan Dodds                     i);
1240*21fed052SAidan Dodds       return;
1241*21fed052SAidan Dodds     }
1242*21fed052SAidan Dodds     if (log)
1243*21fed052SAidan Dodds       log->Printf("Extracted scriptgroup kernel address - 0x%" PRIx64,
1244*21fed052SAidan Dodds                   kernel_addr);
1245*21fed052SAidan Dodds     kernel.m_addr = kernel_addr;
1246*21fed052SAidan Dodds 
1247*21fed052SAidan Dodds     // try to resolve the associated kernel name
1248*21fed052SAidan Dodds     if (!ResolveKernelName(kernel.m_addr, kernel.m_name)) {
1249*21fed052SAidan Dodds       if (log)
1250*21fed052SAidan Dodds         log->Printf("Parsed scriptgroup kernel %" PRIu64 " - 0x%" PRIx64, i,
1251*21fed052SAidan Dodds                     kernel_addr);
1252*21fed052SAidan Dodds       return;
1253*21fed052SAidan Dodds     }
1254*21fed052SAidan Dodds 
1255*21fed052SAidan Dodds     // try to find the non '.expand' function
1256*21fed052SAidan Dodds     {
1257*21fed052SAidan Dodds       const llvm::StringRef expand(".expand");
1258*21fed052SAidan Dodds       const llvm::StringRef name_ref = kernel.m_name.GetStringRef();
1259*21fed052SAidan Dodds       if (name_ref.endswith(expand)) {
1260*21fed052SAidan Dodds         const ConstString base_kernel(name_ref.drop_back(expand.size()));
1261*21fed052SAidan Dodds         // verify this function is a valid kernel
1262*21fed052SAidan Dodds         if (IsKnownKernel(base_kernel)) {
1263*21fed052SAidan Dodds           kernel.m_name = base_kernel;
1264*21fed052SAidan Dodds           if (log)
1265*21fed052SAidan Dodds             log->Printf("%s - found non expand version '%s'", __FUNCTION__,
1266*21fed052SAidan Dodds                         base_kernel.GetCString());
1267*21fed052SAidan Dodds         }
1268*21fed052SAidan Dodds       }
1269*21fed052SAidan Dodds     }
1270*21fed052SAidan Dodds     // add to a list of script group kernels we know about
1271*21fed052SAidan Dodds     group->m_kernels.push_back(kernel);
1272*21fed052SAidan Dodds   }
1273*21fed052SAidan Dodds 
1274*21fed052SAidan Dodds   // Resolve any pending scriptgroup breakpoints
1275*21fed052SAidan Dodds   {
1276*21fed052SAidan Dodds     Target &target = m_process->GetTarget();
1277*21fed052SAidan Dodds     const BreakpointList &list = target.GetBreakpointList();
1278*21fed052SAidan Dodds     const size_t num_breakpoints = list.GetSize();
1279*21fed052SAidan Dodds     if (log)
1280*21fed052SAidan Dodds       log->Printf("Resolving %zu breakpoints", num_breakpoints);
1281*21fed052SAidan Dodds     for (size_t i = 0; i < num_breakpoints; ++i) {
1282*21fed052SAidan Dodds       const BreakpointSP bp = list.GetBreakpointAtIndex(i);
1283*21fed052SAidan Dodds       if (bp) {
1284*21fed052SAidan Dodds         if (bp->MatchesName(group_name.AsCString())) {
1285*21fed052SAidan Dodds           if (log)
1286*21fed052SAidan Dodds             log->Printf("Found breakpoint with name %s",
1287*21fed052SAidan Dodds                         group_name.AsCString());
1288*21fed052SAidan Dodds           bp->ResolveBreakpoint();
1289*21fed052SAidan Dodds         }
1290*21fed052SAidan Dodds       }
1291*21fed052SAidan Dodds     }
1292*21fed052SAidan Dodds   }
1293*21fed052SAidan Dodds }
1294*21fed052SAidan Dodds 
1295b9c1b51eSKate Stone void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
129680af0b9eSLuke Drummond     RuntimeHook *hook, ExecutionContext &exe_ctx) {
1297e09c44b6SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1298e09c44b6SAidan Dodds 
1299b9c1b51eSKate Stone   enum {
1300f4786785SAidan Dodds     eRsContext = 0,
1301f4786785SAidan Dodds     eRsScript,
1302f4786785SAidan Dodds     eRsSlot,
1303f4786785SAidan Dodds     eRsAIns,
1304f4786785SAidan Dodds     eRsInLen,
1305f4786785SAidan Dodds     eRsAOut,
1306f4786785SAidan Dodds     eRsUsr,
1307f4786785SAidan Dodds     eRsUsrLen,
1308f4786785SAidan Dodds     eRsSc,
1309f4786785SAidan Dodds   };
1310e09c44b6SAidan Dodds 
13111ee07253SSaleem Abdulrasool   std::array<ArgItem, 9> args{{
1312f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Context       *rsc
1313f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Script              *s
1314f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // uint32_t             slot
1315f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Allocation   **aIns
1316f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               inLen
1317f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Allocation          *aout
1318f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const void          *usr
1319f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               usrLen
1320f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall  *sc
13211ee07253SSaleem Abdulrasool   }};
1322e09c44b6SAidan Dodds 
132380af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1324b9c1b51eSKate Stone   if (!success) {
1325e09c44b6SAidan Dodds     if (log)
1326b9c1b51eSKate Stone       log->Printf("%s - Error while reading the function parameters",
1327b9c1b51eSKate Stone                   __FUNCTION__);
1328e09c44b6SAidan Dodds     return;
1329e09c44b6SAidan Dodds   }
1330e09c44b6SAidan Dodds 
1331e09c44b6SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
133280af0b9eSLuke Drummond   Error err;
1333e09c44b6SAidan Dodds   std::vector<uint64_t> allocs;
1334e09c44b6SAidan Dodds 
1335e09c44b6SAidan Dodds   // traverse allocation list
1336b9c1b51eSKate Stone   for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1337e09c44b6SAidan Dodds     // calculate offest to allocation pointer
1338f4786785SAidan Dodds     const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1339e09c44b6SAidan Dodds 
134080af0b9eSLuke Drummond     // Note: due to little endian layout, reading 32bits or 64bits into res
134180af0b9eSLuke Drummond     // will give the correct results.
134280af0b9eSLuke Drummond     uint64_t result = 0;
134380af0b9eSLuke Drummond     size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
134480af0b9eSLuke Drummond     if (read != target_ptr_size || !err.Success()) {
1345e09c44b6SAidan Dodds       if (log)
1346b9c1b51eSKate Stone         log->Printf(
1347b9c1b51eSKate Stone             "%s - Error while reading allocation list argument %" PRIu64,
1348b9c1b51eSKate Stone             __FUNCTION__, i);
1349b9c1b51eSKate Stone     } else {
135080af0b9eSLuke Drummond       allocs.push_back(result);
1351e09c44b6SAidan Dodds     }
1352e09c44b6SAidan Dodds   }
1353e09c44b6SAidan Dodds 
1354e09c44b6SAidan Dodds   // if there is an output allocation track it
135580af0b9eSLuke Drummond   if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
135680af0b9eSLuke Drummond     allocs.push_back(alloc_out);
1357e09c44b6SAidan Dodds   }
1358e09c44b6SAidan Dodds 
1359e09c44b6SAidan Dodds   // for all allocations we have found
1360b9c1b51eSKate Stone   for (const uint64_t alloc_addr : allocs) {
13615d057637SLuke Drummond     AllocationDetails *alloc = LookUpAllocation(alloc_addr);
13625d057637SLuke Drummond     if (!alloc)
13635d057637SLuke Drummond       alloc = CreateAllocation(alloc_addr);
13645d057637SLuke Drummond 
1365b9c1b51eSKate Stone     if (alloc) {
1366e09c44b6SAidan Dodds       // save the allocation address
1367b9c1b51eSKate Stone       if (alloc->address.isValid()) {
1368e09c44b6SAidan Dodds         // check the allocation address we already have matches
1369e09c44b6SAidan Dodds         assert(*alloc->address.get() == alloc_addr);
1370b9c1b51eSKate Stone       } else {
1371e09c44b6SAidan Dodds         alloc->address = alloc_addr;
1372e09c44b6SAidan Dodds       }
1373e09c44b6SAidan Dodds 
1374e09c44b6SAidan Dodds       // save the context
1375b9c1b51eSKate Stone       if (log) {
1376b9c1b51eSKate Stone         if (alloc->context.isValid() &&
1377b9c1b51eSKate Stone             *alloc->context.get() != addr_t(args[eRsContext]))
1378b9c1b51eSKate Stone           log->Printf("%s - Allocation used by multiple contexts",
1379b9c1b51eSKate Stone                       __FUNCTION__);
1380e09c44b6SAidan Dodds       }
1381f4786785SAidan Dodds       alloc->context = addr_t(args[eRsContext]);
1382e09c44b6SAidan Dodds     }
1383e09c44b6SAidan Dodds   }
1384e09c44b6SAidan Dodds 
1385e09c44b6SAidan Dodds   // make sure we track this script object
1386b9c1b51eSKate Stone   if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1387b9c1b51eSKate Stone           LookUpScript(addr_t(args[eRsScript]), true)) {
1388b9c1b51eSKate Stone     if (log) {
1389b9c1b51eSKate Stone       if (script->context.isValid() &&
1390b9c1b51eSKate Stone           *script->context.get() != addr_t(args[eRsContext]))
1391b3f7f69dSAidan Dodds         log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1392e09c44b6SAidan Dodds     }
1393f4786785SAidan Dodds     script->context = addr_t(args[eRsContext]);
1394e09c44b6SAidan Dodds   }
1395e09c44b6SAidan Dodds }
1396e09c44b6SAidan Dodds 
139780af0b9eSLuke Drummond void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1398b9c1b51eSKate Stone                                               ExecutionContext &context) {
13994640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14004640cde1SColin Riley 
1401b9c1b51eSKate Stone   enum {
1402f4786785SAidan Dodds     eRsContext,
1403f4786785SAidan Dodds     eRsScript,
1404f4786785SAidan Dodds     eRsId,
1405f4786785SAidan Dodds     eRsData,
1406f4786785SAidan Dodds     eRsLength,
1407f4786785SAidan Dodds   };
14084640cde1SColin Riley 
14091ee07253SSaleem Abdulrasool   std::array<ArgItem, 5> args{{
1410f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1411f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsScript
1412f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsId
1413f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsData
1414f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsLength
14151ee07253SSaleem Abdulrasool   }};
14164640cde1SColin Riley 
1417f4786785SAidan Dodds   bool success = GetArgs(context, &args[0], args.size());
1418b9c1b51eSKate Stone   if (!success) {
141982780287SAidan Dodds     if (log)
1420b3f7f69dSAidan Dodds       log->Printf("%s - error reading the function parameters.", __FUNCTION__);
142182780287SAidan Dodds     return;
142282780287SAidan Dodds   }
14234640cde1SColin Riley 
1424b9c1b51eSKate Stone   if (log) {
1425b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1426b9c1b51eSKate Stone                 ":%" PRIu64 "bytes.",
1427b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1428b9c1b51eSKate Stone                 uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1429f4786785SAidan Dodds                 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
14304640cde1SColin Riley 
1431f4786785SAidan Dodds     addr_t script_addr = addr_t(args[eRsScript]);
1432b9c1b51eSKate Stone     if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
14334640cde1SColin Riley       auto rsm = m_scriptMappings[script_addr];
1434b9c1b51eSKate Stone       if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1435f4786785SAidan Dodds         auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1436b9c1b51eSKate Stone         log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__,
1437b9c1b51eSKate Stone                     rsg.m_name.AsCString(),
1438f4786785SAidan Dodds                     rsm->m_module->GetFileSpec().GetFilename().AsCString());
14394640cde1SColin Riley       }
14404640cde1SColin Riley     }
14414640cde1SColin Riley   }
14424640cde1SColin Riley }
14434640cde1SColin Riley 
144480af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
144580af0b9eSLuke Drummond                                                 ExecutionContext &exe_ctx) {
14464640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14474640cde1SColin Riley 
1448b9c1b51eSKate Stone   enum { eRsContext, eRsAlloc, eRsForceZero };
14494640cde1SColin Riley 
14501ee07253SSaleem Abdulrasool   std::array<ArgItem, 3> args{{
1451f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1452f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1453f4786785SAidan Dodds       ArgItem{ArgItem::eBool, 0},    // eRsForceZero
14541ee07253SSaleem Abdulrasool   }};
14554640cde1SColin Riley 
145680af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
145780af0b9eSLuke Drummond   if (!success) {
145882780287SAidan Dodds     if (log)
1459b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters",
1460b9c1b51eSKate Stone                   __FUNCTION__);
146180af0b9eSLuke Drummond     return;
146282780287SAidan Dodds   }
14634640cde1SColin Riley 
14644640cde1SColin Riley   if (log)
1465b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1466b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1467f4786785SAidan Dodds                 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
146878f339d1SEwan Crawford 
14695d057637SLuke Drummond   AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
147078f339d1SEwan Crawford   if (alloc)
1471f4786785SAidan Dodds     alloc->context = uint64_t(args[eRsContext]);
14724640cde1SColin Riley }
14734640cde1SColin Riley 
147480af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
147580af0b9eSLuke Drummond                                                    ExecutionContext &exe_ctx) {
1476e69df382SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1477e69df382SEwan Crawford 
1478b9c1b51eSKate Stone   enum {
1479f4786785SAidan Dodds     eRsContext,
1480f4786785SAidan Dodds     eRsAlloc,
1481f4786785SAidan Dodds   };
1482e69df382SEwan Crawford 
14831ee07253SSaleem Abdulrasool   std::array<ArgItem, 2> args{{
1484f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1485f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
14861ee07253SSaleem Abdulrasool   }};
1487f4786785SAidan Dodds 
148880af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1489b9c1b51eSKate Stone   if (!success) {
1490e69df382SEwan Crawford     if (log)
1491b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1492b9c1b51eSKate Stone                   __FUNCTION__);
1493b3f7f69dSAidan Dodds     return;
1494e69df382SEwan Crawford   }
1495e69df382SEwan Crawford 
1496e69df382SEwan Crawford   if (log)
1497b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1498b9c1b51eSKate Stone                 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1499e69df382SEwan Crawford 
1500b9c1b51eSKate Stone   for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1501e69df382SEwan Crawford     auto &allocation_ap = *iter; // get the unique pointer
1502b9c1b51eSKate Stone     if (allocation_ap->address.isValid() &&
1503b9c1b51eSKate Stone         *allocation_ap->address.get() == addr_t(args[eRsAlloc])) {
1504e69df382SEwan Crawford       m_allocations.erase(iter);
1505e69df382SEwan Crawford       if (log)
1506b3f7f69dSAidan Dodds         log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1507e69df382SEwan Crawford       return;
1508e69df382SEwan Crawford     }
1509e69df382SEwan Crawford   }
1510e69df382SEwan Crawford 
1511e69df382SEwan Crawford   if (log)
1512b3f7f69dSAidan Dodds     log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1513e69df382SEwan Crawford }
1514e69df382SEwan Crawford 
151580af0b9eSLuke Drummond void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
151680af0b9eSLuke Drummond                                             ExecutionContext &exe_ctx) {
15174640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
15184640cde1SColin Riley 
151980af0b9eSLuke Drummond   Error err;
152080af0b9eSLuke Drummond   Process *process = exe_ctx.GetProcessPtr();
15214640cde1SColin Riley 
1522b9c1b51eSKate Stone   enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
15234640cde1SColin Riley 
1524b9c1b51eSKate Stone   std::array<ArgItem, 4> args{
1525b9c1b51eSKate Stone       {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
15261ee07253SSaleem Abdulrasool        ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
152780af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1528b9c1b51eSKate Stone   if (!success) {
152982780287SAidan Dodds     if (log)
1530b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1531b9c1b51eSKate Stone                   __FUNCTION__);
153282780287SAidan Dodds     return;
153382780287SAidan Dodds   }
153482780287SAidan Dodds 
153580af0b9eSLuke Drummond   std::string res_name;
153680af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
153780af0b9eSLuke Drummond   if (err.Fail()) {
15384640cde1SColin Riley     if (log)
153980af0b9eSLuke Drummond       log->Printf("%s - error reading res_name: %s.", __FUNCTION__,
154080af0b9eSLuke Drummond                   err.AsCString());
15414640cde1SColin Riley   }
15424640cde1SColin Riley 
154380af0b9eSLuke Drummond   std::string cache_dir;
154480af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
154580af0b9eSLuke Drummond   if (err.Fail()) {
15464640cde1SColin Riley     if (log)
154780af0b9eSLuke Drummond       log->Printf("%s - error reading cache_dir: %s.", __FUNCTION__,
154880af0b9eSLuke Drummond                   err.AsCString());
15494640cde1SColin Riley   }
15504640cde1SColin Riley 
15514640cde1SColin Riley   if (log)
1552b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1553b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
155480af0b9eSLuke Drummond                 uint64_t(args[eRsScript]), res_name.c_str(), cache_dir.c_str());
15554640cde1SColin Riley 
155680af0b9eSLuke Drummond   if (res_name.size() > 0) {
15574640cde1SColin Riley     StreamString strm;
155880af0b9eSLuke Drummond     strm.Printf("librs.%s.so", res_name.c_str());
15594640cde1SColin Riley 
1560f4786785SAidan Dodds     ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1561b9c1b51eSKate Stone     if (script) {
156278f339d1SEwan Crawford       script->type = ScriptDetails::eScriptC;
156380af0b9eSLuke Drummond       script->cache_dir = cache_dir;
156480af0b9eSLuke Drummond       script->res_name = res_name;
156580af0b9eSLuke Drummond       script->shared_lib = strm.GetData();
1566f4786785SAidan Dodds       script->context = addr_t(args[eRsContext]);
156778f339d1SEwan Crawford     }
15684640cde1SColin Riley 
15694640cde1SColin Riley     if (log)
1570b9c1b51eSKate Stone       log->Printf("%s - '%s' tagged with context 0x%" PRIx64
1571b9c1b51eSKate Stone                   " and script 0x%" PRIx64 ".",
1572b9c1b51eSKate Stone                   __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1573b9c1b51eSKate Stone                   uint64_t(args[eRsScript]));
1574b9c1b51eSKate Stone   } else if (log) {
1575b3f7f69dSAidan Dodds     log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
15764640cde1SColin Riley   }
15774640cde1SColin Riley }
15784640cde1SColin Riley 
1579b9c1b51eSKate Stone void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1580b9c1b51eSKate Stone                                            ModuleKind kind) {
15814640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
15824640cde1SColin Riley 
1583b9c1b51eSKate Stone   if (!module) {
15844640cde1SColin Riley     return;
15854640cde1SColin Riley   }
15864640cde1SColin Riley 
158782780287SAidan Dodds   Target &target = GetProcess()->GetTarget();
1588*21fed052SAidan Dodds   const llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
158982780287SAidan Dodds 
159080af0b9eSLuke Drummond   if (machine != llvm::Triple::ArchType::x86 &&
159180af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::arm &&
159280af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::aarch64 &&
159380af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mipsel &&
159480af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mips64el &&
159580af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::x86_64) {
15964640cde1SColin Riley     if (log)
1597b3f7f69dSAidan Dodds       log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
15984640cde1SColin Riley     return;
15994640cde1SColin Riley   }
16004640cde1SColin Riley 
1601*21fed052SAidan Dodds   const uint32_t target_ptr_size =
1602*21fed052SAidan Dodds       target.GetArchitecture().GetAddressByteSize();
1603*21fed052SAidan Dodds 
1604*21fed052SAidan Dodds   std::array<bool, s_runtimeHookCount> hook_placed;
1605*21fed052SAidan Dodds   hook_placed.fill(false);
16064640cde1SColin Riley 
1607b9c1b51eSKate Stone   for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
16084640cde1SColin Riley     const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1609b9c1b51eSKate Stone     if (hook_defn->kind != kind) {
16104640cde1SColin Riley       continue;
16114640cde1SColin Riley     }
16124640cde1SColin Riley 
161380af0b9eSLuke Drummond     const char *symbol_name = (target_ptr_size == 4)
161480af0b9eSLuke Drummond                                   ? hook_defn->symbol_name_m32
1615b9c1b51eSKate Stone                                   : hook_defn->symbol_name_m64;
161682780287SAidan Dodds 
1617b9c1b51eSKate Stone     const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1618b9c1b51eSKate Stone         ConstString(symbol_name), eSymbolTypeCode);
1619b9c1b51eSKate Stone     if (!sym) {
1620b9c1b51eSKate Stone       if (log) {
1621b3f7f69dSAidan Dodds         log->Printf("%s - symbol '%s' related to the function %s not found",
1622b3f7f69dSAidan Dodds                     __FUNCTION__, symbol_name, hook_defn->name);
162382780287SAidan Dodds       }
162482780287SAidan Dodds       continue;
162582780287SAidan Dodds     }
16264640cde1SColin Riley 
1627358cf1eaSGreg Clayton     addr_t addr = sym->GetLoadAddress(&target);
1628b9c1b51eSKate Stone     if (addr == LLDB_INVALID_ADDRESS) {
16294640cde1SColin Riley       if (log)
1630b9c1b51eSKate Stone         log->Printf("%s - unable to resolve the address of hook function '%s' "
1631b9c1b51eSKate Stone                     "with symbol '%s'.",
1632b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, symbol_name);
16334640cde1SColin Riley       continue;
1634b9c1b51eSKate Stone     } else {
163582780287SAidan Dodds       if (log)
1636b3f7f69dSAidan Dodds         log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1637b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, addr);
163882780287SAidan Dodds     }
16394640cde1SColin Riley 
16404640cde1SColin Riley     RuntimeHookSP hook(new RuntimeHook());
16414640cde1SColin Riley     hook->address = addr;
16424640cde1SColin Riley     hook->defn = hook_defn;
16434640cde1SColin Riley     hook->bp_sp = target.CreateBreakpoint(addr, true, false);
16444640cde1SColin Riley     hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
16454640cde1SColin Riley     m_runtimeHooks[addr] = hook;
1646b9c1b51eSKate Stone     if (log) {
1647b9c1b51eSKate Stone       log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64
1648b9c1b51eSKate Stone                   " at 0x%" PRIx64 ".",
1649b9c1b51eSKate Stone                   __FUNCTION__, hook_defn->name,
1650b9c1b51eSKate Stone                   module->GetFileSpec().GetFilename().AsCString(),
1651b3f7f69dSAidan Dodds                   (uint64_t)hook_defn->version, (uint64_t)addr);
16524640cde1SColin Riley     }
1653*21fed052SAidan Dodds     hook_placed[idx] = true;
1654*21fed052SAidan Dodds   }
1655*21fed052SAidan Dodds 
1656*21fed052SAidan Dodds   // log any unhooked function
1657*21fed052SAidan Dodds   if (log) {
1658*21fed052SAidan Dodds     for (size_t i = 0; i < hook_placed.size(); ++i) {
1659*21fed052SAidan Dodds       if (hook_placed[i])
1660*21fed052SAidan Dodds         continue;
1661*21fed052SAidan Dodds       const HookDefn &hook_defn = s_runtimeHookDefns[i];
1662*21fed052SAidan Dodds       if (hook_defn.kind != kind)
1663*21fed052SAidan Dodds         continue;
1664*21fed052SAidan Dodds       log->Printf("%s - function %s was not hooked", __FUNCTION__,
1665*21fed052SAidan Dodds                   hook_defn.name);
1666*21fed052SAidan Dodds     }
16674640cde1SColin Riley   }
16684640cde1SColin Riley }
16694640cde1SColin Riley 
1670b9c1b51eSKate Stone void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
16714640cde1SColin Riley   if (!rsmodule_sp)
16724640cde1SColin Riley     return;
16734640cde1SColin Riley 
16744640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
16754640cde1SColin Riley 
16764640cde1SColin Riley   const ModuleSP module = rsmodule_sp->m_module;
16774640cde1SColin Riley   const FileSpec &file = module->GetPlatformFileSpec();
16784640cde1SColin Riley 
167978f339d1SEwan Crawford   // Iterate over all of the scripts that we currently know of.
168078f339d1SEwan Crawford   // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
1681b9c1b51eSKate Stone   for (const auto &rs_script : m_scripts) {
168278f339d1SEwan Crawford     // Extract the expected .so file path for this script.
168380af0b9eSLuke Drummond     std::string shared_lib;
168480af0b9eSLuke Drummond     if (!rs_script->shared_lib.get(shared_lib))
168578f339d1SEwan Crawford       continue;
168678f339d1SEwan Crawford 
168778f339d1SEwan Crawford     // Only proceed if the module that has loaded corresponds to this script.
168880af0b9eSLuke Drummond     if (file.GetFilename() != ConstString(shared_lib.c_str()))
168978f339d1SEwan Crawford       continue;
169078f339d1SEwan Crawford 
169178f339d1SEwan Crawford     // Obtain the script address which we use as a key.
169278f339d1SEwan Crawford     lldb::addr_t script;
169378f339d1SEwan Crawford     if (!rs_script->script.get(script))
169478f339d1SEwan Crawford       continue;
169578f339d1SEwan Crawford 
169678f339d1SEwan Crawford     // If we have a script mapping for the current script.
1697b9c1b51eSKate Stone     if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
169878f339d1SEwan Crawford       // if the module we have stored is different to the one we just received.
1699b9c1b51eSKate Stone       if (m_scriptMappings[script] != rsmodule_sp) {
17004640cde1SColin Riley         if (log)
1701b9c1b51eSKate Stone           log->Printf(
1702b9c1b51eSKate Stone               "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1703b9c1b51eSKate Stone               __FUNCTION__, (uint64_t)script,
1704b9c1b51eSKate Stone               rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
17054640cde1SColin Riley       }
17064640cde1SColin Riley     }
170778f339d1SEwan Crawford     // We don't have a script mapping for the current script.
1708b9c1b51eSKate Stone     else {
170978f339d1SEwan Crawford       // Obtain the script resource name.
171080af0b9eSLuke Drummond       std::string res_name;
171180af0b9eSLuke Drummond       if (rs_script->res_name.get(res_name))
171278f339d1SEwan Crawford         // Set the modules resource name.
171380af0b9eSLuke Drummond         rsmodule_sp->m_resname = res_name;
171478f339d1SEwan Crawford       // Add Script/Module pair to map.
171578f339d1SEwan Crawford       m_scriptMappings[script] = rsmodule_sp;
17164640cde1SColin Riley       if (log)
1717b9c1b51eSKate Stone         log->Printf(
1718b9c1b51eSKate Stone             "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1719b9c1b51eSKate Stone             __FUNCTION__, (uint64_t)script,
1720b9c1b51eSKate Stone             rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
17214640cde1SColin Riley     }
17224640cde1SColin Riley   }
17234640cde1SColin Riley }
17244640cde1SColin Riley 
1725b9c1b51eSKate Stone // Uses the Target API to evaluate the expression passed as a parameter to the
172680af0b9eSLuke Drummond // function The result of that expression is returned an unsigned 64 bit int,
172780af0b9eSLuke Drummond // via the result* parameter. Function returns true on success, and false on
172880af0b9eSLuke Drummond // failure
172980af0b9eSLuke Drummond bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1730b9c1b51eSKate Stone                                            StackFrame *frame_ptr,
1731b9c1b51eSKate Stone                                            uint64_t *result) {
173215f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
173315f2bd95SEwan Crawford   if (log)
173480af0b9eSLuke Drummond     log->Printf("%s(%s)", __FUNCTION__, expr);
173515f2bd95SEwan Crawford 
173615f2bd95SEwan Crawford   ValueObjectSP expr_result;
17378433fdbeSAidan Dodds   EvaluateExpressionOptions options;
17388433fdbeSAidan Dodds   options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
173915f2bd95SEwan Crawford   // Perform the actual expression evaluation
174080af0b9eSLuke Drummond   auto &target = GetProcess()->GetTarget();
174180af0b9eSLuke Drummond   target.EvaluateExpression(expr, frame_ptr, expr_result, options);
174215f2bd95SEwan Crawford 
1743b9c1b51eSKate Stone   if (!expr_result) {
174415f2bd95SEwan Crawford     if (log)
1745b3f7f69dSAidan Dodds       log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
174615f2bd95SEwan Crawford     return false;
174715f2bd95SEwan Crawford   }
174815f2bd95SEwan Crawford 
174915f2bd95SEwan Crawford   // The result of the expression is invalid
1750b9c1b51eSKate Stone   if (!expr_result->GetError().Success()) {
175115f2bd95SEwan Crawford     Error err = expr_result->GetError();
175280af0b9eSLuke Drummond     // Expression returned is void, so this is actually a success
175380af0b9eSLuke Drummond     if (err.GetError() == UserExpression::kNoResult) {
175415f2bd95SEwan Crawford       if (log)
1755b3f7f69dSAidan Dodds         log->Printf("%s - expression returned void.", __FUNCTION__);
175615f2bd95SEwan Crawford 
175715f2bd95SEwan Crawford       result = nullptr;
175815f2bd95SEwan Crawford       return true;
175915f2bd95SEwan Crawford     }
176015f2bd95SEwan Crawford 
176115f2bd95SEwan Crawford     if (log)
1762b3f7f69dSAidan Dodds       log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1763b3f7f69dSAidan Dodds                   err.AsCString());
176415f2bd95SEwan Crawford     return false;
176515f2bd95SEwan Crawford   }
176615f2bd95SEwan Crawford 
176715f2bd95SEwan Crawford   bool success = false;
176880af0b9eSLuke Drummond   // We only read the result as an uint32_t.
176980af0b9eSLuke Drummond   *result = expr_result->GetValueAsUnsigned(0, &success);
177015f2bd95SEwan Crawford 
1771b9c1b51eSKate Stone   if (!success) {
177215f2bd95SEwan Crawford     if (log)
1773b9c1b51eSKate Stone       log->Printf("%s - couldn't convert expression result to uint32_t",
1774b9c1b51eSKate Stone                   __FUNCTION__);
177515f2bd95SEwan Crawford     return false;
177615f2bd95SEwan Crawford   }
177715f2bd95SEwan Crawford 
177815f2bd95SEwan Crawford   return true;
177915f2bd95SEwan Crawford }
178015f2bd95SEwan Crawford 
1781b9c1b51eSKate Stone namespace {
1782836d9651SEwan Crawford // Used to index expression format strings
1783b9c1b51eSKate Stone enum ExpressionStrings {
1784836d9651SEwan Crawford   eExprGetOffsetPtr = 0,
1785836d9651SEwan Crawford   eExprAllocGetType,
1786836d9651SEwan Crawford   eExprTypeDimX,
1787836d9651SEwan Crawford   eExprTypeDimY,
1788836d9651SEwan Crawford   eExprTypeDimZ,
1789836d9651SEwan Crawford   eExprTypeElemPtr,
1790836d9651SEwan Crawford   eExprElementType,
1791836d9651SEwan Crawford   eExprElementKind,
1792836d9651SEwan Crawford   eExprElementVec,
1793836d9651SEwan Crawford   eExprElementFieldCount,
1794836d9651SEwan Crawford   eExprSubelementsId,
1795836d9651SEwan Crawford   eExprSubelementsName,
1796ea0636b5SEwan Crawford   eExprSubelementsArrSize,
1797ea0636b5SEwan Crawford 
179880af0b9eSLuke Drummond   _eExprLast // keep at the end, implicit size of the array runtime_expressions
1799836d9651SEwan Crawford };
180015f2bd95SEwan Crawford 
1801ea0636b5SEwan Crawford // max length of an expanded expression
1802ea0636b5SEwan Crawford const int jit_max_expr_size = 512;
1803ea0636b5SEwan Crawford 
1804ea0636b5SEwan Crawford // Retrieve the string to JIT for the given expression
1805b9c1b51eSKate Stone const char *JITTemplate(ExpressionStrings e) {
1806ea0636b5SEwan Crawford   // Format strings containing the expressions we may need to evaluate.
180780af0b9eSLuke Drummond   static std::array<const char *, _eExprLast> runtime_expressions = {
1808b9c1b51eSKate Stone       {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1809b9c1b51eSKate Stone        "(int*)_"
1810b9c1b51eSKate Stone        "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1811b9c1b51eSKate Stone        "CubemapFace"
1812577570b4SAidan Dodds        "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)",
181315f2bd95SEwan Crawford 
181415f2bd95SEwan Crawford        // Type* rsaAllocationGetType(Context*, Allocation*)
1815577570b4SAidan Dodds        "(void*)rsaAllocationGetType(0x%" PRIx64 ", 0x%" PRIx64 ")",
181615f2bd95SEwan Crawford 
181780af0b9eSLuke Drummond        // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
181880af0b9eSLuke Drummond        // data in the following way mHal.state.dimX; mHal.state.dimY;
181980af0b9eSLuke Drummond        // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement; into
182080af0b9eSLuke Drummond        // typeData Need to specify 32 or 64 bit for uint_t since this differs
182180af0b9eSLuke Drummond        // between devices
1822b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1823b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[0]", // X dim
1824b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1825b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[1]", // Y dim
1826b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1827b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[2]", // Z dim
1828b9c1b51eSKate Stone        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1829b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 6); data[5]", // Element ptr
183015f2bd95SEwan Crawford 
183115f2bd95SEwan Crawford        // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1832b9c1b51eSKate Stone        // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1833b9c1b51eSKate Stone        // elemData
1834b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1835b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[0]", // Type
1836b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1837b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[1]", // Kind
1838b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1839b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[3]", // Vector Size
1840b9c1b51eSKate Stone        "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1841b9c1b51eSKate Stone        ", 0x%" PRIx64 ", data, 5); data[4]", // Field Count
18428b244e21SEwan Crawford 
1843b9c1b51eSKate Stone        // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
184480af0b9eSLuke Drummond        // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1845b9c1b51eSKate Stone        // Needed for Allocations of structs to gather details about
184680af0b9eSLuke Drummond        // fields/Subelements Element* of field
1847b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1848b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1849b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1850b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]",
18518b244e21SEwan Crawford 
1852577570b4SAidan Dodds        // Name of field
1853b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1854b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1855b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1856b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]",
18578b244e21SEwan Crawford 
1858577570b4SAidan Dodds        // Array size of field
1859b9c1b51eSKate Stone        "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1860b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
1861b9c1b51eSKate Stone        "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1862b9c1b51eSKate Stone        ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}};
1863ea0636b5SEwan Crawford 
186480af0b9eSLuke Drummond   return runtime_expressions[e];
1865ea0636b5SEwan Crawford }
1866ea0636b5SEwan Crawford } // end of the anonymous namespace
1867ea0636b5SEwan Crawford 
186880af0b9eSLuke Drummond // JITs the RS runtime for the internal data pointer of an allocation. Is passed
186980af0b9eSLuke Drummond // x,y,z coordinates for the pointer to a specific element. Then sets the
187080af0b9eSLuke Drummond // data_ptr member in Allocation with the result. Returns true on success, false
187180af0b9eSLuke Drummond // otherwise
187280af0b9eSLuke Drummond bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1873b9c1b51eSKate Stone                                          StackFrame *frame_ptr, uint32_t x,
1874b9c1b51eSKate Stone                                          uint32_t y, uint32_t z) {
187515f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
187615f2bd95SEwan Crawford 
187780af0b9eSLuke Drummond   if (!alloc->address.isValid()) {
187815f2bd95SEwan Crawford     if (log)
1879b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
188015f2bd95SEwan Crawford     return false;
188115f2bd95SEwan Crawford   }
188215f2bd95SEwan Crawford 
188380af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
188480af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
188515f2bd95SEwan Crawford 
188680af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
188780af0b9eSLuke Drummond                          *alloc->address.get(), x, y, z);
188880af0b9eSLuke Drummond   if (written < 0) {
188915f2bd95SEwan Crawford     if (log)
1890b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
189115f2bd95SEwan Crawford     return false;
189280af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
189315f2bd95SEwan Crawford     if (log)
1894b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
189515f2bd95SEwan Crawford     return false;
189615f2bd95SEwan Crawford   }
189715f2bd95SEwan Crawford 
189815f2bd95SEwan Crawford   uint64_t result = 0;
189980af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
190015f2bd95SEwan Crawford     return false;
190115f2bd95SEwan Crawford 
190280af0b9eSLuke Drummond   addr_t data_ptr = static_cast<lldb::addr_t>(result);
190380af0b9eSLuke Drummond   alloc->data_ptr = data_ptr;
190415f2bd95SEwan Crawford 
190515f2bd95SEwan Crawford   return true;
190615f2bd95SEwan Crawford }
190715f2bd95SEwan Crawford 
190815f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
190980af0b9eSLuke Drummond // Then sets the type_ptr member in Allocation with the result. Returns true on
191080af0b9eSLuke Drummond // success, false otherwise
191180af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1912b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
191315f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
191415f2bd95SEwan Crawford 
191580af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->context.isValid()) {
191615f2bd95SEwan Crawford     if (log)
1917b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
191815f2bd95SEwan Crawford     return false;
191915f2bd95SEwan Crawford   }
192015f2bd95SEwan Crawford 
192180af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprAllocGetType);
192280af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
192315f2bd95SEwan Crawford 
192480af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
192580af0b9eSLuke Drummond                          *alloc->context.get(), *alloc->address.get());
192680af0b9eSLuke Drummond   if (written < 0) {
192715f2bd95SEwan Crawford     if (log)
1928b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
192915f2bd95SEwan Crawford     return false;
193080af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
193115f2bd95SEwan Crawford     if (log)
1932b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
193315f2bd95SEwan Crawford     return false;
193415f2bd95SEwan Crawford   }
193515f2bd95SEwan Crawford 
193615f2bd95SEwan Crawford   uint64_t result = 0;
193780af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
193815f2bd95SEwan Crawford     return false;
193915f2bd95SEwan Crawford 
194015f2bd95SEwan Crawford   addr_t type_ptr = static_cast<lldb::addr_t>(result);
194180af0b9eSLuke Drummond   alloc->type_ptr = type_ptr;
194215f2bd95SEwan Crawford 
194315f2bd95SEwan Crawford   return true;
194415f2bd95SEwan Crawford }
194515f2bd95SEwan Crawford 
1946b9c1b51eSKate Stone // JITs the RS runtime for information about the dimensions and type of an
194780af0b9eSLuke Drummond // allocation Then sets dimension and element_ptr members in Allocation with the
194880af0b9eSLuke Drummond // result. Returns true on success, false otherwise
194980af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1950b9c1b51eSKate Stone                                         StackFrame *frame_ptr) {
195115f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
195215f2bd95SEwan Crawford 
195380af0b9eSLuke Drummond   if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
195415f2bd95SEwan Crawford     if (log)
1955b3f7f69dSAidan Dodds       log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
195615f2bd95SEwan Crawford     return false;
195715f2bd95SEwan Crawford   }
195815f2bd95SEwan Crawford 
195915f2bd95SEwan Crawford   // Expression is different depending on if device is 32 or 64 bit
196080af0b9eSLuke Drummond   uint32_t target_ptr_size =
1961b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
196280af0b9eSLuke Drummond   const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
196315f2bd95SEwan Crawford 
196415f2bd95SEwan Crawford   // We want 4 elements from packed data
1965b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
1966b9c1b51eSKate Stone   assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) &&
1967b9c1b51eSKate Stone          "Invalid number of expressions");
196815f2bd95SEwan Crawford 
196980af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
197015f2bd95SEwan Crawford   uint64_t results[num_exprs];
197115f2bd95SEwan Crawford 
1972b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; ++i) {
197380af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
197480af0b9eSLuke Drummond     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, bits,
197580af0b9eSLuke Drummond                            *alloc->context.get(), *alloc->type_ptr.get());
197680af0b9eSLuke Drummond     if (written < 0) {
197715f2bd95SEwan Crawford       if (log)
1978b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
197915f2bd95SEwan Crawford       return false;
198080af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
198115f2bd95SEwan Crawford       if (log)
1982b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
198315f2bd95SEwan Crawford       return false;
198415f2bd95SEwan Crawford     }
198515f2bd95SEwan Crawford 
198615f2bd95SEwan Crawford     // Perform expression evaluation
198780af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
198815f2bd95SEwan Crawford       return false;
198915f2bd95SEwan Crawford   }
199015f2bd95SEwan Crawford 
199115f2bd95SEwan Crawford   // Assign results to allocation members
199215f2bd95SEwan Crawford   AllocationDetails::Dimension dims;
199315f2bd95SEwan Crawford   dims.dim_1 = static_cast<uint32_t>(results[0]);
199415f2bd95SEwan Crawford   dims.dim_2 = static_cast<uint32_t>(results[1]);
199515f2bd95SEwan Crawford   dims.dim_3 = static_cast<uint32_t>(results[2]);
199680af0b9eSLuke Drummond   alloc->dimension = dims;
199715f2bd95SEwan Crawford 
199880af0b9eSLuke Drummond   addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
199980af0b9eSLuke Drummond   alloc->element.element_ptr = element_ptr;
200015f2bd95SEwan Crawford 
200115f2bd95SEwan Crawford   if (log)
2002b9c1b51eSKate Stone     log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
2003b9c1b51eSKate Stone                 ") Element*: 0x%" PRIx64 ".",
200480af0b9eSLuke Drummond                 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
200515f2bd95SEwan Crawford 
200615f2bd95SEwan Crawford   return true;
200715f2bd95SEwan Crawford }
200815f2bd95SEwan Crawford 
200980af0b9eSLuke Drummond // JITs the RS runtime for information about the Element of an allocation Then
201080af0b9eSLuke Drummond // sets type, type_vec_size, field_count and type_kind members in Element with
201180af0b9eSLuke Drummond // the result. Returns true on success, false otherwise
2012b9c1b51eSKate Stone bool RenderScriptRuntime::JITElementPacked(Element &elem,
2013b9c1b51eSKate Stone                                            const lldb::addr_t context,
2014b9c1b51eSKate Stone                                            StackFrame *frame_ptr) {
201515f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
201615f2bd95SEwan Crawford 
2017b9c1b51eSKate Stone   if (!elem.element_ptr.isValid()) {
201815f2bd95SEwan Crawford     if (log)
2019b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
202015f2bd95SEwan Crawford     return false;
202115f2bd95SEwan Crawford   }
202215f2bd95SEwan Crawford 
20238b244e21SEwan Crawford   // We want 4 elements from packed data
2024b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
2025b9c1b51eSKate Stone   assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) &&
2026b9c1b51eSKate Stone          "Invalid number of expressions");
202715f2bd95SEwan Crawford 
202880af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
202915f2bd95SEwan Crawford   uint64_t results[num_exprs];
203015f2bd95SEwan Crawford 
2031b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; i++) {
203280af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
203380af0b9eSLuke Drummond     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
203480af0b9eSLuke Drummond                            *elem.element_ptr.get());
203580af0b9eSLuke Drummond     if (written < 0) {
203615f2bd95SEwan Crawford       if (log)
2037b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
203815f2bd95SEwan Crawford       return false;
203980af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
204015f2bd95SEwan Crawford       if (log)
2041b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
204215f2bd95SEwan Crawford       return false;
204315f2bd95SEwan Crawford     }
204415f2bd95SEwan Crawford 
204515f2bd95SEwan Crawford     // Perform expression evaluation
204680af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
204715f2bd95SEwan Crawford       return false;
204815f2bd95SEwan Crawford   }
204915f2bd95SEwan Crawford 
205015f2bd95SEwan Crawford   // Assign results to allocation members
20518b244e21SEwan Crawford   elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
2052b9c1b51eSKate Stone   elem.type_kind =
2053b9c1b51eSKate Stone       static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
20548b244e21SEwan Crawford   elem.type_vec_size = static_cast<uint32_t>(results[2]);
20558b244e21SEwan Crawford   elem.field_count = static_cast<uint32_t>(results[3]);
205615f2bd95SEwan Crawford 
205715f2bd95SEwan Crawford   if (log)
2058b9c1b51eSKate Stone     log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32
2059b9c1b51eSKate Stone                 ", vector size %" PRIu32 ", field count %" PRIu32,
2060b9c1b51eSKate Stone                 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
2061b9c1b51eSKate Stone                 *elem.type_vec_size.get(), *elem.field_count.get());
20628b244e21SEwan Crawford 
2063b9c1b51eSKate Stone   // If this Element has subelements then JIT rsaElementGetSubElements() for
2064b9c1b51eSKate Stone   // details about its fields
20658b244e21SEwan Crawford   if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
20668b244e21SEwan Crawford     return false;
20678b244e21SEwan Crawford 
20688b244e21SEwan Crawford   return true;
20698b244e21SEwan Crawford }
20708b244e21SEwan Crawford 
2071b9c1b51eSKate Stone // JITs the RS runtime for information about the subelements/fields of a struct
207280af0b9eSLuke Drummond // allocation This is necessary for infering the struct type so we can pretty
207380af0b9eSLuke Drummond // print the allocation's contents. Returns true on success, false otherwise
2074b9c1b51eSKate Stone bool RenderScriptRuntime::JITSubelements(Element &elem,
2075b9c1b51eSKate Stone                                          const lldb::addr_t context,
2076b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
20778b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
20788b244e21SEwan Crawford 
2079b9c1b51eSKate Stone   if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
20808b244e21SEwan Crawford     if (log)
2081b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
20828b244e21SEwan Crawford     return false;
20838b244e21SEwan Crawford   }
20848b244e21SEwan Crawford 
20858b244e21SEwan Crawford   const short num_exprs = 3;
2086b9c1b51eSKate Stone   assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) &&
2087b9c1b51eSKate Stone          "Invalid number of expressions");
20888b244e21SEwan Crawford 
2089ea0636b5SEwan Crawford   char expr_buffer[jit_max_expr_size];
20908b244e21SEwan Crawford   uint64_t results;
20918b244e21SEwan Crawford 
20928b244e21SEwan Crawford   // Iterate over struct fields.
20938b244e21SEwan Crawford   const uint32_t field_count = *elem.field_count.get();
2094b9c1b51eSKate Stone   for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
20958b244e21SEwan Crawford     Element child;
2096b9c1b51eSKate Stone     for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
209780af0b9eSLuke Drummond       const char *fmt_str =
2098b9c1b51eSKate Stone           JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
209980af0b9eSLuke Drummond       int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
210080af0b9eSLuke Drummond                              field_count, field_count, field_count, context,
210180af0b9eSLuke Drummond                              *elem.element_ptr.get(), field_count, field_index);
210280af0b9eSLuke Drummond       if (written < 0) {
21038b244e21SEwan Crawford         if (log)
2104b3f7f69dSAidan Dodds           log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
21058b244e21SEwan Crawford         return false;
210680af0b9eSLuke Drummond       } else if (written >= jit_max_expr_size) {
21078b244e21SEwan Crawford         if (log)
2108b3f7f69dSAidan Dodds           log->Printf("%s - expression too long.", __FUNCTION__);
21098b244e21SEwan Crawford         return false;
21108b244e21SEwan Crawford       }
21118b244e21SEwan Crawford 
21128b244e21SEwan Crawford       // Perform expression evaluation
21138b244e21SEwan Crawford       if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
21148b244e21SEwan Crawford         return false;
21158b244e21SEwan Crawford 
21168b244e21SEwan Crawford       if (log)
2117b3f7f69dSAidan Dodds         log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
21188b244e21SEwan Crawford 
2119b9c1b51eSKate Stone       switch (expr_index) {
21208b244e21SEwan Crawford       case 0: // Element* of child
21218b244e21SEwan Crawford         child.element_ptr = static_cast<addr_t>(results);
21228b244e21SEwan Crawford         break;
21238b244e21SEwan Crawford       case 1: // Name of child
21248b244e21SEwan Crawford       {
21258b244e21SEwan Crawford         lldb::addr_t address = static_cast<addr_t>(results);
21268b244e21SEwan Crawford         Error err;
21278b244e21SEwan Crawford         std::string name;
21288b244e21SEwan Crawford         GetProcess()->ReadCStringFromMemory(address, name, err);
21298b244e21SEwan Crawford         if (!err.Fail())
21308b244e21SEwan Crawford           child.type_name = ConstString(name);
2131b9c1b51eSKate Stone         else {
21328b244e21SEwan Crawford           if (log)
2133b9c1b51eSKate Stone             log->Printf("%s - warning: Couldn't read field name.",
2134b9c1b51eSKate Stone                         __FUNCTION__);
21358b244e21SEwan Crawford         }
21368b244e21SEwan Crawford         break;
21378b244e21SEwan Crawford       }
21388b244e21SEwan Crawford       case 2: // Array size of child
21398b244e21SEwan Crawford         child.array_size = static_cast<uint32_t>(results);
21408b244e21SEwan Crawford         break;
21418b244e21SEwan Crawford       }
21428b244e21SEwan Crawford     }
21438b244e21SEwan Crawford 
21448b244e21SEwan Crawford     // We need to recursively JIT each Element field of the struct since
21458b244e21SEwan Crawford     // structs can be nested inside structs.
21468b244e21SEwan Crawford     if (!JITElementPacked(child, context, frame_ptr))
21478b244e21SEwan Crawford       return false;
21488b244e21SEwan Crawford     elem.children.push_back(child);
21498b244e21SEwan Crawford   }
21508b244e21SEwan Crawford 
2151b9c1b51eSKate Stone   // Try to infer the name of the struct type so we can pretty print the
2152b9c1b51eSKate Stone   // allocation contents.
21538b244e21SEwan Crawford   FindStructTypeName(elem, frame_ptr);
215415f2bd95SEwan Crawford 
215515f2bd95SEwan Crawford   return true;
215615f2bd95SEwan Crawford }
215715f2bd95SEwan Crawford 
2158a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
2159b9c1b51eSKate Stone // The `elem_size` parameter represents the size of a single element, including
216080af0b9eSLuke Drummond // padding. Which is needed as an offset from the last element pointer. Using
216180af0b9eSLuke Drummond // this offset minus the starting address we can calculate the size of the
216280af0b9eSLuke Drummond // allocation. Returns true on success, false otherwise
216380af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
2164b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
2165a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2166a0f08674SEwan Crawford 
216780af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
216880af0b9eSLuke Drummond       !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
2169a0f08674SEwan Crawford     if (log)
2170b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2171a0f08674SEwan Crawford     return false;
2172a0f08674SEwan Crawford   }
2173a0f08674SEwan Crawford 
2174a0f08674SEwan Crawford   // Find dimensions
217580af0b9eSLuke Drummond   uint32_t dim_x = alloc->dimension.get()->dim_1;
217680af0b9eSLuke Drummond   uint32_t dim_y = alloc->dimension.get()->dim_2;
217780af0b9eSLuke Drummond   uint32_t dim_z = alloc->dimension.get()->dim_3;
2178a0f08674SEwan Crawford 
2179b9c1b51eSKate Stone   // Our plan of jitting the last element address doesn't seem to work for
218080af0b9eSLuke Drummond   // struct Allocations` Instead try to infer the size ourselves without any
218180af0b9eSLuke Drummond   // inter element padding.
218280af0b9eSLuke Drummond   if (alloc->element.children.size() > 0) {
2183b9c1b51eSKate Stone     if (dim_x == 0)
2184b9c1b51eSKate Stone       dim_x = 1;
2185b9c1b51eSKate Stone     if (dim_y == 0)
2186b9c1b51eSKate Stone       dim_y = 1;
2187b9c1b51eSKate Stone     if (dim_z == 0)
2188b9c1b51eSKate Stone       dim_z = 1;
21898b244e21SEwan Crawford 
219080af0b9eSLuke Drummond     alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
21918b244e21SEwan Crawford 
21928b244e21SEwan Crawford     if (log)
2193b9c1b51eSKate Stone       log->Printf("%s - inferred size of struct allocation %" PRIu32 ".",
219480af0b9eSLuke Drummond                   __FUNCTION__, *alloc->size.get());
21958b244e21SEwan Crawford     return true;
21968b244e21SEwan Crawford   }
21978b244e21SEwan Crawford 
219880af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
219980af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
22008b244e21SEwan Crawford 
2201a0f08674SEwan Crawford   // Calculate last element
2202a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 0 : dim_x - 1;
2203a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 0 : dim_y - 1;
2204a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 0 : dim_z - 1;
2205a0f08674SEwan Crawford 
220680af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
220780af0b9eSLuke Drummond                          *alloc->address.get(), dim_x, dim_y, dim_z);
220880af0b9eSLuke Drummond   if (written < 0) {
2209a0f08674SEwan Crawford     if (log)
2210b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2211a0f08674SEwan Crawford     return false;
221280af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
2213a0f08674SEwan Crawford     if (log)
2214b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
2215a0f08674SEwan Crawford     return false;
2216a0f08674SEwan Crawford   }
2217a0f08674SEwan Crawford 
2218a0f08674SEwan Crawford   uint64_t result = 0;
221980af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2220a0f08674SEwan Crawford     return false;
2221a0f08674SEwan Crawford 
2222a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2223a0f08674SEwan Crawford   // Find pointer to last element and add on size of an element
222480af0b9eSLuke Drummond   alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
222580af0b9eSLuke Drummond                 *alloc->element.datum_size.get();
2226a0f08674SEwan Crawford 
2227a0f08674SEwan Crawford   return true;
2228a0f08674SEwan Crawford }
2229a0f08674SEwan Crawford 
2230b9c1b51eSKate Stone // JITs the RS runtime for information about the stride between rows in the
223180af0b9eSLuke Drummond // allocation. This is done to detect padding, since allocated memory is 16-byte
223280af0b9eSLuke Drummond // aligned.
2233a0f08674SEwan Crawford // Returns true on success, false otherwise
223480af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
2235b9c1b51eSKate Stone                                               StackFrame *frame_ptr) {
2236a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2237a0f08674SEwan Crawford 
223880af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
2239a0f08674SEwan Crawford     if (log)
2240b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2241a0f08674SEwan Crawford     return false;
2242a0f08674SEwan Crawford   }
2243a0f08674SEwan Crawford 
224480af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
224580af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
2246a0f08674SEwan Crawford 
224780af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
224880af0b9eSLuke Drummond                          *alloc->address.get(), 0, 1, 0);
224980af0b9eSLuke Drummond   if (written < 0) {
2250a0f08674SEwan Crawford     if (log)
2251b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2252a0f08674SEwan Crawford     return false;
225380af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
2254a0f08674SEwan Crawford     if (log)
2255b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
2256a0f08674SEwan Crawford     return false;
2257a0f08674SEwan Crawford   }
2258a0f08674SEwan Crawford 
2259a0f08674SEwan Crawford   uint64_t result = 0;
226080af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2261a0f08674SEwan Crawford     return false;
2262a0f08674SEwan Crawford 
2263a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
226480af0b9eSLuke Drummond   alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
2265a0f08674SEwan Crawford 
2266a0f08674SEwan Crawford   return true;
2267a0f08674SEwan Crawford }
2268a0f08674SEwan Crawford 
226915f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
227080af0b9eSLuke Drummond bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2271b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
227215f2bd95SEwan Crawford   // GetOffsetPointer()
227380af0b9eSLuke Drummond   if (!JITDataPointer(alloc, frame_ptr))
227415f2bd95SEwan Crawford     return false;
227515f2bd95SEwan Crawford 
227615f2bd95SEwan Crawford   // rsaAllocationGetType()
227780af0b9eSLuke Drummond   if (!JITTypePointer(alloc, frame_ptr))
227815f2bd95SEwan Crawford     return false;
227915f2bd95SEwan Crawford 
228015f2bd95SEwan Crawford   // rsaTypeGetNativeData()
228180af0b9eSLuke Drummond   if (!JITTypePacked(alloc, frame_ptr))
228215f2bd95SEwan Crawford     return false;
228315f2bd95SEwan Crawford 
228415f2bd95SEwan Crawford   // rsaElementGetNativeData()
228580af0b9eSLuke Drummond   if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
228615f2bd95SEwan Crawford     return false;
228715f2bd95SEwan Crawford 
22888b244e21SEwan Crawford   // Sets the datum_size member in Element
228980af0b9eSLuke Drummond   SetElementSize(alloc->element);
22908b244e21SEwan Crawford 
229155232f09SEwan Crawford   // Use GetOffsetPointer() to infer size of the allocation
229280af0b9eSLuke Drummond   if (!JITAllocationSize(alloc, frame_ptr))
229355232f09SEwan Crawford     return false;
229455232f09SEwan Crawford 
229555232f09SEwan Crawford   return true;
229655232f09SEwan Crawford }
229755232f09SEwan Crawford 
2298b9c1b51eSKate Stone // Function attempts to set the type_name member of the paramaterised Element
2299b9c1b51eSKate Stone // object.
23008b244e21SEwan Crawford // This string should be the name of the struct type the Element represents.
23018b244e21SEwan Crawford // We need this string for pretty printing the Element to users.
2302b9c1b51eSKate Stone void RenderScriptRuntime::FindStructTypeName(Element &elem,
2303b9c1b51eSKate Stone                                              StackFrame *frame_ptr) {
23048b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
23058b244e21SEwan Crawford 
23068b244e21SEwan Crawford   if (!elem.type_name.IsEmpty()) // Name already set
23078b244e21SEwan Crawford     return;
23088b244e21SEwan Crawford   else
2309b9c1b51eSKate Stone     elem.type_name = Element::GetFallbackStructName(); // Default type name if
2310b9c1b51eSKate Stone                                                        // we don't succeed
23118b244e21SEwan Crawford 
23128b244e21SEwan Crawford   // Find all the global variables from the script rs modules
231380af0b9eSLuke Drummond   VariableList var_list;
23148b244e21SEwan Crawford   for (auto module_sp : m_rsmodules)
231595eae423SZachary Turner     module_sp->m_module->FindGlobalVariables(
231680af0b9eSLuke Drummond         RegularExpression(llvm::StringRef(".")), true, UINT32_MAX, var_list);
23178b244e21SEwan Crawford 
2318b9c1b51eSKate Stone   // Iterate over all the global variables looking for one with a matching type
2319b9c1b51eSKate Stone   // to the Element.
2320b9c1b51eSKate Stone   // We make the assumption a match exists since there needs to be a global
232180af0b9eSLuke Drummond   // variable to reflect the struct type back into java host code.
232280af0b9eSLuke Drummond   for (uint32_t i = 0; i < var_list.GetSize(); ++i) {
232380af0b9eSLuke Drummond     const VariableSP var_sp(var_list.GetVariableAtIndex(i));
23248b244e21SEwan Crawford     if (!var_sp)
23258b244e21SEwan Crawford       continue;
23268b244e21SEwan Crawford 
23278b244e21SEwan Crawford     ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
23288b244e21SEwan Crawford     if (!valobj_sp)
23298b244e21SEwan Crawford       continue;
23308b244e21SEwan Crawford 
23318b244e21SEwan Crawford     // Find the number of variable fields.
2332b9c1b51eSKate Stone     // If it has no fields, or more fields than our Element, then it can't be
2333b9c1b51eSKate Stone     // the struct we're looking for.
2334b9c1b51eSKate Stone     // Don't check for equality since RS can add extra struct members for
2335b9c1b51eSKate Stone     // padding.
23368b244e21SEwan Crawford     size_t num_children = valobj_sp->GetNumChildren();
23378b244e21SEwan Crawford     if (num_children > elem.children.size() || num_children == 0)
23388b244e21SEwan Crawford       continue;
23398b244e21SEwan Crawford 
23408b244e21SEwan Crawford     // Iterate over children looking for members with matching field names.
23418b244e21SEwan Crawford     // If all the field names match, this is likely the struct we want.
2342b9c1b51eSKate Stone     //   TODO: This could be made more robust by also checking children data
2343b9c1b51eSKate Stone     //   sizes, or array size
23448b244e21SEwan Crawford     bool found = true;
234580af0b9eSLuke Drummond     for (size_t i = 0; i < num_children; ++i) {
234680af0b9eSLuke Drummond       ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
234780af0b9eSLuke Drummond       if (!child || (child->GetName() != elem.children[i].type_name)) {
23488b244e21SEwan Crawford         found = false;
23498b244e21SEwan Crawford         break;
23508b244e21SEwan Crawford       }
23518b244e21SEwan Crawford     }
23528b244e21SEwan Crawford 
2353b9c1b51eSKate Stone     // RS can add extra struct members for padding in the format
2354b9c1b51eSKate Stone     // '#rs_padding_[0-9]+'
2355b9c1b51eSKate Stone     if (found && num_children < elem.children.size()) {
2356b3f7f69dSAidan Dodds       const uint32_t size_diff = elem.children.size() - num_children;
23578b244e21SEwan Crawford       if (log)
2358b9c1b51eSKate Stone         log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2359b9c1b51eSKate Stone                     size_diff);
23608b244e21SEwan Crawford 
236180af0b9eSLuke Drummond       for (uint32_t i = 0; i < size_diff; ++i) {
236280af0b9eSLuke Drummond         const ConstString &name = elem.children[num_children + i].type_name;
23638b244e21SEwan Crawford         if (strcmp(name.AsCString(), "#rs_padding") < 0)
23648b244e21SEwan Crawford           found = false;
23658b244e21SEwan Crawford       }
23668b244e21SEwan Crawford     }
23678b244e21SEwan Crawford 
236880af0b9eSLuke Drummond     // We've found a global variable with matching type
2369b9c1b51eSKate Stone     if (found) {
23708b244e21SEwan Crawford       // Dereference since our Element type isn't a pointer.
2371b9c1b51eSKate Stone       if (valobj_sp->IsPointerType()) {
23728b244e21SEwan Crawford         Error err;
23738b244e21SEwan Crawford         ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
23748b244e21SEwan Crawford         if (!err.Fail())
23758b244e21SEwan Crawford           valobj_sp = deref_valobj;
23768b244e21SEwan Crawford       }
23778b244e21SEwan Crawford 
23788b244e21SEwan Crawford       // Save name of variable in Element.
23798b244e21SEwan Crawford       elem.type_name = valobj_sp->GetTypeName();
23808b244e21SEwan Crawford       if (log)
2381b9c1b51eSKate Stone         log->Printf("%s - element name set to %s", __FUNCTION__,
2382b9c1b51eSKate Stone                     elem.type_name.AsCString());
23838b244e21SEwan Crawford 
23848b244e21SEwan Crawford       return;
23858b244e21SEwan Crawford     }
23868b244e21SEwan Crawford   }
23878b244e21SEwan Crawford }
23888b244e21SEwan Crawford 
2389b9c1b51eSKate Stone // Function sets the datum_size member of Element. Representing the size of a
2390b9c1b51eSKate Stone // single instance including padding.
23918b244e21SEwan Crawford // Assumes the relevant allocation information has already been jitted.
2392b9c1b51eSKate Stone void RenderScriptRuntime::SetElementSize(Element &elem) {
23938b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
23948b244e21SEwan Crawford   const Element::DataType type = *elem.type.get();
2395b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2396b9c1b51eSKate Stone          "Invalid allocation type");
239755232f09SEwan Crawford 
2398b3f7f69dSAidan Dodds   const uint32_t vec_size = *elem.type_vec_size.get();
2399b3f7f69dSAidan Dodds   uint32_t data_size = 0;
2400b3f7f69dSAidan Dodds   uint32_t padding = 0;
240155232f09SEwan Crawford 
24028b244e21SEwan Crawford   // Element is of a struct type, calculate size recursively.
2403b9c1b51eSKate Stone   if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2404b9c1b51eSKate Stone     for (Element &child : elem.children) {
24058b244e21SEwan Crawford       SetElementSize(child);
2406b9c1b51eSKate Stone       const uint32_t array_size =
2407b9c1b51eSKate Stone           child.array_size.isValid() ? *child.array_size.get() : 1;
24088b244e21SEwan Crawford       data_size += *child.datum_size.get() * array_size;
24098b244e21SEwan Crawford     }
24108b244e21SEwan Crawford   }
2411b3f7f69dSAidan Dodds   // These have been packed already
2412b3f7f69dSAidan Dodds   else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2413b3f7f69dSAidan Dodds            type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2414b9c1b51eSKate Stone            type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
24152e920715SEwan Crawford     data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2416b9c1b51eSKate Stone   } else if (type < Element::RS_TYPE_ELEMENT) {
2417b9c1b51eSKate Stone     data_size =
2418b9c1b51eSKate Stone         vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
24192e920715SEwan Crawford     if (vec_size == 3)
24202e920715SEwan Crawford       padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2421b9c1b51eSKate Stone   } else
2422b9c1b51eSKate Stone     data_size =
2423b9c1b51eSKate Stone         GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
24248b244e21SEwan Crawford 
24258b244e21SEwan Crawford   elem.padding = padding;
24268b244e21SEwan Crawford   elem.datum_size = data_size + padding;
24278b244e21SEwan Crawford   if (log)
2428b9c1b51eSKate Stone     log->Printf("%s - element size set to %" PRIu32, __FUNCTION__,
2429b9c1b51eSKate Stone                 data_size + padding);
243055232f09SEwan Crawford }
243155232f09SEwan Crawford 
2432b9c1b51eSKate Stone // Given an allocation, this function copies the allocation contents from device
2433b9c1b51eSKate Stone // into a buffer on the heap.
243455232f09SEwan Crawford // Returning a shared pointer to the buffer containing the data.
243555232f09SEwan Crawford std::shared_ptr<uint8_t>
243680af0b9eSLuke Drummond RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2437b9c1b51eSKate Stone                                        StackFrame *frame_ptr) {
243855232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
243955232f09SEwan Crawford 
244055232f09SEwan Crawford   // JIT all the allocation details
244180af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
244255232f09SEwan Crawford     if (log)
2443b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info",
2444b9c1b51eSKate Stone                   __FUNCTION__);
244555232f09SEwan Crawford 
244680af0b9eSLuke Drummond     if (!RefreshAllocation(alloc, frame_ptr)) {
244755232f09SEwan Crawford       if (log)
2448b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
244955232f09SEwan Crawford       return nullptr;
245055232f09SEwan Crawford     }
245155232f09SEwan Crawford   }
245255232f09SEwan Crawford 
245380af0b9eSLuke Drummond   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
245480af0b9eSLuke Drummond          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
245580af0b9eSLuke Drummond          "Allocation information not available");
245655232f09SEwan Crawford 
245755232f09SEwan Crawford   // Allocate a buffer to copy data into
245880af0b9eSLuke Drummond   const uint32_t size = *alloc->size.get();
245955232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2460b9c1b51eSKate Stone   if (!buffer) {
246155232f09SEwan Crawford     if (log)
2462b9c1b51eSKate Stone       log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer",
2463b9c1b51eSKate Stone                   __FUNCTION__, size);
246455232f09SEwan Crawford     return nullptr;
246555232f09SEwan Crawford   }
246655232f09SEwan Crawford 
246755232f09SEwan Crawford   // Read the inferior memory
246880af0b9eSLuke Drummond   Error err;
246980af0b9eSLuke Drummond   lldb::addr_t data_ptr = *alloc->data_ptr.get();
247080af0b9eSLuke Drummond   GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
247180af0b9eSLuke Drummond   if (err.Fail()) {
247255232f09SEwan Crawford     if (log)
2473b9c1b51eSKate Stone       log->Printf("%s - '%s' Couldn't read %" PRIu32
2474b9c1b51eSKate Stone                   " bytes of allocation data from 0x%" PRIx64,
247580af0b9eSLuke Drummond                   __FUNCTION__, err.AsCString(), size, data_ptr);
247655232f09SEwan Crawford     return nullptr;
247755232f09SEwan Crawford   }
247855232f09SEwan Crawford 
247955232f09SEwan Crawford   return buffer;
248055232f09SEwan Crawford }
248155232f09SEwan Crawford 
248255232f09SEwan Crawford // Function copies data from a binary file into an allocation.
2483b9c1b51eSKate Stone // There is a header at the start of the file, FileHeader, before the data
2484b9c1b51eSKate Stone // content itself.
2485b9c1b51eSKate Stone // Information from this header is used to display warnings to the user about
2486b9c1b51eSKate Stone // incompatibilities
2487b9c1b51eSKate Stone bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
248880af0b9eSLuke Drummond                                          const char *path,
2489b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
249055232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
249155232f09SEwan Crawford 
249255232f09SEwan Crawford   // Find allocation with the given id
249355232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
249455232f09SEwan Crawford   if (!alloc)
249555232f09SEwan Crawford     return false;
249655232f09SEwan Crawford 
249755232f09SEwan Crawford   if (log)
2498b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2499b9c1b51eSKate Stone                 *alloc->address.get());
250055232f09SEwan Crawford 
250155232f09SEwan Crawford   // JIT all the allocation details
250280af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
250355232f09SEwan Crawford     if (log)
2504b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2505b9c1b51eSKate Stone                   __FUNCTION__);
250655232f09SEwan Crawford 
2507b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
250855232f09SEwan Crawford       if (log)
2509b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
25104cfc9198SSylvestre Ledru       return false;
251155232f09SEwan Crawford     }
251255232f09SEwan Crawford   }
251355232f09SEwan Crawford 
2514b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2515b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2516b9c1b51eSKate Stone          alloc->element.datum_size.isValid() &&
2517b9c1b51eSKate Stone          "Allocation information not available");
251855232f09SEwan Crawford 
251955232f09SEwan Crawford   // Check we can read from file
252080af0b9eSLuke Drummond   FileSpec file(path, true);
2521b9c1b51eSKate Stone   if (!file.Exists()) {
252280af0b9eSLuke Drummond     strm.Printf("Error: File %s does not exist", path);
252355232f09SEwan Crawford     strm.EOL();
252455232f09SEwan Crawford     return false;
252555232f09SEwan Crawford   }
252655232f09SEwan Crawford 
2527b9c1b51eSKate Stone   if (!file.Readable()) {
252880af0b9eSLuke Drummond     strm.Printf("Error: File %s does not have readable permissions", path);
252955232f09SEwan Crawford     strm.EOL();
253055232f09SEwan Crawford     return false;
253155232f09SEwan Crawford   }
253255232f09SEwan Crawford 
253355232f09SEwan Crawford   // Read file into data buffer
253455232f09SEwan Crawford   DataBufferSP data_sp(file.ReadFileContents());
253555232f09SEwan Crawford 
253655232f09SEwan Crawford   // Cast start of buffer to FileHeader and use pointer to read metadata
253780af0b9eSLuke Drummond   void *file_buf = data_sp->GetBytes();
253880af0b9eSLuke Drummond   if (file_buf == nullptr ||
2539b9c1b51eSKate Stone       data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2540b9c1b51eSKate Stone                                 sizeof(AllocationDetails::ElementHeader))) {
254180af0b9eSLuke Drummond     strm.Printf("Error: File %s does not contain enough data for header", path);
254226e52a70SEwan Crawford     strm.EOL();
254326e52a70SEwan Crawford     return false;
254426e52a70SEwan Crawford   }
2545b9c1b51eSKate Stone   const AllocationDetails::FileHeader *file_header =
254680af0b9eSLuke Drummond       static_cast<AllocationDetails::FileHeader *>(file_buf);
254755232f09SEwan Crawford 
254826e52a70SEwan Crawford   // Check file starts with ascii characters "RSAD"
2549b9c1b51eSKate Stone   if (memcmp(file_header->ident, "RSAD", 4)) {
2550b9c1b51eSKate Stone     strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2551b9c1b51eSKate Stone                 "dump. Are you sure this is the correct file?");
255226e52a70SEwan Crawford     strm.EOL();
255326e52a70SEwan Crawford     return false;
255426e52a70SEwan Crawford   }
255526e52a70SEwan Crawford 
255626e52a70SEwan Crawford   // Look at the type of the root element in the header
255780af0b9eSLuke Drummond   AllocationDetails::ElementHeader root_el_hdr;
255880af0b9eSLuke Drummond   memcpy(&root_el_hdr, static_cast<uint8_t *>(file_buf) +
2559b9c1b51eSKate Stone                            sizeof(AllocationDetails::FileHeader),
256026e52a70SEwan Crawford          sizeof(AllocationDetails::ElementHeader));
256155232f09SEwan Crawford 
256255232f09SEwan Crawford   if (log)
2563b9c1b51eSKate Stone     log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32,
256480af0b9eSLuke Drummond                 __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
256555232f09SEwan Crawford 
2566b9c1b51eSKate Stone   // Check if the target allocation and file both have the same number of bytes
2567b9c1b51eSKate Stone   // for an Element
256880af0b9eSLuke Drummond   if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2569b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2570b9c1b51eSKate Stone                 " bytes, allocation %" PRIu32 " bytes",
257180af0b9eSLuke Drummond                 root_el_hdr.element_size, *alloc->element.datum_size.get());
257255232f09SEwan Crawford     strm.EOL();
257355232f09SEwan Crawford   }
257455232f09SEwan Crawford 
257526e52a70SEwan Crawford   // Check if the target allocation and file both have the same type
2576b3f7f69dSAidan Dodds   const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
257780af0b9eSLuke Drummond   const uint32_t file_type = root_el_hdr.type;
257826e52a70SEwan Crawford 
2579b9c1b51eSKate Stone   if (file_type > Element::RS_TYPE_FONT) {
258026e52a70SEwan Crawford     strm.Printf("Warning: File has unknown allocation type");
258126e52a70SEwan Crawford     strm.EOL();
2582b9c1b51eSKate Stone   } else if (alloc_type != file_type) {
2583b9c1b51eSKate Stone     // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2584b9c1b51eSKate Stone     // array
258580af0b9eSLuke Drummond     uint32_t target_type_name_idx = alloc_type;
258680af0b9eSLuke Drummond     uint32_t head_type_name_idx = file_type;
2587b9c1b51eSKate Stone     if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2588b9c1b51eSKate Stone         alloc_type <= Element::RS_TYPE_FONT)
258980af0b9eSLuke Drummond       target_type_name_idx = static_cast<Element::DataType>(
2590b9c1b51eSKate Stone           (alloc_type - Element::RS_TYPE_ELEMENT) +
2591b3f7f69dSAidan Dodds           Element::RS_TYPE_MATRIX_2X2 + 1);
25922e920715SEwan Crawford 
2593b9c1b51eSKate Stone     if (file_type >= Element::RS_TYPE_ELEMENT &&
2594b9c1b51eSKate Stone         file_type <= Element::RS_TYPE_FONT)
259580af0b9eSLuke Drummond       head_type_name_idx = static_cast<Element::DataType>(
2596b9c1b51eSKate Stone           (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2597b9c1b51eSKate Stone           1);
25982e920715SEwan Crawford 
259980af0b9eSLuke Drummond     const char *head_type_name =
260080af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
260180af0b9eSLuke Drummond     const char *target_type_name =
260280af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
260355232f09SEwan Crawford 
2604b9c1b51eSKate Stone     strm.Printf(
2605b9c1b51eSKate Stone         "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
260680af0b9eSLuke Drummond         head_type_name, target_type_name);
260755232f09SEwan Crawford     strm.EOL();
260855232f09SEwan Crawford   }
260955232f09SEwan Crawford 
261026e52a70SEwan Crawford   // Advance buffer past header
261180af0b9eSLuke Drummond   file_buf = static_cast<uint8_t *>(file_buf) + file_header->hdr_size;
261226e52a70SEwan Crawford 
261355232f09SEwan Crawford   // Calculate size of allocation data in file
261480af0b9eSLuke Drummond   size_t size = data_sp->GetByteSize() - file_header->hdr_size;
261555232f09SEwan Crawford 
261655232f09SEwan Crawford   // Check if the target allocation and file both have the same total data size.
2617b3f7f69dSAidan Dodds   const uint32_t alloc_size = *alloc->size.get();
261880af0b9eSLuke Drummond   if (alloc_size != size) {
2619b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2620b9c1b51eSKate Stone                 " bytes, allocation 0x%" PRIx32 " bytes",
262180af0b9eSLuke Drummond                 (uint64_t)size, alloc_size);
262255232f09SEwan Crawford     strm.EOL();
262380af0b9eSLuke Drummond     // Set length to copy to minimum
262480af0b9eSLuke Drummond     size = alloc_size < size ? alloc_size : size;
262555232f09SEwan Crawford   }
262655232f09SEwan Crawford 
262755232f09SEwan Crawford   // Copy file data from our buffer into the target allocation.
262855232f09SEwan Crawford   lldb::addr_t alloc_data = *alloc->data_ptr.get();
262980af0b9eSLuke Drummond   Error err;
263080af0b9eSLuke Drummond   size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
263180af0b9eSLuke Drummond   if (!err.Success() || written != size) {
263280af0b9eSLuke Drummond     strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
263355232f09SEwan Crawford     strm.EOL();
263455232f09SEwan Crawford     return false;
263555232f09SEwan Crawford   }
263655232f09SEwan Crawford 
263780af0b9eSLuke Drummond   strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2638b9c1b51eSKate Stone               alloc->id);
263955232f09SEwan Crawford   strm.EOL();
264055232f09SEwan Crawford 
264155232f09SEwan Crawford   return true;
264255232f09SEwan Crawford }
264355232f09SEwan Crawford 
2644b9c1b51eSKate Stone // Function takes as parameters a byte buffer, which will eventually be written
264580af0b9eSLuke Drummond // to file as the element header, an offset into that buffer, and an Element
264680af0b9eSLuke Drummond // that will be saved into the buffer at the parametrised offset.
264726e52a70SEwan Crawford // Return value is the new offset after writing the element into the buffer.
2648b9c1b51eSKate Stone // Elements are saved to the file as the ElementHeader struct followed by
264980af0b9eSLuke Drummond // offsets to the structs of all the element's children.
2650b9c1b51eSKate Stone size_t RenderScriptRuntime::PopulateElementHeaders(
2651b9c1b51eSKate Stone     const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2652b9c1b51eSKate Stone     const Element &elem) {
2653b9c1b51eSKate Stone   // File struct for an element header with all the relevant details copied from
265480af0b9eSLuke Drummond   // elem. We assume members are valid already.
265526e52a70SEwan Crawford   AllocationDetails::ElementHeader elem_header;
265626e52a70SEwan Crawford   elem_header.type = *elem.type.get();
265726e52a70SEwan Crawford   elem_header.kind = *elem.type_kind.get();
265826e52a70SEwan Crawford   elem_header.element_size = *elem.datum_size.get();
265926e52a70SEwan Crawford   elem_header.vector_size = *elem.type_vec_size.get();
2660b9c1b51eSKate Stone   elem_header.array_size =
2661b9c1b51eSKate Stone       elem.array_size.isValid() ? *elem.array_size.get() : 0;
266226e52a70SEwan Crawford   const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
266326e52a70SEwan Crawford 
266426e52a70SEwan Crawford   // Copy struct into buffer and advance offset
2665b9c1b51eSKate Stone   // We assume that header_buffer has been checked for nullptr before this
2666b9c1b51eSKate Stone   // method is called
266726e52a70SEwan Crawford   memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
266826e52a70SEwan Crawford   offset += elem_header_size;
266926e52a70SEwan Crawford 
267026e52a70SEwan Crawford   // Starting offset of child ElementHeader struct
2671b9c1b51eSKate Stone   size_t child_offset =
2672b9c1b51eSKate Stone       offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2673b9c1b51eSKate Stone   for (const RenderScriptRuntime::Element &child : elem.children) {
2674b9c1b51eSKate Stone     // Recursively populate the buffer with the element header structs of
267580af0b9eSLuke Drummond     // children. Then save the offsets where they were set after the parent
267680af0b9eSLuke Drummond     // element header.
267726e52a70SEwan Crawford     memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
267826e52a70SEwan Crawford     offset += sizeof(uint32_t);
267926e52a70SEwan Crawford 
268026e52a70SEwan Crawford     child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
268126e52a70SEwan Crawford   }
268226e52a70SEwan Crawford 
268326e52a70SEwan Crawford   // Zero indicates no more children
268426e52a70SEwan Crawford   memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
268526e52a70SEwan Crawford 
268626e52a70SEwan Crawford   return child_offset;
268726e52a70SEwan Crawford }
268826e52a70SEwan Crawford 
2689b9c1b51eSKate Stone // Given an Element object this function returns the total size needed in the
269080af0b9eSLuke Drummond // file header to store the element's details. Taking into account the size of
269180af0b9eSLuke Drummond // the element header struct, plus the offsets to all the element's children.
2692b9c1b51eSKate Stone // Function is recursive so that the size of all ancestors is taken into
2693b9c1b51eSKate Stone // account.
2694b9c1b51eSKate Stone size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
269580af0b9eSLuke Drummond   // Offsets to children plus zero terminator
269680af0b9eSLuke Drummond   size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
269780af0b9eSLuke Drummond   // Size of header struct with type details
269880af0b9eSLuke Drummond   size += sizeof(AllocationDetails::ElementHeader);
269926e52a70SEwan Crawford 
270026e52a70SEwan Crawford   // Calculate recursively for all descendants
270126e52a70SEwan Crawford   for (const Element &child : elem.children)
270226e52a70SEwan Crawford     size += CalculateElementHeaderSize(child);
270326e52a70SEwan Crawford 
270426e52a70SEwan Crawford   return size;
270526e52a70SEwan Crawford }
270626e52a70SEwan Crawford 
270780af0b9eSLuke Drummond // Function copies allocation contents into a binary file. This file can then be
270880af0b9eSLuke Drummond // loaded later into a different allocation. There is a header, FileHeader,
270980af0b9eSLuke Drummond // before the allocation data containing meta-data.
2710b9c1b51eSKate Stone bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
271180af0b9eSLuke Drummond                                          const char *path,
2712b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
271355232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
271455232f09SEwan Crawford 
271555232f09SEwan Crawford   // Find allocation with the given id
271655232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
271755232f09SEwan Crawford   if (!alloc)
271855232f09SEwan Crawford     return false;
271955232f09SEwan Crawford 
272055232f09SEwan Crawford   if (log)
2721b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2722b9c1b51eSKate Stone                 *alloc->address.get());
272355232f09SEwan Crawford 
272455232f09SEwan Crawford   // JIT all the allocation details
272580af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
272655232f09SEwan Crawford     if (log)
2727b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2728b9c1b51eSKate Stone                   __FUNCTION__);
272955232f09SEwan Crawford 
2730b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
273155232f09SEwan Crawford       if (log)
2732b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
27334cfc9198SSylvestre Ledru       return false;
273455232f09SEwan Crawford     }
273555232f09SEwan Crawford   }
273655232f09SEwan Crawford 
2737b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2738b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() &&
2739b9c1b51eSKate Stone          alloc->element.datum_size.get() &&
2740b9c1b51eSKate Stone          alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2741b3f7f69dSAidan Dodds          "Allocation information not available");
274255232f09SEwan Crawford 
274355232f09SEwan Crawford   // Check we can create writable file
274480af0b9eSLuke Drummond   FileSpec file_spec(path, true);
2745b9c1b51eSKate Stone   File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate |
2746b9c1b51eSKate Stone                            File::eOpenOptionTruncate);
2747b9c1b51eSKate Stone   if (!file) {
274880af0b9eSLuke Drummond     strm.Printf("Error: Failed to open '%s' for writing", path);
274955232f09SEwan Crawford     strm.EOL();
275055232f09SEwan Crawford     return false;
275155232f09SEwan Crawford   }
275255232f09SEwan Crawford 
275355232f09SEwan Crawford   // Read allocation into buffer of heap memory
275455232f09SEwan Crawford   const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2755b9c1b51eSKate Stone   if (!buffer) {
275655232f09SEwan Crawford     strm.Printf("Error: Couldn't read allocation data into buffer");
275755232f09SEwan Crawford     strm.EOL();
275855232f09SEwan Crawford     return false;
275955232f09SEwan Crawford   }
276055232f09SEwan Crawford 
276155232f09SEwan Crawford   // Create the file header
276255232f09SEwan Crawford   AllocationDetails::FileHeader head;
2763b3f7f69dSAidan Dodds   memcpy(head.ident, "RSAD", 4);
27642d62328aSEwan Crawford   head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
27652d62328aSEwan Crawford   head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
27662d62328aSEwan Crawford   head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
276726e52a70SEwan Crawford 
276826e52a70SEwan Crawford   const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2769b9c1b51eSKate Stone   assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2770b9c1b51eSKate Stone              UINT16_MAX &&
2771b9c1b51eSKate Stone          "Element header too large");
2772b9c1b51eSKate Stone   head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2773b9c1b51eSKate Stone                                         element_header_size);
277455232f09SEwan Crawford 
277555232f09SEwan Crawford   // Write the file header
277655232f09SEwan Crawford   size_t num_bytes = sizeof(AllocationDetails::FileHeader);
277726e52a70SEwan Crawford   if (log)
2778b9c1b51eSKate Stone     log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2779b9c1b51eSKate Stone                 (uint64_t)num_bytes);
278026e52a70SEwan Crawford 
278126e52a70SEwan Crawford   Error err = file.Write(&head, num_bytes);
2782b9c1b51eSKate Stone   if (!err.Success()) {
278380af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
278426e52a70SEwan Crawford     strm.EOL();
278526e52a70SEwan Crawford     return false;
278626e52a70SEwan Crawford   }
278726e52a70SEwan Crawford 
278826e52a70SEwan Crawford   // Create the headers describing the element type of the allocation.
2789b9c1b51eSKate Stone   std::shared_ptr<uint8_t> element_header_buffer(
2790b9c1b51eSKate Stone       new uint8_t[element_header_size]);
2791b9c1b51eSKate Stone   if (element_header_buffer == nullptr) {
2792b9c1b51eSKate Stone     strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2793b9c1b51eSKate Stone                 " bytes on the heap",
2794b9c1b51eSKate Stone                 (uint64_t)element_header_size);
279526e52a70SEwan Crawford     strm.EOL();
279626e52a70SEwan Crawford     return false;
279726e52a70SEwan Crawford   }
279826e52a70SEwan Crawford 
279926e52a70SEwan Crawford   PopulateElementHeaders(element_header_buffer, 0, alloc->element);
280026e52a70SEwan Crawford 
280126e52a70SEwan Crawford   // Write headers for allocation element type to file
280226e52a70SEwan Crawford   num_bytes = element_header_size;
280326e52a70SEwan Crawford   if (log)
2804b9c1b51eSKate Stone     log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.",
2805b9c1b51eSKate Stone                 __FUNCTION__, (uint64_t)num_bytes);
280626e52a70SEwan Crawford 
280726e52a70SEwan Crawford   err = file.Write(element_header_buffer.get(), num_bytes);
2808b9c1b51eSKate Stone   if (!err.Success()) {
280980af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
281055232f09SEwan Crawford     strm.EOL();
281155232f09SEwan Crawford     return false;
281255232f09SEwan Crawford   }
281355232f09SEwan Crawford 
281455232f09SEwan Crawford   // Write allocation data to file
281555232f09SEwan Crawford   num_bytes = static_cast<size_t>(*alloc->size.get());
281655232f09SEwan Crawford   if (log)
2817b9c1b51eSKate Stone     log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2818b9c1b51eSKate Stone                 (uint64_t)num_bytes);
281955232f09SEwan Crawford 
282055232f09SEwan Crawford   err = file.Write(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 
282780af0b9eSLuke Drummond   strm.Printf("Allocation written to file '%s'", path);
282855232f09SEwan Crawford   strm.EOL();
282915f2bd95SEwan Crawford   return true;
283015f2bd95SEwan Crawford }
283115f2bd95SEwan Crawford 
2832b9c1b51eSKate Stone bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
28334640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
28344640cde1SColin Riley 
2835b9c1b51eSKate Stone   if (module_sp) {
2836b9c1b51eSKate Stone     for (const auto &rs_module : m_rsmodules) {
2837b9c1b51eSKate Stone       if (rs_module->m_module == module_sp) {
28387dc7771cSEwan Crawford         // Check if the user has enabled automatically breaking on
28397dc7771cSEwan Crawford         // all RS kernels.
28407dc7771cSEwan Crawford         if (m_breakAllKernels)
28417dc7771cSEwan Crawford           BreakOnModuleKernels(rs_module);
28427dc7771cSEwan Crawford 
28435ec532a9SColin Riley         return false;
28445ec532a9SColin Riley       }
28457dc7771cSEwan Crawford     }
2846ef20b08fSColin Riley     bool module_loaded = false;
2847b9c1b51eSKate Stone     switch (GetModuleKind(module_sp)) {
2848b9c1b51eSKate Stone     case eModuleKindKernelObj: {
28494640cde1SColin Riley       RSModuleDescriptorSP module_desc;
28504640cde1SColin Riley       module_desc.reset(new RSModuleDescriptor(module_sp));
2851b9c1b51eSKate Stone       if (module_desc->ParseRSInfo()) {
28525ec532a9SColin Riley         m_rsmodules.push_back(module_desc);
2853ef20b08fSColin Riley         module_loaded = true;
28545ec532a9SColin Riley       }
2855b9c1b51eSKate Stone       if (module_loaded) {
28564640cde1SColin Riley         FixupScriptDetails(module_desc);
28574640cde1SColin Riley       }
2858ef20b08fSColin Riley       break;
2859ef20b08fSColin Riley     }
2860b9c1b51eSKate Stone     case eModuleKindDriver: {
2861b9c1b51eSKate Stone       if (!m_libRSDriver) {
28624640cde1SColin Riley         m_libRSDriver = module_sp;
28634640cde1SColin Riley         LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
28644640cde1SColin Riley       }
28654640cde1SColin Riley       break;
28664640cde1SColin Riley     }
2867b9c1b51eSKate Stone     case eModuleKindImpl: {
2868*21fed052SAidan Dodds       if (!m_libRSCpuRef) {
28694640cde1SColin Riley         m_libRSCpuRef = module_sp;
2870*21fed052SAidan Dodds         LoadRuntimeHooks(m_libRSCpuRef, RenderScriptRuntime::eModuleKindImpl);
2871*21fed052SAidan Dodds       }
28724640cde1SColin Riley       break;
28734640cde1SColin Riley     }
2874b9c1b51eSKate Stone     case eModuleKindLibRS: {
2875b9c1b51eSKate Stone       if (!m_libRS) {
28764640cde1SColin Riley         m_libRS = module_sp;
28774640cde1SColin Riley         static ConstString gDbgPresentStr("gDebuggerPresent");
2878b9c1b51eSKate Stone         const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2879b9c1b51eSKate Stone             gDbgPresentStr, eSymbolTypeData);
2880b9c1b51eSKate Stone         if (debug_present) {
288180af0b9eSLuke Drummond           Error err;
28824640cde1SColin Riley           uint32_t flag = 0x00000001U;
28834640cde1SColin Riley           Target &target = GetProcess()->GetTarget();
2884358cf1eaSGreg Clayton           addr_t addr = debug_present->GetLoadAddress(&target);
288580af0b9eSLuke Drummond           GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
288680af0b9eSLuke Drummond           if (err.Success()) {
28874640cde1SColin Riley             if (log)
2888b9c1b51eSKate Stone               log->Printf("%s - debugger present flag set on debugee.",
2889b9c1b51eSKate Stone                           __FUNCTION__);
28904640cde1SColin Riley 
28914640cde1SColin Riley             m_debuggerPresentFlagged = true;
2892b9c1b51eSKate Stone           } else if (log) {
2893b9c1b51eSKate Stone             log->Printf("%s - error writing debugger present flags '%s' ",
289480af0b9eSLuke Drummond                         __FUNCTION__, err.AsCString());
28954640cde1SColin Riley           }
2896b9c1b51eSKate Stone         } else if (log) {
2897b9c1b51eSKate Stone           log->Printf(
2898b9c1b51eSKate Stone               "%s - error writing debugger present flags - symbol not found",
2899b9c1b51eSKate Stone               __FUNCTION__);
29004640cde1SColin Riley         }
29014640cde1SColin Riley       }
29024640cde1SColin Riley       break;
29034640cde1SColin Riley     }
2904ef20b08fSColin Riley     default:
2905ef20b08fSColin Riley       break;
2906ef20b08fSColin Riley     }
2907ef20b08fSColin Riley     if (module_loaded)
2908ef20b08fSColin Riley       Update();
2909ef20b08fSColin Riley     return module_loaded;
29105ec532a9SColin Riley   }
29115ec532a9SColin Riley   return false;
29125ec532a9SColin Riley }
29135ec532a9SColin Riley 
2914b9c1b51eSKate Stone void RenderScriptRuntime::Update() {
2915b9c1b51eSKate Stone   if (m_rsmodules.size() > 0) {
2916b9c1b51eSKate Stone     if (!m_initiated) {
2917ef20b08fSColin Riley       Initiate();
2918ef20b08fSColin Riley     }
2919ef20b08fSColin Riley   }
2920ef20b08fSColin Riley }
2921ef20b08fSColin Riley 
29227f193d69SLuke Drummond bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
29237f193d69SLuke Drummond                                           size_t n_lines) {
29247f193d69SLuke Drummond   // Skip the pragma prototype line
29257f193d69SLuke Drummond   ++lines;
29267f193d69SLuke Drummond   for (; n_lines--; ++lines) {
29277f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
29287f193d69SLuke Drummond     m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
29297f193d69SLuke Drummond   }
29307f193d69SLuke Drummond   return true;
29317f193d69SLuke Drummond }
29327f193d69SLuke Drummond 
29337f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
29347f193d69SLuke Drummond                                                 size_t n_lines) {
29357f193d69SLuke Drummond   // The list of reduction kernels in the `.rs.info` symbol is of the form
29367f193d69SLuke Drummond   // "signature - accumulatordatasize - reduction_name - initializer_name -
29377f193d69SLuke Drummond   // accumulator_name - combiner_name -
29387f193d69SLuke Drummond   // outconverter_name - halter_name"
29397f193d69SLuke Drummond   // Where a function is not explicitly named by the user, or is not generated
29407f193d69SLuke Drummond   // by the compiler, it is named "." so the
29417f193d69SLuke Drummond   // dash separated list should always be 8 items long
29427f193d69SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
29437f193d69SLuke Drummond   // Skip the exportReduceCount line
29447f193d69SLuke Drummond   ++lines;
29457f193d69SLuke Drummond   for (; n_lines--; ++lines) {
29467f193d69SLuke Drummond     llvm::SmallVector<llvm::StringRef, 8> spec;
29477f193d69SLuke Drummond     lines->split(spec, " - ");
29487f193d69SLuke Drummond     if (spec.size() != 8) {
29497f193d69SLuke Drummond       if (spec.size() < 8) {
29507f193d69SLuke Drummond         if (log)
29517f193d69SLuke Drummond           log->Error("Error parsing RenderScript reduction spec. wrong number "
29527f193d69SLuke Drummond                      "of fields");
29537f193d69SLuke Drummond         return false;
29547f193d69SLuke Drummond       } else if (log)
29557f193d69SLuke Drummond         log->Warning("Extraneous members in reduction spec: '%s'",
29567f193d69SLuke Drummond                      lines->str().c_str());
29577f193d69SLuke Drummond     }
29587f193d69SLuke Drummond 
29597f193d69SLuke Drummond     const auto sig_s = spec[0];
29607f193d69SLuke Drummond     uint32_t sig;
29617f193d69SLuke Drummond     if (sig_s.getAsInteger(10, sig)) {
29627f193d69SLuke Drummond       if (log)
29637f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid kernel "
29647f193d69SLuke Drummond                    "signature: '%s'",
29657f193d69SLuke Drummond                    sig_s.str().c_str());
29667f193d69SLuke Drummond       return false;
29677f193d69SLuke Drummond     }
29687f193d69SLuke Drummond 
29697f193d69SLuke Drummond     const auto accum_data_size_s = spec[1];
29707f193d69SLuke Drummond     uint32_t accum_data_size;
29717f193d69SLuke Drummond     if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
29727f193d69SLuke Drummond       if (log)
29737f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid "
29747f193d69SLuke Drummond                    "accumulator data size %s",
29757f193d69SLuke Drummond                    accum_data_size_s.str().c_str());
29767f193d69SLuke Drummond       return false;
29777f193d69SLuke Drummond     }
29787f193d69SLuke Drummond 
29797f193d69SLuke Drummond     if (log)
29807f193d69SLuke Drummond       log->Printf("Found RenderScript reduction '%s'", spec[2].str().c_str());
29817f193d69SLuke Drummond 
29827f193d69SLuke Drummond     m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
29837f193d69SLuke Drummond                                                  spec[2], spec[3], spec[4],
29847f193d69SLuke Drummond                                                  spec[5], spec[6], spec[7]));
29857f193d69SLuke Drummond   }
29867f193d69SLuke Drummond   return true;
29877f193d69SLuke Drummond }
29887f193d69SLuke Drummond 
29897f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
29907f193d69SLuke Drummond                                                  size_t n_lines) {
29917f193d69SLuke Drummond   // Skip the exportForeachCount line
29927f193d69SLuke Drummond   ++lines;
29937f193d69SLuke Drummond   for (; n_lines--; ++lines) {
29947f193d69SLuke Drummond     uint32_t slot;
29957f193d69SLuke Drummond     // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
29967f193d69SLuke Drummond     // pair per line
29977f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
29987f193d69SLuke Drummond     if (kv_pair.first.getAsInteger(10, slot))
29997f193d69SLuke Drummond       return false;
30007f193d69SLuke Drummond     m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
30017f193d69SLuke Drummond   }
30027f193d69SLuke Drummond   return true;
30037f193d69SLuke Drummond }
30047f193d69SLuke Drummond 
30057f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
30067f193d69SLuke Drummond                                              size_t n_lines) {
30077f193d69SLuke Drummond   // Skip the ExportVarCount line
30087f193d69SLuke Drummond   ++lines;
30097f193d69SLuke Drummond   for (; n_lines--; ++lines)
30107f193d69SLuke Drummond     m_globals.push_back(RSGlobalDescriptor(this, *lines));
30117f193d69SLuke Drummond   return true;
30127f193d69SLuke Drummond }
30135ec532a9SColin Riley 
3014b9c1b51eSKate Stone // The .rs.info symbol in renderscript modules contains a string which needs to
3015b9c1b51eSKate Stone // be parsed.
30165ec532a9SColin Riley // The string is basic and is parsed on a line by line basis.
3017b9c1b51eSKate Stone bool RSModuleDescriptor::ParseRSInfo() {
3018b0be30f7SAidan Dodds   assert(m_module);
30197f193d69SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3020b9c1b51eSKate Stone   const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
3021b9c1b51eSKate Stone       ConstString(".rs.info"), eSymbolTypeData);
3022b0be30f7SAidan Dodds   if (!info_sym)
3023b0be30f7SAidan Dodds     return false;
3024b0be30f7SAidan Dodds 
3025358cf1eaSGreg Clayton   const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
3026b0be30f7SAidan Dodds   if (addr == LLDB_INVALID_ADDRESS)
3027b0be30f7SAidan Dodds     return false;
3028b0be30f7SAidan Dodds 
30295ec532a9SColin Riley   const addr_t size = info_sym->GetByteSize();
30305ec532a9SColin Riley   const FileSpec fs = m_module->GetFileSpec();
30315ec532a9SColin Riley 
3032b0be30f7SAidan Dodds   const DataBufferSP buffer = fs.ReadFileContents(addr, size);
30335ec532a9SColin Riley   if (!buffer)
30345ec532a9SColin Riley     return false;
30355ec532a9SColin Riley 
3036b0be30f7SAidan Dodds   // split rs.info. contents into lines
30377f193d69SLuke Drummond   llvm::SmallVector<llvm::StringRef, 128> info_lines;
30385ec532a9SColin Riley   {
30397f193d69SLuke Drummond     const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
30407f193d69SLuke Drummond     raw_rs_info.split(info_lines, '\n');
30417f193d69SLuke Drummond     if (log)
30427f193d69SLuke Drummond       log->Printf("'.rs.info symbol for '%s':\n%s",
30437f193d69SLuke Drummond                   m_module->GetFileSpec().GetCString(),
30447f193d69SLuke Drummond                   raw_rs_info.str().c_str());
3045b0be30f7SAidan Dodds   }
3046b0be30f7SAidan Dodds 
30477f193d69SLuke Drummond   enum {
30487f193d69SLuke Drummond     eExportVar,
30497f193d69SLuke Drummond     eExportForEach,
30507f193d69SLuke Drummond     eExportReduce,
30517f193d69SLuke Drummond     ePragma,
30527f193d69SLuke Drummond     eBuildChecksum,
30537f193d69SLuke Drummond     eObjectSlot
30547f193d69SLuke Drummond   };
30557f193d69SLuke Drummond 
3056b3bbcb12SLuke Drummond   const auto rs_info_handler = [](llvm::StringRef name) -> int {
3057b3bbcb12SLuke Drummond     return llvm::StringSwitch<int>(name)
3058b3bbcb12SLuke Drummond         // The number of visible global variables in the script
3059b3bbcb12SLuke Drummond         .Case("exportVarCount", eExportVar)
30607f193d69SLuke Drummond         // The number of RenderScrip `forEach` kernels __attribute__((kernel))
3061b3bbcb12SLuke Drummond         .Case("exportForEachCount", eExportForEach)
3062b3bbcb12SLuke Drummond         // The number of generalreductions: This marked in the script by
3063b3bbcb12SLuke Drummond         // `#pragma reduce()`
3064b3bbcb12SLuke Drummond         .Case("exportReduceCount", eExportReduce)
3065b3bbcb12SLuke Drummond         // Total count of all RenderScript specific `#pragmas` used in the
3066b3bbcb12SLuke Drummond         // script
3067b3bbcb12SLuke Drummond         .Case("pragmaCount", ePragma)
3068b3bbcb12SLuke Drummond         .Case("objectSlotCount", eObjectSlot)
3069b3bbcb12SLuke Drummond         .Default(-1);
3070b3bbcb12SLuke Drummond   };
3071b0be30f7SAidan Dodds 
3072b0be30f7SAidan Dodds   // parse all text lines of .rs.info
3073b9c1b51eSKate Stone   for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
30747f193d69SLuke Drummond     const auto kv_pair = line->split(": ");
30757f193d69SLuke Drummond     const auto key = kv_pair.first;
30767f193d69SLuke Drummond     const auto val = kv_pair.second.trim();
30775ec532a9SColin Riley 
3078b3bbcb12SLuke Drummond     const auto handler = rs_info_handler(key);
3079b3bbcb12SLuke Drummond     if (handler == -1)
30807f193d69SLuke Drummond       continue;
30817f193d69SLuke Drummond     // getAsInteger returns `true` on an error condition - we're only interested
3082b3bbcb12SLuke Drummond     // in numeric fields at the moment
30837f193d69SLuke Drummond     uint64_t n_lines;
30847f193d69SLuke Drummond     if (val.getAsInteger(10, n_lines)) {
30857f193d69SLuke Drummond       if (log)
30867f193d69SLuke Drummond         log->Debug("Failed to parse non-numeric '.rs.info' section %s",
30877f193d69SLuke Drummond                    line->str().c_str());
30887f193d69SLuke Drummond       continue;
30897f193d69SLuke Drummond     }
30907f193d69SLuke Drummond     if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
30917f193d69SLuke Drummond       return false;
30927f193d69SLuke Drummond 
30937f193d69SLuke Drummond     bool success = false;
3094b3bbcb12SLuke Drummond     switch (handler) {
30957f193d69SLuke Drummond     case eExportVar:
30967f193d69SLuke Drummond       success = ParseExportVarCount(line, n_lines);
30977f193d69SLuke Drummond       break;
30987f193d69SLuke Drummond     case eExportForEach:
30997f193d69SLuke Drummond       success = ParseExportForeachCount(line, n_lines);
31007f193d69SLuke Drummond       break;
31017f193d69SLuke Drummond     case eExportReduce:
31027f193d69SLuke Drummond       success = ParseExportReduceCount(line, n_lines);
31037f193d69SLuke Drummond       break;
31047f193d69SLuke Drummond     case ePragma:
31057f193d69SLuke Drummond       success = ParsePragmaCount(line, n_lines);
31067f193d69SLuke Drummond       break;
31077f193d69SLuke Drummond     default: {
31087f193d69SLuke Drummond       if (log)
31097f193d69SLuke Drummond         log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__,
31107f193d69SLuke Drummond                     line->str().c_str());
31117f193d69SLuke Drummond       continue;
31127f193d69SLuke Drummond     }
31137f193d69SLuke Drummond     }
31147f193d69SLuke Drummond     if (!success)
31157f193d69SLuke Drummond       return false;
31167f193d69SLuke Drummond     line += n_lines;
31177f193d69SLuke Drummond   }
31187f193d69SLuke Drummond   return info_lines.size() > 0;
31195ec532a9SColin Riley }
31205ec532a9SColin Riley 
3121b9c1b51eSKate Stone void RenderScriptRuntime::Status(Stream &strm) const {
3122b9c1b51eSKate Stone   if (m_libRS) {
31234640cde1SColin Riley     strm.Printf("Runtime Library discovered.");
31244640cde1SColin Riley     strm.EOL();
31254640cde1SColin Riley   }
3126b9c1b51eSKate Stone   if (m_libRSDriver) {
31274640cde1SColin Riley     strm.Printf("Runtime Driver discovered.");
31284640cde1SColin Riley     strm.EOL();
31294640cde1SColin Riley   }
3130b9c1b51eSKate Stone   if (m_libRSCpuRef) {
31314640cde1SColin Riley     strm.Printf("CPU Reference Implementation discovered.");
31324640cde1SColin Riley     strm.EOL();
31334640cde1SColin Riley   }
31344640cde1SColin Riley 
3135b9c1b51eSKate Stone   if (m_runtimeHooks.size()) {
31364640cde1SColin Riley     strm.Printf("Runtime functions hooked:");
31374640cde1SColin Riley     strm.EOL();
3138b9c1b51eSKate Stone     for (auto b : m_runtimeHooks) {
31394640cde1SColin Riley       strm.Indent(b.second->defn->name);
31404640cde1SColin Riley       strm.EOL();
31414640cde1SColin Riley     }
3142b9c1b51eSKate Stone   } else {
31434640cde1SColin Riley     strm.Printf("Runtime is not hooked.");
31444640cde1SColin Riley     strm.EOL();
31454640cde1SColin Riley   }
31464640cde1SColin Riley }
31474640cde1SColin Riley 
3148b9c1b51eSKate Stone void RenderScriptRuntime::DumpContexts(Stream &strm) const {
31494640cde1SColin Riley   strm.Printf("Inferred RenderScript Contexts:");
31504640cde1SColin Riley   strm.EOL();
31514640cde1SColin Riley   strm.IndentMore();
31524640cde1SColin Riley 
31534640cde1SColin Riley   std::map<addr_t, uint64_t> contextReferences;
31544640cde1SColin Riley 
315578f339d1SEwan Crawford   // Iterate over all of the currently discovered scripts.
3156b9c1b51eSKate Stone   // Note: We cant push or pop from m_scripts inside this loop or it may
3157b9c1b51eSKate Stone   // invalidate script.
3158b9c1b51eSKate Stone   for (const auto &script : m_scripts) {
315978f339d1SEwan Crawford     if (!script->context.isValid())
316078f339d1SEwan Crawford       continue;
316178f339d1SEwan Crawford     lldb::addr_t context = *script->context;
316278f339d1SEwan Crawford 
3163b9c1b51eSKate Stone     if (contextReferences.find(context) != contextReferences.end()) {
316478f339d1SEwan Crawford       contextReferences[context]++;
3165b9c1b51eSKate Stone     } else {
316678f339d1SEwan Crawford       contextReferences[context] = 1;
31674640cde1SColin Riley     }
31684640cde1SColin Riley   }
31694640cde1SColin Riley 
3170b9c1b51eSKate Stone   for (const auto &cRef : contextReferences) {
3171b9c1b51eSKate Stone     strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
3172b9c1b51eSKate Stone                 cRef.first, cRef.second);
31734640cde1SColin Riley     strm.EOL();
31744640cde1SColin Riley   }
31754640cde1SColin Riley   strm.IndentLess();
31764640cde1SColin Riley }
31774640cde1SColin Riley 
3178b9c1b51eSKate Stone void RenderScriptRuntime::DumpKernels(Stream &strm) const {
31794640cde1SColin Riley   strm.Printf("RenderScript Kernels:");
31804640cde1SColin Riley   strm.EOL();
31814640cde1SColin Riley   strm.IndentMore();
3182b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
31834640cde1SColin Riley     strm.Printf("Resource '%s':", module->m_resname.c_str());
31844640cde1SColin Riley     strm.EOL();
3185b9c1b51eSKate Stone     for (const auto &kernel : module->m_kernels) {
31864640cde1SColin Riley       strm.Indent(kernel.m_name.AsCString());
31874640cde1SColin Riley       strm.EOL();
31884640cde1SColin Riley     }
31894640cde1SColin Riley   }
31904640cde1SColin Riley   strm.IndentLess();
31914640cde1SColin Riley }
31924640cde1SColin Riley 
3193a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails *
3194b9c1b51eSKate Stone RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
3195a0f08674SEwan Crawford   AllocationDetails *alloc = nullptr;
3196a0f08674SEwan Crawford 
3197a0f08674SEwan Crawford   // See if we can find allocation using id as an index;
3198b9c1b51eSKate Stone   if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
3199b9c1b51eSKate Stone       m_allocations[alloc_id - 1]->id == alloc_id) {
3200a0f08674SEwan Crawford     alloc = m_allocations[alloc_id - 1].get();
3201a0f08674SEwan Crawford     return alloc;
3202a0f08674SEwan Crawford   }
3203a0f08674SEwan Crawford 
3204a0f08674SEwan Crawford   // Fallback to searching
3205b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
3206b9c1b51eSKate Stone     if (a->id == alloc_id) {
3207a0f08674SEwan Crawford       alloc = a.get();
3208a0f08674SEwan Crawford       break;
3209a0f08674SEwan Crawford     }
3210a0f08674SEwan Crawford   }
3211a0f08674SEwan Crawford 
3212b9c1b51eSKate Stone   if (alloc == nullptr) {
3213b9c1b51eSKate Stone     strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
3214b9c1b51eSKate Stone                 alloc_id);
3215a0f08674SEwan Crawford     strm.EOL();
3216a0f08674SEwan Crawford   }
3217a0f08674SEwan Crawford 
3218a0f08674SEwan Crawford   return alloc;
3219a0f08674SEwan Crawford }
3220a0f08674SEwan Crawford 
3221b9c1b51eSKate Stone // Prints the contents of an allocation to the output stream, which may be a
3222b9c1b51eSKate Stone // file
3223b9c1b51eSKate Stone bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
3224b9c1b51eSKate Stone                                          const uint32_t id) {
3225a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3226a0f08674SEwan Crawford 
3227a0f08674SEwan Crawford   // Check we can find the desired allocation
3228a0f08674SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, id);
3229a0f08674SEwan Crawford   if (!alloc)
3230a0f08674SEwan Crawford     return false; // FindAllocByID() will print error message for us here
3231a0f08674SEwan Crawford 
3232a0f08674SEwan Crawford   if (log)
3233b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
3234b9c1b51eSKate Stone                 *alloc->address.get());
3235a0f08674SEwan Crawford 
3236a0f08674SEwan Crawford   // Check we have information about the allocation, if not calculate it
323780af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
3238a0f08674SEwan Crawford     if (log)
3239b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
3240b9c1b51eSKate Stone                   __FUNCTION__);
3241a0f08674SEwan Crawford 
3242a0f08674SEwan Crawford     // JIT all the allocation information
3243b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
3244a0f08674SEwan Crawford       strm.Printf("Error: Couldn't JIT allocation details");
3245a0f08674SEwan Crawford       strm.EOL();
3246a0f08674SEwan Crawford       return false;
3247a0f08674SEwan Crawford     }
3248a0f08674SEwan Crawford   }
3249a0f08674SEwan Crawford 
3250a0f08674SEwan Crawford   // Establish format and size of each data element
3251b3f7f69dSAidan Dodds   const uint32_t vec_size = *alloc->element.type_vec_size.get();
32528b244e21SEwan Crawford   const Element::DataType type = *alloc->element.type.get();
3253a0f08674SEwan Crawford 
3254b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
3255b9c1b51eSKate Stone          "Invalid allocation type");
3256a0f08674SEwan Crawford 
32572e920715SEwan Crawford   lldb::Format format;
32582e920715SEwan Crawford   if (type >= Element::RS_TYPE_ELEMENT)
32592e920715SEwan Crawford     format = eFormatHex;
32602e920715SEwan Crawford   else
3261b9c1b51eSKate Stone     format = vec_size == 1
3262b9c1b51eSKate Stone                  ? static_cast<lldb::Format>(
3263b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatSingle])
3264b9c1b51eSKate Stone                  : static_cast<lldb::Format>(
3265b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatVector]);
3266a0f08674SEwan Crawford 
3267b3f7f69dSAidan Dodds   const uint32_t data_size = *alloc->element.datum_size.get();
3268a0f08674SEwan Crawford 
3269a0f08674SEwan Crawford   if (log)
3270b9c1b51eSKate Stone     log->Printf("%s - element size %" PRIu32 " bytes, including padding",
3271b9c1b51eSKate Stone                 __FUNCTION__, data_size);
3272a0f08674SEwan Crawford 
327355232f09SEwan Crawford   // Allocate a buffer to copy data into
327455232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3275b9c1b51eSKate Stone   if (!buffer) {
32762e920715SEwan Crawford     strm.Printf("Error: Couldn't read allocation data");
327755232f09SEwan Crawford     strm.EOL();
327855232f09SEwan Crawford     return false;
327955232f09SEwan Crawford   }
328055232f09SEwan Crawford 
3281a0f08674SEwan Crawford   // Calculate stride between rows as there may be padding at end of rows since
3282a0f08674SEwan Crawford   // allocated memory is 16-byte aligned
3283b9c1b51eSKate Stone   if (!alloc->stride.isValid()) {
3284a0f08674SEwan Crawford     if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
3285a0f08674SEwan Crawford       alloc->stride = 0;
3286b9c1b51eSKate Stone     else if (!JITAllocationStride(alloc, frame_ptr)) {
3287a0f08674SEwan Crawford       strm.Printf("Error: Couldn't calculate allocation row stride");
3288a0f08674SEwan Crawford       strm.EOL();
3289a0f08674SEwan Crawford       return false;
3290a0f08674SEwan Crawford     }
3291a0f08674SEwan Crawford   }
3292b3f7f69dSAidan Dodds   const uint32_t stride = *alloc->stride.get();
3293b3f7f69dSAidan Dodds   const uint32_t size = *alloc->size.get(); // Size of whole allocation
3294b9c1b51eSKate Stone   const uint32_t padding =
3295b9c1b51eSKate Stone       alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3296a0f08674SEwan Crawford   if (log)
3297b9c1b51eSKate Stone     log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32
3298b9c1b51eSKate Stone                 " bytes, padding %" PRIu32,
3299b3f7f69dSAidan Dodds                 __FUNCTION__, stride, size, padding);
3300a0f08674SEwan Crawford 
3301a0f08674SEwan Crawford   // Find dimensions used to index loops, so need to be non-zero
3302b3f7f69dSAidan Dodds   uint32_t dim_x = alloc->dimension.get()->dim_1;
3303a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 1 : dim_x;
3304a0f08674SEwan Crawford 
3305b3f7f69dSAidan Dodds   uint32_t dim_y = alloc->dimension.get()->dim_2;
3306a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 1 : dim_y;
3307a0f08674SEwan Crawford 
3308b3f7f69dSAidan Dodds   uint32_t dim_z = alloc->dimension.get()->dim_3;
3309a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 1 : dim_z;
3310a0f08674SEwan Crawford 
331155232f09SEwan Crawford   // Use data extractor to format output
331280af0b9eSLuke Drummond   const uint32_t target_ptr_size =
3313b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3314b9c1b51eSKate Stone   DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
331580af0b9eSLuke Drummond                            target_ptr_size);
331655232f09SEwan Crawford 
3317b3f7f69dSAidan Dodds   uint32_t offset = 0;   // Offset in buffer to next element to be printed
3318b3f7f69dSAidan Dodds   uint32_t prev_row = 0; // Offset to the start of the previous row
3319a0f08674SEwan Crawford 
3320a0f08674SEwan Crawford   // Iterate over allocation dimensions, printing results to user
3321a0f08674SEwan Crawford   strm.Printf("Data (X, Y, Z):");
3322b9c1b51eSKate Stone   for (uint32_t z = 0; z < dim_z; ++z) {
3323b9c1b51eSKate Stone     for (uint32_t y = 0; y < dim_y; ++y) {
3324a0f08674SEwan Crawford       // Use stride to index start of next row.
3325a0f08674SEwan Crawford       if (!(y == 0 && z == 0))
3326a0f08674SEwan Crawford         offset = prev_row + stride;
3327a0f08674SEwan Crawford       prev_row = offset;
3328a0f08674SEwan Crawford 
3329a0f08674SEwan Crawford       // Print each element in the row individually
3330b9c1b51eSKate Stone       for (uint32_t x = 0; x < dim_x; ++x) {
3331b3f7f69dSAidan Dodds         strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3332b9c1b51eSKate Stone         if ((type == Element::RS_TYPE_NONE) &&
3333b9c1b51eSKate Stone             (alloc->element.children.size() > 0) &&
3334b9c1b51eSKate Stone             (alloc->element.type_name != Element::GetFallbackStructName())) {
33358b244e21SEwan Crawford           // Here we are dumping an Element of struct type.
3336b9c1b51eSKate Stone           // This is done using expression evaluation with the name of the
3337b9c1b51eSKate Stone           // struct type and pointer to element.
3338b9c1b51eSKate Stone           // Don't print the name of the resulting expression, since this will
3339b9c1b51eSKate Stone           // be '$[0-9]+'
33408b244e21SEwan Crawford           DumpValueObjectOptions expr_options;
33418b244e21SEwan Crawford           expr_options.SetHideName(true);
33428b244e21SEwan Crawford 
33438b244e21SEwan Crawford           // Setup expression as derefrencing a pointer cast to element address.
3344ea0636b5SEwan Crawford           char expr_char_buffer[jit_max_expr_size];
334580af0b9eSLuke Drummond           int written =
3346b9c1b51eSKate Stone               snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3347b9c1b51eSKate Stone                        alloc->element.type_name.AsCString(),
3348b9c1b51eSKate Stone                        *alloc->data_ptr.get() + offset);
33498b244e21SEwan Crawford 
335080af0b9eSLuke Drummond           if (written < 0 || written >= jit_max_expr_size) {
33518b244e21SEwan Crawford             if (log)
3352b3f7f69dSAidan Dodds               log->Printf("%s - error in snprintf().", __FUNCTION__);
33538b244e21SEwan Crawford             continue;
33548b244e21SEwan Crawford           }
33558b244e21SEwan Crawford 
33568b244e21SEwan Crawford           // Evaluate expression
33578b244e21SEwan Crawford           ValueObjectSP expr_result;
3358b9c1b51eSKate Stone           GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3359b9c1b51eSKate Stone                                                        frame_ptr, expr_result);
33608b244e21SEwan Crawford 
33618b244e21SEwan Crawford           // Print the results to our stream.
33628b244e21SEwan Crawford           expr_result->Dump(strm, expr_options);
3363b9c1b51eSKate Stone         } else {
3364b9c1b51eSKate Stone           alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1,
3365b9c1b51eSKate Stone                           LLDB_INVALID_ADDRESS, 0, 0);
33668b244e21SEwan Crawford         }
33678b244e21SEwan Crawford         offset += data_size;
3368a0f08674SEwan Crawford       }
3369a0f08674SEwan Crawford     }
3370a0f08674SEwan Crawford   }
3371a0f08674SEwan Crawford   strm.EOL();
3372a0f08674SEwan Crawford 
3373a0f08674SEwan Crawford   return true;
3374a0f08674SEwan Crawford }
3375a0f08674SEwan Crawford 
3376b9c1b51eSKate Stone // Function recalculates all our cached information about allocations by jitting
337780af0b9eSLuke Drummond // the RS runtime regarding each allocation we know about. Returns true if all
337880af0b9eSLuke Drummond // allocations could be recomputed, false otherwise.
3379b9c1b51eSKate Stone bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3380b9c1b51eSKate Stone                                                   StackFrame *frame_ptr) {
33810d2bfcfbSEwan Crawford   bool success = true;
3382b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
33830d2bfcfbSEwan Crawford     // JIT current allocation information
3384b9c1b51eSKate Stone     if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3385b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3386b9c1b51eSKate Stone                   "\n",
3387b9c1b51eSKate Stone                   alloc->id);
33880d2bfcfbSEwan Crawford       success = false;
33890d2bfcfbSEwan Crawford     }
33900d2bfcfbSEwan Crawford   }
33910d2bfcfbSEwan Crawford 
33920d2bfcfbSEwan Crawford   if (success)
33930d2bfcfbSEwan Crawford     strm.Printf("All allocations successfully recomputed");
33940d2bfcfbSEwan Crawford   strm.EOL();
33950d2bfcfbSEwan Crawford 
33960d2bfcfbSEwan Crawford   return success;
33970d2bfcfbSEwan Crawford }
33980d2bfcfbSEwan Crawford 
339980af0b9eSLuke Drummond // Prints information regarding currently loaded allocations. These details are
340080af0b9eSLuke Drummond // gathered by jitting the runtime, which has as latency. Index parameter
340180af0b9eSLuke Drummond // specifies a single allocation ID to print, or a zero value to print them all
3402b9c1b51eSKate Stone void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3403b9c1b51eSKate Stone                                           const uint32_t index) {
340415f2bd95SEwan Crawford   strm.Printf("RenderScript Allocations:");
340515f2bd95SEwan Crawford   strm.EOL();
340615f2bd95SEwan Crawford   strm.IndentMore();
340715f2bd95SEwan Crawford 
3408b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
3409b649b005SEwan Crawford     // index will only be zero if we want to print all allocations
3410b649b005SEwan Crawford     if (index != 0 && index != alloc->id)
3411b649b005SEwan Crawford       continue;
341215f2bd95SEwan Crawford 
341315f2bd95SEwan Crawford     // JIT current allocation information
341480af0b9eSLuke Drummond     if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3415b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3416b9c1b51eSKate Stone                   alloc->id);
3417b3f7f69dSAidan Dodds       strm.EOL();
341815f2bd95SEwan Crawford       continue;
341915f2bd95SEwan Crawford     }
342015f2bd95SEwan Crawford 
3421b3f7f69dSAidan Dodds     strm.Printf("%" PRIu32 ":", alloc->id);
3422b3f7f69dSAidan Dodds     strm.EOL();
342315f2bd95SEwan Crawford     strm.IndentMore();
342415f2bd95SEwan Crawford 
342515f2bd95SEwan Crawford     strm.Indent("Context: ");
342615f2bd95SEwan Crawford     if (!alloc->context.isValid())
342715f2bd95SEwan Crawford       strm.Printf("unknown\n");
342815f2bd95SEwan Crawford     else
342915f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
343015f2bd95SEwan Crawford 
343115f2bd95SEwan Crawford     strm.Indent("Address: ");
343215f2bd95SEwan Crawford     if (!alloc->address.isValid())
343315f2bd95SEwan Crawford       strm.Printf("unknown\n");
343415f2bd95SEwan Crawford     else
343515f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
343615f2bd95SEwan Crawford 
343715f2bd95SEwan Crawford     strm.Indent("Data pointer: ");
343815f2bd95SEwan Crawford     if (!alloc->data_ptr.isValid())
343915f2bd95SEwan Crawford       strm.Printf("unknown\n");
344015f2bd95SEwan Crawford     else
344115f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
344215f2bd95SEwan Crawford 
344315f2bd95SEwan Crawford     strm.Indent("Dimensions: ");
344415f2bd95SEwan Crawford     if (!alloc->dimension.isValid())
344515f2bd95SEwan Crawford       strm.Printf("unknown\n");
344615f2bd95SEwan Crawford     else
3447b3f7f69dSAidan Dodds       strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3448b9c1b51eSKate Stone                   alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3449b9c1b51eSKate Stone                   alloc->dimension.get()->dim_3);
345015f2bd95SEwan Crawford 
345115f2bd95SEwan Crawford     strm.Indent("Data Type: ");
3452b9c1b51eSKate Stone     if (!alloc->element.type.isValid() ||
3453b9c1b51eSKate Stone         !alloc->element.type_vec_size.isValid())
345415f2bd95SEwan Crawford       strm.Printf("unknown\n");
3455b9c1b51eSKate Stone     else {
34568b244e21SEwan Crawford       const int vector_size = *alloc->element.type_vec_size.get();
34572e920715SEwan Crawford       Element::DataType type = *alloc->element.type.get();
345815f2bd95SEwan Crawford 
34598b244e21SEwan Crawford       if (!alloc->element.type_name.IsEmpty())
34608b244e21SEwan Crawford         strm.Printf("%s\n", alloc->element.type_name.AsCString());
3461b9c1b51eSKate Stone       else {
3462b9c1b51eSKate Stone         // Enum value isn't monotonous, so doesn't always index
3463b9c1b51eSKate Stone         // RsDataTypeToString array
34642e920715SEwan Crawford         if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3465b9c1b51eSKate Stone           type =
3466b9c1b51eSKate Stone               static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3467b3f7f69dSAidan Dodds                                              Element::RS_TYPE_MATRIX_2X2 + 1);
34682e920715SEwan Crawford 
3469b3f7f69dSAidan Dodds         if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3470b3f7f69dSAidan Dodds                      sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3471b3f7f69dSAidan Dodds             vector_size > 4 || vector_size < 1)
347215f2bd95SEwan Crawford           strm.Printf("invalid type\n");
347315f2bd95SEwan Crawford         else
3474b9c1b51eSKate Stone           strm.Printf(
3475b9c1b51eSKate Stone               "%s\n",
3476b9c1b51eSKate Stone               AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3477b3f7f69dSAidan Dodds                                                    [vector_size - 1]);
347815f2bd95SEwan Crawford       }
34792e920715SEwan Crawford     }
348015f2bd95SEwan Crawford 
348115f2bd95SEwan Crawford     strm.Indent("Data Kind: ");
34828b244e21SEwan Crawford     if (!alloc->element.type_kind.isValid())
348315f2bd95SEwan Crawford       strm.Printf("unknown\n");
3484b9c1b51eSKate Stone     else {
34858b244e21SEwan Crawford       const Element::DataKind kind = *alloc->element.type_kind.get();
34868b244e21SEwan Crawford       if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
348715f2bd95SEwan Crawford         strm.Printf("invalid kind\n");
348815f2bd95SEwan Crawford       else
3489b9c1b51eSKate Stone         strm.Printf(
3490b9c1b51eSKate Stone             "%s\n",
3491b9c1b51eSKate Stone             AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
349215f2bd95SEwan Crawford     }
349315f2bd95SEwan Crawford 
349415f2bd95SEwan Crawford     strm.EOL();
349515f2bd95SEwan Crawford     strm.IndentLess();
349615f2bd95SEwan Crawford   }
349715f2bd95SEwan Crawford   strm.IndentLess();
349815f2bd95SEwan Crawford }
349915f2bd95SEwan Crawford 
35007dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
3501b9c1b51eSKate Stone void RenderScriptRuntime::BreakOnModuleKernels(
3502b9c1b51eSKate Stone     const RSModuleDescriptorSP rsmodule_sp) {
3503b9c1b51eSKate Stone   for (const auto &kernel : rsmodule_sp->m_kernels) {
35047dc7771cSEwan Crawford     // Don't set breakpoint on 'root' kernel
35057dc7771cSEwan Crawford     if (strcmp(kernel.m_name.AsCString(), "root") == 0)
35067dc7771cSEwan Crawford       continue;
35077dc7771cSEwan Crawford 
35087dc7771cSEwan Crawford     CreateKernelBreakpoint(kernel.m_name);
35097dc7771cSEwan Crawford   }
35107dc7771cSEwan Crawford }
35117dc7771cSEwan Crawford 
351280af0b9eSLuke Drummond // Method is internally called by the 'kernel breakpoint all' command to enable
351380af0b9eSLuke Drummond // or disable breaking on all kernels. When do_break is true we want to enable
351480af0b9eSLuke Drummond // this functionality. When do_break is false we want to disable it.
3515b9c1b51eSKate Stone void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3516b9c1b51eSKate Stone   Log *log(
3517b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
35187dc7771cSEwan Crawford 
35197dc7771cSEwan Crawford   InitSearchFilter(target);
35207dc7771cSEwan Crawford 
35217dc7771cSEwan Crawford   // Set breakpoints on all the kernels
3522b9c1b51eSKate Stone   if (do_break && !m_breakAllKernels) {
35237dc7771cSEwan Crawford     m_breakAllKernels = true;
35247dc7771cSEwan Crawford 
35257dc7771cSEwan Crawford     for (const auto &module : m_rsmodules)
35267dc7771cSEwan Crawford       BreakOnModuleKernels(module);
35277dc7771cSEwan Crawford 
35287dc7771cSEwan Crawford     if (log)
3529b9c1b51eSKate Stone       log->Printf("%s(True) - breakpoints set on all currently loaded kernels.",
3530b9c1b51eSKate Stone                   __FUNCTION__);
3531b9c1b51eSKate Stone   } else if (!do_break &&
3532b9c1b51eSKate Stone              m_breakAllKernels) // Breakpoints won't be set on any new kernels.
35337dc7771cSEwan Crawford   {
35347dc7771cSEwan Crawford     m_breakAllKernels = false;
35357dc7771cSEwan Crawford 
35367dc7771cSEwan Crawford     if (log)
3537b9c1b51eSKate Stone       log->Printf("%s(False) - breakpoints no longer automatically set.",
3538b9c1b51eSKate Stone                   __FUNCTION__);
35397dc7771cSEwan Crawford   }
35407dc7771cSEwan Crawford }
35417dc7771cSEwan Crawford 
35427dc7771cSEwan Crawford // Given the name of a kernel this function creates a breakpoint using our
35437dc7771cSEwan Crawford // own breakpoint resolver, and returns the Breakpoint shared pointer.
35447dc7771cSEwan Crawford BreakpointSP
3545b9c1b51eSKate Stone RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) {
3546b9c1b51eSKate Stone   Log *log(
3547b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
35487dc7771cSEwan Crawford 
3549b9c1b51eSKate Stone   if (!m_filtersp) {
35507dc7771cSEwan Crawford     if (log)
3551b3f7f69dSAidan Dodds       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
35527dc7771cSEwan Crawford     return nullptr;
35537dc7771cSEwan Crawford   }
35547dc7771cSEwan Crawford 
35557dc7771cSEwan Crawford   BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3556b9c1b51eSKate Stone   BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
3557b9c1b51eSKate Stone       m_filtersp, resolver_sp, false, false, false);
35587dc7771cSEwan Crawford 
3559b9c1b51eSKate Stone   // Give RS breakpoints a specific name, so the user can manipulate them as a
3560b9c1b51eSKate Stone   // group.
356154782db7SEwan Crawford   Error err;
3562b3bbcb12SLuke Drummond   if (!bp->AddName("RenderScriptKernel", err))
3563b3bbcb12SLuke Drummond     if (log)
3564b3bbcb12SLuke Drummond       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3565b3bbcb12SLuke Drummond                   err.AsCString());
3566b3bbcb12SLuke Drummond 
3567b3bbcb12SLuke Drummond   return bp;
3568b3bbcb12SLuke Drummond }
3569b3bbcb12SLuke Drummond 
3570b3bbcb12SLuke Drummond BreakpointSP
3571b3bbcb12SLuke Drummond RenderScriptRuntime::CreateReductionBreakpoint(const ConstString &name,
3572b3bbcb12SLuke Drummond                                                int kernel_types) {
3573b3bbcb12SLuke Drummond   Log *log(
3574b3bbcb12SLuke Drummond       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3575b3bbcb12SLuke Drummond 
3576b3bbcb12SLuke Drummond   if (!m_filtersp) {
3577b3bbcb12SLuke Drummond     if (log)
3578b3bbcb12SLuke Drummond       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3579b3bbcb12SLuke Drummond     return nullptr;
3580b3bbcb12SLuke Drummond   }
3581b3bbcb12SLuke Drummond 
3582b3bbcb12SLuke Drummond   BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3583b3bbcb12SLuke Drummond       nullptr, name, &m_rsmodules, kernel_types));
3584b3bbcb12SLuke Drummond   BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
3585b3bbcb12SLuke Drummond       m_filtersp, resolver_sp, false, false, false);
3586b3bbcb12SLuke Drummond 
3587b3bbcb12SLuke Drummond   // Give RS breakpoints a specific name, so the user can manipulate them as a
3588b3bbcb12SLuke Drummond   // group.
3589b3bbcb12SLuke Drummond   Error err;
3590b3bbcb12SLuke Drummond   if (!bp->AddName("RenderScriptReduction", err))
3591b3bbcb12SLuke Drummond     if (log)
3592b9c1b51eSKate Stone       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3593b9c1b51eSKate Stone                   err.AsCString());
359454782db7SEwan Crawford 
35957dc7771cSEwan Crawford   return bp;
35967dc7771cSEwan Crawford }
35977dc7771cSEwan Crawford 
3598b9c1b51eSKate Stone // Given an expression for a variable this function tries to calculate the
359980af0b9eSLuke Drummond // variable's value. If this is possible it returns true and sets the uint64_t
360080af0b9eSLuke Drummond // parameter to the variables unsigned value. Otherwise function returns false.
3601b9c1b51eSKate Stone bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3602b9c1b51eSKate Stone                                                 const char *var_name,
3603b9c1b51eSKate Stone                                                 uint64_t &val) {
3604018f5a7eSEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
360580af0b9eSLuke Drummond   Error err;
3606018f5a7eSEwan Crawford   VariableSP var_sp;
3607018f5a7eSEwan Crawford 
3608018f5a7eSEwan Crawford   // Find variable in stack frame
3609b3f7f69dSAidan Dodds   ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3610b3f7f69dSAidan Dodds       var_name, eNoDynamicValues,
3611b9c1b51eSKate Stone       StackFrame::eExpressionPathOptionCheckPtrVsMember |
3612b9c1b51eSKate Stone           StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
361380af0b9eSLuke Drummond       var_sp, err));
361480af0b9eSLuke Drummond   if (!err.Success()) {
3615018f5a7eSEwan Crawford     if (log)
3616b9c1b51eSKate Stone       log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__,
3617b9c1b51eSKate Stone                   var_name);
3618018f5a7eSEwan Crawford     return false;
3619018f5a7eSEwan Crawford   }
3620018f5a7eSEwan Crawford 
3621b3f7f69dSAidan Dodds   // Find the uint32_t value for the variable
3622018f5a7eSEwan Crawford   bool success = false;
3623018f5a7eSEwan Crawford   val = value_sp->GetValueAsUnsigned(0, &success);
3624b9c1b51eSKate Stone   if (!success) {
3625018f5a7eSEwan Crawford     if (log)
3626b9c1b51eSKate Stone       log->Printf("%s - error, couldn't parse '%s' as an uint32_t.",
3627b9c1b51eSKate Stone                   __FUNCTION__, var_name);
3628018f5a7eSEwan Crawford     return false;
3629018f5a7eSEwan Crawford   }
3630018f5a7eSEwan Crawford 
3631018f5a7eSEwan Crawford   return true;
3632018f5a7eSEwan Crawford }
3633018f5a7eSEwan Crawford 
3634b9c1b51eSKate Stone // Function attempts to find the current coordinate of a kernel invocation by
363580af0b9eSLuke Drummond // investigating the values of frame variables in the .expand function. These
363680af0b9eSLuke Drummond // coordinates are returned via the coord array reference parameter. Returns
363780af0b9eSLuke Drummond // true if the coordinates could be found, and false otherwise.
3638b9c1b51eSKate Stone bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3639b9c1b51eSKate Stone                                               Thread *thread_ptr) {
364000f56eebSLuke Drummond   static const char *const x_expr = "rsIndex";
364100f56eebSLuke Drummond   static const char *const y_expr = "p->current.y";
364200f56eebSLuke Drummond   static const char *const z_expr = "p->current.z";
36431e05c3bcSGreg Clayton 
36444f8817c2SEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
36454f8817c2SEwan Crawford 
3646b9c1b51eSKate Stone   if (!thread_ptr) {
36474f8817c2SEwan Crawford     if (log)
36484f8817c2SEwan Crawford       log->Printf("%s - Error, No thread pointer", __FUNCTION__);
36494f8817c2SEwan Crawford 
36504f8817c2SEwan Crawford     return false;
36514f8817c2SEwan Crawford   }
36524f8817c2SEwan Crawford 
3653b9c1b51eSKate Stone   // Walk the call stack looking for a function whose name has the suffix
365480af0b9eSLuke Drummond   // '.expand' and contains the variables we're looking for.
3655b9c1b51eSKate Stone   for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
36564f8817c2SEwan Crawford     if (!thread_ptr->SetSelectedFrameByIndex(i))
36574f8817c2SEwan Crawford       continue;
36584f8817c2SEwan Crawford 
36594f8817c2SEwan Crawford     StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
36604f8817c2SEwan Crawford     if (!frame_sp)
36614f8817c2SEwan Crawford       continue;
36624f8817c2SEwan Crawford 
36634f8817c2SEwan Crawford     // Find the function name
36644f8817c2SEwan Crawford     const SymbolContext sym_ctx = frame_sp->GetSymbolContext(false);
366500f56eebSLuke Drummond     const ConstString func_name = sym_ctx.GetFunctionName();
366600f56eebSLuke Drummond     if (!func_name)
36674f8817c2SEwan Crawford       continue;
36684f8817c2SEwan Crawford 
36694f8817c2SEwan Crawford     if (log)
3670b9c1b51eSKate Stone       log->Printf("%s - Inspecting function '%s'", __FUNCTION__,
367100f56eebSLuke Drummond                   func_name.GetCString());
36724f8817c2SEwan Crawford 
36734f8817c2SEwan Crawford     // Check if function name has .expand suffix
367400f56eebSLuke Drummond     if (!func_name.GetStringRef().endswith(".expand"))
36754f8817c2SEwan Crawford       continue;
36764f8817c2SEwan Crawford 
36774f8817c2SEwan Crawford     if (log)
3678b9c1b51eSKate Stone       log->Printf("%s - Found .expand function '%s'", __FUNCTION__,
367900f56eebSLuke Drummond                   func_name.GetCString());
36804f8817c2SEwan Crawford 
3681b9c1b51eSKate Stone     // Get values for variables in .expand frame that tell us the current kernel
3682b9c1b51eSKate Stone     // invocation
368300f56eebSLuke Drummond     uint64_t x, y, z;
368400f56eebSLuke Drummond     bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
368500f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
368600f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, z_expr, z);
36874f8817c2SEwan Crawford 
368800f56eebSLuke Drummond     if (found) {
368900f56eebSLuke Drummond       // The RenderScript runtime uses uint32_t for these vars. If they're not
369000f56eebSLuke Drummond       // within bounds, our frame parsing is garbage
369100f56eebSLuke Drummond       assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
369200f56eebSLuke Drummond       coord.x = (uint32_t)x;
369300f56eebSLuke Drummond       coord.y = (uint32_t)y;
369400f56eebSLuke Drummond       coord.z = (uint32_t)z;
36954f8817c2SEwan Crawford       return true;
36964f8817c2SEwan Crawford     }
369700f56eebSLuke Drummond   }
36984f8817c2SEwan Crawford   return false;
36994f8817c2SEwan Crawford }
37004f8817c2SEwan Crawford 
3701b9c1b51eSKate Stone // Callback when a kernel breakpoint hits and we're looking for a specific
370280af0b9eSLuke Drummond // coordinate. Baton parameter contains a pointer to the target coordinate we
370380af0b9eSLuke Drummond // want to break on.
3704b9c1b51eSKate Stone // Function then checks the .expand frame for the current coordinate and breaks
3705b9c1b51eSKate Stone // to user if it matches.
3706018f5a7eSEwan Crawford // Parameter 'break_id' is the id of the Breakpoint which made the callback.
3707018f5a7eSEwan Crawford // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
3708018f5a7eSEwan Crawford // a single logical breakpoint can have multiple addresses.
3709b9c1b51eSKate Stone bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3710b9c1b51eSKate Stone                                               StoppointCallbackContext *ctx,
3711b9c1b51eSKate Stone                                               user_id_t break_id,
3712b9c1b51eSKate Stone                                               user_id_t break_loc_id) {
3713b9c1b51eSKate Stone   Log *log(
3714b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3715018f5a7eSEwan Crawford 
3716b9c1b51eSKate Stone   assert(baton &&
3717b9c1b51eSKate Stone          "Error: null baton in conditional kernel breakpoint callback");
3718018f5a7eSEwan Crawford 
3719018f5a7eSEwan Crawford   // Coordinate we want to stop on
372000f56eebSLuke Drummond   RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3721018f5a7eSEwan Crawford 
3722018f5a7eSEwan Crawford   if (log)
372300f56eebSLuke Drummond     log->Printf("%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__, break_id,
372400f56eebSLuke Drummond                 target_coord.x, target_coord.y, target_coord.z);
3725018f5a7eSEwan Crawford 
37264f8817c2SEwan Crawford   // Select current thread
3727018f5a7eSEwan Crawford   ExecutionContext context(ctx->exe_ctx_ref);
37284f8817c2SEwan Crawford   Thread *thread_ptr = context.GetThreadPtr();
37294f8817c2SEwan Crawford   assert(thread_ptr && "Null thread pointer");
37304f8817c2SEwan Crawford 
37314f8817c2SEwan Crawford   // Find current kernel invocation from .expand frame variables
373200f56eebSLuke Drummond   RSCoordinate current_coord{};
3733b9c1b51eSKate Stone   if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3734018f5a7eSEwan Crawford     if (log)
3735b9c1b51eSKate Stone       log->Printf("%s - Error, couldn't select .expand stack frame",
3736b9c1b51eSKate Stone                   __FUNCTION__);
3737018f5a7eSEwan Crawford     return false;
3738018f5a7eSEwan Crawford   }
3739018f5a7eSEwan Crawford 
3740018f5a7eSEwan Crawford   if (log)
374100f56eebSLuke Drummond     log->Printf("%s - " FMT_COORD, __FUNCTION__, current_coord.x,
374200f56eebSLuke Drummond                 current_coord.y, current_coord.z);
3743018f5a7eSEwan Crawford 
3744b9c1b51eSKate Stone   // Check if the current kernel invocation coordinate matches our target
3745b9c1b51eSKate Stone   // coordinate
374600f56eebSLuke Drummond   if (target_coord == current_coord) {
3747018f5a7eSEwan Crawford     if (log)
374800f56eebSLuke Drummond       log->Printf("%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
374900f56eebSLuke Drummond                   current_coord.y, current_coord.z);
3750018f5a7eSEwan Crawford 
3751b9c1b51eSKate Stone     BreakpointSP breakpoint_sp =
3752b9c1b51eSKate Stone         context.GetTargetPtr()->GetBreakpointByID(break_id);
3753b9c1b51eSKate Stone     assert(breakpoint_sp != nullptr &&
3754b9c1b51eSKate Stone            "Error: Couldn't find breakpoint matching break id for callback");
3755b9c1b51eSKate Stone     breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3756b9c1b51eSKate Stone                                       // should only be hit once.
3757018f5a7eSEwan Crawford     return true;
3758018f5a7eSEwan Crawford   }
3759018f5a7eSEwan Crawford 
3760018f5a7eSEwan Crawford   // No match on coordinate
3761018f5a7eSEwan Crawford   return false;
3762018f5a7eSEwan Crawford }
3763018f5a7eSEwan Crawford 
376400f56eebSLuke Drummond void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
376500f56eebSLuke Drummond                                          const RSCoordinate &coord) {
376600f56eebSLuke Drummond   messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
376700f56eebSLuke Drummond                   coord.x, coord.y, coord.z);
376800f56eebSLuke Drummond   messages.EOL();
376900f56eebSLuke Drummond 
377000f56eebSLuke Drummond   // Allocate memory for the baton, and copy over coordinate
377100f56eebSLuke Drummond   RSCoordinate *baton = new RSCoordinate(coord);
377200f56eebSLuke Drummond 
377300f56eebSLuke Drummond   // Create a callback that will be invoked every time the breakpoint is hit.
377400f56eebSLuke Drummond   // The baton object passed to the handler is the target coordinate we want to
377500f56eebSLuke Drummond   // break on.
377600f56eebSLuke Drummond   bp->SetCallback(KernelBreakpointHit, baton, true);
377700f56eebSLuke Drummond 
377800f56eebSLuke Drummond   // Store a shared pointer to the baton, so the memory will eventually be
377900f56eebSLuke Drummond   // cleaned up after destruction
378000f56eebSLuke Drummond   m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
378100f56eebSLuke Drummond }
378200f56eebSLuke Drummond 
3783b9c1b51eSKate Stone // Tries to set a breakpoint on the start of a kernel, resolved using the kernel
378480af0b9eSLuke Drummond // name. Argument 'coords', represents a three dimensional coordinate which can
378580af0b9eSLuke Drummond // be
378680af0b9eSLuke Drummond // used to specify a single kernel instance to break on. If this is set then we
378780af0b9eSLuke Drummond // add a callback
3788b9c1b51eSKate Stone // to the breakpoint.
378900f56eebSLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
379000f56eebSLuke Drummond                                                   Stream &messages,
379100f56eebSLuke Drummond                                                   const char *name,
379200f56eebSLuke Drummond                                                   const RSCoordinate *coord) {
379300f56eebSLuke Drummond   if (!name)
379400f56eebSLuke Drummond     return false;
37954640cde1SColin Riley 
37967dc7771cSEwan Crawford   InitSearchFilter(target);
379798156583SEwan Crawford 
37984640cde1SColin Riley   ConstString kernel_name(name);
37997dc7771cSEwan Crawford   BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
380000f56eebSLuke Drummond   if (!bp)
380100f56eebSLuke Drummond     return false;
3802018f5a7eSEwan Crawford 
3803018f5a7eSEwan Crawford   // We have a conditional breakpoint on a specific coordinate
380400f56eebSLuke Drummond   if (coord)
380500f56eebSLuke Drummond     SetConditional(bp, messages, *coord);
3806018f5a7eSEwan Crawford 
380700f56eebSLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3808018f5a7eSEwan Crawford 
380900f56eebSLuke Drummond   return true;
38104640cde1SColin Riley }
38114640cde1SColin Riley 
3812*21fed052SAidan Dodds BreakpointSP
3813*21fed052SAidan Dodds RenderScriptRuntime::CreateScriptGroupBreakpoint(const ConstString &name,
3814*21fed052SAidan Dodds                                                  bool stop_on_all) {
3815*21fed052SAidan Dodds   Log *log(
3816*21fed052SAidan Dodds       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3817*21fed052SAidan Dodds 
3818*21fed052SAidan Dodds   if (!m_filtersp) {
3819*21fed052SAidan Dodds     if (log)
3820*21fed052SAidan Dodds       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3821*21fed052SAidan Dodds     return nullptr;
3822*21fed052SAidan Dodds   }
3823*21fed052SAidan Dodds 
3824*21fed052SAidan Dodds   BreakpointResolverSP resolver_sp(new RSScriptGroupBreakpointResolver(
3825*21fed052SAidan Dodds       nullptr, name, m_scriptGroups, stop_on_all));
3826*21fed052SAidan Dodds   BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
3827*21fed052SAidan Dodds       m_filtersp, resolver_sp, false, false, false);
3828*21fed052SAidan Dodds   // Give RS breakpoints a specific name, so the user can manipulate them as a
3829*21fed052SAidan Dodds   // group.
3830*21fed052SAidan Dodds   Error err;
3831*21fed052SAidan Dodds   if (!bp->AddName(name.AsCString(), err))
3832*21fed052SAidan Dodds     if (log)
3833*21fed052SAidan Dodds       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3834*21fed052SAidan Dodds                   err.AsCString());
3835*21fed052SAidan Dodds   // ask the breakpoint to resolve itself
3836*21fed052SAidan Dodds   bp->ResolveBreakpoint();
3837*21fed052SAidan Dodds   return bp;
3838*21fed052SAidan Dodds }
3839*21fed052SAidan Dodds 
3840*21fed052SAidan Dodds bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target,
3841*21fed052SAidan Dodds                                                        Stream &strm,
3842*21fed052SAidan Dodds                                                        const ConstString &name,
3843*21fed052SAidan Dodds                                                        bool multi) {
3844*21fed052SAidan Dodds   InitSearchFilter(target);
3845*21fed052SAidan Dodds   BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi);
3846*21fed052SAidan Dodds   if (bp)
3847*21fed052SAidan Dodds     bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
3848*21fed052SAidan Dodds   return bool(bp);
3849*21fed052SAidan Dodds }
3850*21fed052SAidan Dodds 
3851b3bbcb12SLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3852b3bbcb12SLuke Drummond                                                      Stream &messages,
3853b3bbcb12SLuke Drummond                                                      const char *reduce_name,
3854b3bbcb12SLuke Drummond                                                      const RSCoordinate *coord,
3855b3bbcb12SLuke Drummond                                                      int kernel_types) {
3856b3bbcb12SLuke Drummond   if (!reduce_name)
3857b3bbcb12SLuke Drummond     return false;
3858b3bbcb12SLuke Drummond 
3859b3bbcb12SLuke Drummond   InitSearchFilter(target);
3860b3bbcb12SLuke Drummond   BreakpointSP bp =
3861b3bbcb12SLuke Drummond       CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3862b3bbcb12SLuke Drummond   if (!bp)
3863b3bbcb12SLuke Drummond     return false;
3864b3bbcb12SLuke Drummond 
3865b3bbcb12SLuke Drummond   if (coord)
3866b3bbcb12SLuke Drummond     SetConditional(bp, messages, *coord);
3867b3bbcb12SLuke Drummond 
3868b3bbcb12SLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3869b3bbcb12SLuke Drummond 
3870b3bbcb12SLuke Drummond   return true;
3871b3bbcb12SLuke Drummond }
3872b3bbcb12SLuke Drummond 
3873b9c1b51eSKate Stone void RenderScriptRuntime::DumpModules(Stream &strm) const {
38745ec532a9SColin Riley   strm.Printf("RenderScript Modules:");
38755ec532a9SColin Riley   strm.EOL();
38765ec532a9SColin Riley   strm.IndentMore();
3877b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
38784640cde1SColin Riley     module->Dump(strm);
38795ec532a9SColin Riley   }
38805ec532a9SColin Riley   strm.IndentLess();
38815ec532a9SColin Riley }
38825ec532a9SColin Riley 
388378f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails *
3884b9c1b51eSKate Stone RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3885b9c1b51eSKate Stone   for (const auto &s : m_scripts) {
388678f339d1SEwan Crawford     if (s->script.isValid())
388778f339d1SEwan Crawford       if (*s->script == address)
388878f339d1SEwan Crawford         return s.get();
388978f339d1SEwan Crawford   }
3890b9c1b51eSKate Stone   if (create) {
389178f339d1SEwan Crawford     std::unique_ptr<ScriptDetails> s(new ScriptDetails);
389278f339d1SEwan Crawford     s->script = address;
389378f339d1SEwan Crawford     m_scripts.push_back(std::move(s));
3894d10ca9deSEwan Crawford     return m_scripts.back().get();
389578f339d1SEwan Crawford   }
389678f339d1SEwan Crawford   return nullptr;
389778f339d1SEwan Crawford }
389878f339d1SEwan Crawford 
389978f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails *
3900b9c1b51eSKate Stone RenderScriptRuntime::LookUpAllocation(addr_t address) {
3901b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
390278f339d1SEwan Crawford     if (a->address.isValid())
390378f339d1SEwan Crawford       if (*a->address == address)
390478f339d1SEwan Crawford         return a.get();
390578f339d1SEwan Crawford   }
39065d057637SLuke Drummond   return nullptr;
39075d057637SLuke Drummond }
39085d057637SLuke Drummond 
39095d057637SLuke Drummond RenderScriptRuntime::AllocationDetails *
3910b9c1b51eSKate Stone RenderScriptRuntime::CreateAllocation(addr_t address) {
39115d057637SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
39125d057637SLuke Drummond 
39135d057637SLuke Drummond   // Remove any previous allocation which contains the same address
39145d057637SLuke Drummond   auto it = m_allocations.begin();
3915b9c1b51eSKate Stone   while (it != m_allocations.end()) {
3916b9c1b51eSKate Stone     if (*((*it)->address) == address) {
39175d057637SLuke Drummond       if (log)
3918b9c1b51eSKate Stone         log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64,
3919b9c1b51eSKate Stone                     __FUNCTION__, (*it)->id, address);
39205d057637SLuke Drummond 
39215d057637SLuke Drummond       it = m_allocations.erase(it);
3922b9c1b51eSKate Stone     } else {
39235d057637SLuke Drummond       it++;
39245d057637SLuke Drummond     }
39255d057637SLuke Drummond   }
39265d057637SLuke Drummond 
392778f339d1SEwan Crawford   std::unique_ptr<AllocationDetails> a(new AllocationDetails);
392878f339d1SEwan Crawford   a->address = address;
392978f339d1SEwan Crawford   m_allocations.push_back(std::move(a));
3930d10ca9deSEwan Crawford   return m_allocations.back().get();
393178f339d1SEwan Crawford }
393278f339d1SEwan Crawford 
3933*21fed052SAidan Dodds bool RenderScriptRuntime::ResolveKernelName(lldb::addr_t kernel_addr,
3934*21fed052SAidan Dodds                                             ConstString &name) {
3935*21fed052SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
3936*21fed052SAidan Dodds 
3937*21fed052SAidan Dodds   Target &target = GetProcess()->GetTarget();
3938*21fed052SAidan Dodds   Address resolved;
3939*21fed052SAidan Dodds   // RenderScript module
3940*21fed052SAidan Dodds   if (!target.GetSectionLoadList().ResolveLoadAddress(kernel_addr, resolved)) {
3941*21fed052SAidan Dodds     if (log)
3942*21fed052SAidan Dodds       log->Printf("%s: unable to resolve 0x%" PRIx64 " to a loaded symbol",
3943*21fed052SAidan Dodds                   __FUNCTION__, kernel_addr);
3944*21fed052SAidan Dodds     return false;
3945*21fed052SAidan Dodds   }
3946*21fed052SAidan Dodds 
3947*21fed052SAidan Dodds   Symbol *sym = resolved.CalculateSymbolContextSymbol();
3948*21fed052SAidan Dodds   if (!sym)
3949*21fed052SAidan Dodds     return false;
3950*21fed052SAidan Dodds 
3951*21fed052SAidan Dodds   name = sym->GetName();
3952*21fed052SAidan Dodds   assert(IsRenderScriptModule(resolved.CalculateSymbolContextModule()));
3953*21fed052SAidan Dodds   if (log)
3954*21fed052SAidan Dodds     log->Printf("%s: 0x%" PRIx64 " resolved to the symbol '%s'", __FUNCTION__,
3955*21fed052SAidan Dodds                 kernel_addr, name.GetCString());
3956*21fed052SAidan Dodds   return true;
3957*21fed052SAidan Dodds }
3958*21fed052SAidan Dodds 
3959b9c1b51eSKate Stone void RSModuleDescriptor::Dump(Stream &strm) const {
39607f193d69SLuke Drummond   int indent = strm.GetIndentLevel();
39617f193d69SLuke Drummond 
39625ec532a9SColin Riley   strm.Indent();
39635ec532a9SColin Riley   m_module->GetFileSpec().Dump(&strm);
39647f193d69SLuke Drummond   strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
39657f193d69SLuke Drummond                                              : "Debug info does not exist.");
39665ec532a9SColin Riley   strm.EOL();
39675ec532a9SColin Riley   strm.IndentMore();
39687f193d69SLuke Drummond 
39695ec532a9SColin Riley   strm.Indent();
3970189598edSColin Riley   strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
39715ec532a9SColin Riley   strm.EOL();
39725ec532a9SColin Riley   strm.IndentMore();
3973b9c1b51eSKate Stone   for (const auto &global : m_globals) {
39745ec532a9SColin Riley     global.Dump(strm);
39755ec532a9SColin Riley   }
39765ec532a9SColin Riley   strm.IndentLess();
39777f193d69SLuke Drummond 
39785ec532a9SColin Riley   strm.Indent();
3979189598edSColin Riley   strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
39805ec532a9SColin Riley   strm.EOL();
39815ec532a9SColin Riley   strm.IndentMore();
3982b9c1b51eSKate Stone   for (const auto &kernel : m_kernels) {
39835ec532a9SColin Riley     kernel.Dump(strm);
39845ec532a9SColin Riley   }
39857f193d69SLuke Drummond   strm.IndentLess();
39867f193d69SLuke Drummond 
39877f193d69SLuke Drummond   strm.Indent();
39884640cde1SColin Riley   strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
39894640cde1SColin Riley   strm.EOL();
39904640cde1SColin Riley   strm.IndentMore();
3991b9c1b51eSKate Stone   for (const auto &key_val : m_pragmas) {
39927f193d69SLuke Drummond     strm.Indent();
39934640cde1SColin Riley     strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
39944640cde1SColin Riley     strm.EOL();
39954640cde1SColin Riley   }
39967f193d69SLuke Drummond   strm.IndentLess();
39977f193d69SLuke Drummond 
39987f193d69SLuke Drummond   strm.Indent();
39997f193d69SLuke Drummond   strm.Printf("Reductions: %" PRIu64,
40007f193d69SLuke Drummond               static_cast<uint64_t>(m_reductions.size()));
40017f193d69SLuke Drummond   strm.EOL();
40027f193d69SLuke Drummond   strm.IndentMore();
40037f193d69SLuke Drummond   for (const auto &reduction : m_reductions) {
40047f193d69SLuke Drummond     reduction.Dump(strm);
40057f193d69SLuke Drummond   }
40067f193d69SLuke Drummond 
40077f193d69SLuke Drummond   strm.SetIndentLevel(indent);
40085ec532a9SColin Riley }
40095ec532a9SColin Riley 
4010b9c1b51eSKate Stone void RSGlobalDescriptor::Dump(Stream &strm) const {
40115ec532a9SColin Riley   strm.Indent(m_name.AsCString());
40124640cde1SColin Riley   VariableList var_list;
40134640cde1SColin Riley   m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
4014b9c1b51eSKate Stone   if (var_list.GetSize() == 1) {
40154640cde1SColin Riley     auto var = var_list.GetVariableAtIndex(0);
40164640cde1SColin Riley     auto type = var->GetType();
4017b9c1b51eSKate Stone     if (type) {
40184640cde1SColin Riley       strm.Printf(" - ");
40194640cde1SColin Riley       type->DumpTypeName(&strm);
4020b9c1b51eSKate Stone     } else {
40214640cde1SColin Riley       strm.Printf(" - Unknown Type");
40224640cde1SColin Riley     }
4023b9c1b51eSKate Stone   } else {
40244640cde1SColin Riley     strm.Printf(" - variable identified, but not found in binary");
4025b9c1b51eSKate Stone     const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
4026b9c1b51eSKate Stone         m_name, eSymbolTypeData);
4027b9c1b51eSKate Stone     if (s) {
40284640cde1SColin Riley       strm.Printf(" (symbol exists) ");
40294640cde1SColin Riley     }
40304640cde1SColin Riley   }
40314640cde1SColin Riley 
40325ec532a9SColin Riley   strm.EOL();
40335ec532a9SColin Riley }
40345ec532a9SColin Riley 
4035b9c1b51eSKate Stone void RSKernelDescriptor::Dump(Stream &strm) const {
40365ec532a9SColin Riley   strm.Indent(m_name.AsCString());
40375ec532a9SColin Riley   strm.EOL();
40385ec532a9SColin Riley }
40395ec532a9SColin Riley 
40407f193d69SLuke Drummond void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
40417f193d69SLuke Drummond   stream.Indent(m_reduce_name.AsCString());
40427f193d69SLuke Drummond   stream.IndentMore();
40437f193d69SLuke Drummond   stream.EOL();
40447f193d69SLuke Drummond   stream.Indent();
40457f193d69SLuke Drummond   stream.Printf("accumulator: %s", m_accum_name.AsCString());
40467f193d69SLuke Drummond   stream.EOL();
40477f193d69SLuke Drummond   stream.Indent();
40487f193d69SLuke Drummond   stream.Printf("initializer: %s", m_init_name.AsCString());
40497f193d69SLuke Drummond   stream.EOL();
40507f193d69SLuke Drummond   stream.Indent();
40517f193d69SLuke Drummond   stream.Printf("combiner: %s", m_comb_name.AsCString());
40527f193d69SLuke Drummond   stream.EOL();
40537f193d69SLuke Drummond   stream.Indent();
40547f193d69SLuke Drummond   stream.Printf("outconverter: %s", m_outc_name.AsCString());
40557f193d69SLuke Drummond   stream.EOL();
40567f193d69SLuke Drummond   // XXX This is currently unspecified by RenderScript, and unused
40577f193d69SLuke Drummond   // stream.Indent();
40587f193d69SLuke Drummond   // stream.Printf("halter: '%s'", m_init_name.AsCString());
40597f193d69SLuke Drummond   // stream.EOL();
40607f193d69SLuke Drummond   stream.IndentLess();
40617f193d69SLuke Drummond }
40627f193d69SLuke Drummond 
4063b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
40645ec532a9SColin Riley public:
40655ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
4066b9c1b51eSKate Stone       : CommandObjectParsed(
4067b9c1b51eSKate Stone             interpreter, "renderscript module dump",
4068b9c1b51eSKate Stone             "Dumps renderscript specific information for all modules.",
4069b9c1b51eSKate Stone             "renderscript module dump",
4070b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
40715ec532a9SColin Riley 
4072222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
40735ec532a9SColin Riley 
4074b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
40755ec532a9SColin Riley     RenderScriptRuntime *runtime =
4076b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4077b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
40785ec532a9SColin Riley     runtime->DumpModules(result.GetOutputStream());
40795ec532a9SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
40805ec532a9SColin Riley     return true;
40815ec532a9SColin Riley   }
40825ec532a9SColin Riley };
40835ec532a9SColin Riley 
4084b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
40855ec532a9SColin Riley public:
40865ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
4087b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript module",
4088b9c1b51eSKate Stone                                "Commands that deal with RenderScript modules.",
4089b9c1b51eSKate Stone                                nullptr) {
4090b9c1b51eSKate Stone     LoadSubCommand(
4091b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
4092b9c1b51eSKate Stone                     interpreter)));
40935ec532a9SColin Riley   }
40945ec532a9SColin Riley 
4095222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModule() override = default;
40965ec532a9SColin Riley };
40975ec532a9SColin Riley 
4098b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
40994640cde1SColin Riley public:
41004640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
4101b9c1b51eSKate Stone       : CommandObjectParsed(
4102b9c1b51eSKate Stone             interpreter, "renderscript kernel list",
4103b3f7f69dSAidan Dodds             "Lists renderscript kernel names and associated script resources.",
4104b9c1b51eSKate Stone             "renderscript kernel list",
4105b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
41064640cde1SColin Riley 
4107222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelList() override = default;
41084640cde1SColin Riley 
4109b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
41104640cde1SColin Riley     RenderScriptRuntime *runtime =
4111b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4112b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
41134640cde1SColin Riley     runtime->DumpKernels(result.GetOutputStream());
41144640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
41154640cde1SColin Riley     return true;
41164640cde1SColin Riley   }
41174640cde1SColin Riley };
41184640cde1SColin Riley 
4119b3bbcb12SLuke Drummond static OptionDefinition g_renderscript_reduction_bp_set_options[] = {
4120b3bbcb12SLuke Drummond     {LLDB_OPT_SET_1, false, "function-role", 't',
4121b3bbcb12SLuke Drummond      OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOneLiner,
4122b3bbcb12SLuke Drummond      "Break on a comma separated set of reduction kernel types "
4123b3bbcb12SLuke Drummond      "(accumulator,outcoverter,combiner,initializer"},
4124b3bbcb12SLuke Drummond     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4125b3bbcb12SLuke Drummond      nullptr, nullptr, 0, eArgTypeValue,
4126b3bbcb12SLuke Drummond      "Set a breakpoint on a single invocation of the kernel with specified "
4127b3bbcb12SLuke Drummond      "coordinate.\n"
4128b3bbcb12SLuke Drummond      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4129b3bbcb12SLuke Drummond      "integers representing kernel dimensions. "
4130b3bbcb12SLuke Drummond      "Any unset dimensions will be defaulted to zero."}};
4131b3bbcb12SLuke Drummond 
4132b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReductionBreakpointSet
4133b3bbcb12SLuke Drummond     : public CommandObjectParsed {
4134b3bbcb12SLuke Drummond public:
4135b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4136b3bbcb12SLuke Drummond       CommandInterpreter &interpreter)
4137b3bbcb12SLuke Drummond       : CommandObjectParsed(
4138b3bbcb12SLuke Drummond             interpreter, "renderscript reduction breakpoint set",
4139b3bbcb12SLuke Drummond             "Set a breakpoint on named RenderScript general reductions",
4140b3bbcb12SLuke Drummond             "renderscript reduction breakpoint set  <kernel_name> [-t "
4141b3bbcb12SLuke Drummond             "<reduction_kernel_type,...>]",
4142b3bbcb12SLuke Drummond             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4143b3bbcb12SLuke Drummond                 eCommandProcessMustBePaused),
4144b3bbcb12SLuke Drummond         m_options(){};
4145b3bbcb12SLuke Drummond 
4146b3bbcb12SLuke Drummond   class CommandOptions : public Options {
4147b3bbcb12SLuke Drummond   public:
4148b3bbcb12SLuke Drummond     CommandOptions()
4149b3bbcb12SLuke Drummond         : Options(),
4150b3bbcb12SLuke Drummond           m_kernel_types(RSReduceBreakpointResolver::eKernelTypeAll) {}
4151b3bbcb12SLuke Drummond 
4152b3bbcb12SLuke Drummond     ~CommandOptions() override = default;
4153b3bbcb12SLuke Drummond 
4154b3bbcb12SLuke Drummond     Error SetOptionValue(uint32_t option_idx, const char *option_val,
4155b3bbcb12SLuke Drummond                          ExecutionContext *exe_ctx) override {
4156b3bbcb12SLuke Drummond       Error err;
4157b3bbcb12SLuke Drummond       StreamString err_str;
4158b3bbcb12SLuke Drummond       const int short_option = m_getopt_table[option_idx].val;
4159b3bbcb12SLuke Drummond       switch (short_option) {
4160b3bbcb12SLuke Drummond       case 't':
4161b3bbcb12SLuke Drummond         if (!ParseReductionTypes(option_val, err_str))
4162b3bbcb12SLuke Drummond           err.SetErrorStringWithFormat(
4163b3bbcb12SLuke Drummond               "Unable to deduce reduction types for %s: %s", option_val,
4164b3bbcb12SLuke Drummond               err_str.GetData());
4165b3bbcb12SLuke Drummond         break;
4166b3bbcb12SLuke Drummond       case 'c': {
4167b3bbcb12SLuke Drummond         auto coord = RSCoordinate{};
4168b3bbcb12SLuke Drummond         if (!ParseCoordinate(option_val, coord))
4169b3bbcb12SLuke Drummond           err.SetErrorStringWithFormat("unable to parse coordinate for %s",
4170b3bbcb12SLuke Drummond                                        option_val);
4171b3bbcb12SLuke Drummond         else {
4172b3bbcb12SLuke Drummond           m_have_coord = true;
4173b3bbcb12SLuke Drummond           m_coord = coord;
4174b3bbcb12SLuke Drummond         }
4175b3bbcb12SLuke Drummond         break;
4176b3bbcb12SLuke Drummond       }
4177b3bbcb12SLuke Drummond       default:
4178b3bbcb12SLuke Drummond         err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
4179b3bbcb12SLuke Drummond       }
4180b3bbcb12SLuke Drummond       return err;
4181b3bbcb12SLuke Drummond     }
4182b3bbcb12SLuke Drummond 
4183b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4184b3bbcb12SLuke Drummond       m_have_coord = false;
4185b3bbcb12SLuke Drummond     }
4186b3bbcb12SLuke Drummond 
4187b3bbcb12SLuke Drummond     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4188b3bbcb12SLuke Drummond       return llvm::makeArrayRef(g_renderscript_reduction_bp_set_options);
4189b3bbcb12SLuke Drummond     }
4190b3bbcb12SLuke Drummond 
4191b3bbcb12SLuke Drummond     bool ParseReductionTypes(const char *option_val, StreamString &err_str) {
4192b3bbcb12SLuke Drummond       m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
4193b3bbcb12SLuke Drummond       const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
4194b3bbcb12SLuke Drummond         return llvm::StringSwitch<int>(name)
4195b3bbcb12SLuke Drummond             .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
4196b3bbcb12SLuke Drummond             .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
4197b3bbcb12SLuke Drummond             .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
4198b3bbcb12SLuke Drummond             .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
4199b3bbcb12SLuke Drummond             .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
4200b3bbcb12SLuke Drummond             // Currently not exposed by the runtime
4201b3bbcb12SLuke Drummond             // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
4202b3bbcb12SLuke Drummond             .Default(0);
4203b3bbcb12SLuke Drummond       };
4204b3bbcb12SLuke Drummond 
4205b3bbcb12SLuke Drummond       // Matching a comma separated list of known words is fairly
4206b3bbcb12SLuke Drummond       // straightforward with PCRE, but we're
4207b3bbcb12SLuke Drummond       // using ERE, so we end up with a little ugliness...
4208b3bbcb12SLuke Drummond       RegularExpression::Match match(/* max_matches */ 5);
4209b3bbcb12SLuke Drummond       RegularExpression match_type_list(
4210b3bbcb12SLuke Drummond           llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
4211b3bbcb12SLuke Drummond 
4212b3bbcb12SLuke Drummond       assert(match_type_list.IsValid());
4213b3bbcb12SLuke Drummond 
4214b3bbcb12SLuke Drummond       if (!match_type_list.Execute(llvm::StringRef(option_val), &match)) {
4215b3bbcb12SLuke Drummond         err_str.PutCString(
4216b3bbcb12SLuke Drummond             "a comma-separated list of kernel types is required");
4217b3bbcb12SLuke Drummond         return false;
4218b3bbcb12SLuke Drummond       }
4219b3bbcb12SLuke Drummond 
4220b3bbcb12SLuke Drummond       // splitting on commas is much easier with llvm::StringRef than regex
4221b3bbcb12SLuke Drummond       llvm::SmallVector<llvm::StringRef, 5> type_names;
4222b3bbcb12SLuke Drummond       llvm::StringRef(option_val).split(type_names, ',');
4223b3bbcb12SLuke Drummond 
4224b3bbcb12SLuke Drummond       for (const auto &name : type_names) {
4225b3bbcb12SLuke Drummond         const int type = reduce_name_to_type(name);
4226b3bbcb12SLuke Drummond         if (!type) {
4227b3bbcb12SLuke Drummond           err_str.Printf("unknown kernel type name %s", name.str().c_str());
4228b3bbcb12SLuke Drummond           return false;
4229b3bbcb12SLuke Drummond         }
4230b3bbcb12SLuke Drummond         m_kernel_types |= type;
4231b3bbcb12SLuke Drummond       }
4232b3bbcb12SLuke Drummond 
4233b3bbcb12SLuke Drummond       return true;
4234b3bbcb12SLuke Drummond     }
4235b3bbcb12SLuke Drummond 
4236b3bbcb12SLuke Drummond     int m_kernel_types;
4237b3bbcb12SLuke Drummond     llvm::StringRef m_reduce_name;
4238b3bbcb12SLuke Drummond     RSCoordinate m_coord;
4239b3bbcb12SLuke Drummond     bool m_have_coord;
4240b3bbcb12SLuke Drummond   };
4241b3bbcb12SLuke Drummond 
4242b3bbcb12SLuke Drummond   Options *GetOptions() override { return &m_options; }
4243b3bbcb12SLuke Drummond 
4244b3bbcb12SLuke Drummond   bool DoExecute(Args &command, CommandReturnObject &result) override {
4245b3bbcb12SLuke Drummond     const size_t argc = command.GetArgumentCount();
4246b3bbcb12SLuke Drummond     if (argc < 1) {
4247b3bbcb12SLuke Drummond       result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
4248b3bbcb12SLuke Drummond                                    "and an optional kernel type list",
4249b3bbcb12SLuke Drummond                                    m_cmd_name.c_str());
4250b3bbcb12SLuke Drummond       result.SetStatus(eReturnStatusFailed);
4251b3bbcb12SLuke Drummond       return false;
4252b3bbcb12SLuke Drummond     }
4253b3bbcb12SLuke Drummond 
4254b3bbcb12SLuke Drummond     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4255b3bbcb12SLuke Drummond         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4256b3bbcb12SLuke Drummond             eLanguageTypeExtRenderScript));
4257b3bbcb12SLuke Drummond 
4258b3bbcb12SLuke Drummond     auto &outstream = result.GetOutputStream();
4259b3bbcb12SLuke Drummond     auto name = command.GetArgumentAtIndex(0);
4260b3bbcb12SLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
4261b3bbcb12SLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4262b3bbcb12SLuke Drummond     if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
4263b3bbcb12SLuke Drummond                                              m_options.m_kernel_types)) {
4264b3bbcb12SLuke Drummond       result.SetStatus(eReturnStatusFailed);
4265b3bbcb12SLuke Drummond       result.AppendError("Error: unable to place breakpoint on reduction");
4266b3bbcb12SLuke Drummond       return false;
4267b3bbcb12SLuke Drummond     }
4268b3bbcb12SLuke Drummond     result.AppendMessage("Breakpoint(s) created");
4269b3bbcb12SLuke Drummond     result.SetStatus(eReturnStatusSuccessFinishResult);
4270b3bbcb12SLuke Drummond     return true;
4271b3bbcb12SLuke Drummond   }
4272b3bbcb12SLuke Drummond 
4273b3bbcb12SLuke Drummond private:
4274b3bbcb12SLuke Drummond   CommandOptions m_options;
4275b3bbcb12SLuke Drummond };
4276b3bbcb12SLuke Drummond 
42771f0f5b5bSZachary Turner static OptionDefinition g_renderscript_kernel_bp_set_options[] = {
42781f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
42791f0f5b5bSZachary Turner      nullptr, nullptr, 0, eArgTypeValue,
42801f0f5b5bSZachary Turner      "Set a breakpoint on a single invocation of the kernel with specified "
42811f0f5b5bSZachary Turner      "coordinate.\n"
42821f0f5b5bSZachary Turner      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
42831f0f5b5bSZachary Turner      "integers representing kernel dimensions. "
42841f0f5b5bSZachary Turner      "Any unset dimensions will be defaulted to zero."}};
42851f0f5b5bSZachary Turner 
4286b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointSet
4287b9c1b51eSKate Stone     : public CommandObjectParsed {
42884640cde1SColin Riley public:
4289b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4290b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4291b9c1b51eSKate Stone       : CommandObjectParsed(
4292b9c1b51eSKate Stone             interpreter, "renderscript kernel breakpoint set",
4293b3f7f69dSAidan Dodds             "Sets a breakpoint on a renderscript kernel.",
4294b3f7f69dSAidan Dodds             "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
4295b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4296b9c1b51eSKate Stone                 eCommandProcessMustBePaused),
4297b9c1b51eSKate Stone         m_options() {}
42984640cde1SColin Riley 
4299222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
4300222b937cSEugene Zelenko 
4301b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
4302018f5a7eSEwan Crawford 
4303b9c1b51eSKate Stone   class CommandOptions : public Options {
4304018f5a7eSEwan Crawford   public:
4305e1cfbc79STodd Fiala     CommandOptions() : Options() {}
4306018f5a7eSEwan Crawford 
4307222b937cSEugene Zelenko     ~CommandOptions() override = default;
4308018f5a7eSEwan Crawford 
4309b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
4310b3bbcb12SLuke Drummond                          ExecutionContext *exe_ctx) override {
431180af0b9eSLuke Drummond       Error err;
4312018f5a7eSEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
4313018f5a7eSEwan Crawford 
4314b9c1b51eSKate Stone       switch (short_option) {
431500f56eebSLuke Drummond       case 'c': {
431600f56eebSLuke Drummond         auto coord = RSCoordinate{};
431700f56eebSLuke Drummond         if (!ParseCoordinate(option_arg, coord))
431880af0b9eSLuke Drummond           err.SetErrorStringWithFormat(
4319b9c1b51eSKate Stone               "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
4320b3f7f69dSAidan Dodds               option_arg);
432100f56eebSLuke Drummond         else {
432200f56eebSLuke Drummond           m_have_coord = true;
432300f56eebSLuke Drummond           m_coord = coord;
432400f56eebSLuke Drummond         }
4325018f5a7eSEwan Crawford         break;
432600f56eebSLuke Drummond       }
4327018f5a7eSEwan Crawford       default:
432880af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4329018f5a7eSEwan Crawford         break;
4330018f5a7eSEwan Crawford       }
433180af0b9eSLuke Drummond       return err;
4332018f5a7eSEwan Crawford     }
4333018f5a7eSEwan Crawford 
4334b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
433500f56eebSLuke Drummond       m_have_coord = false;
4336018f5a7eSEwan Crawford     }
4337018f5a7eSEwan Crawford 
43381f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
433970602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
43401f0f5b5bSZachary Turner     }
4341018f5a7eSEwan Crawford 
434200f56eebSLuke Drummond     RSCoordinate m_coord;
434300f56eebSLuke Drummond     bool m_have_coord;
4344018f5a7eSEwan Crawford   };
4345018f5a7eSEwan Crawford 
4346b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
43474640cde1SColin Riley     const size_t argc = command.GetArgumentCount();
4348b9c1b51eSKate Stone     if (argc < 1) {
4349b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4350b9c1b51eSKate Stone           "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4351b3f7f69dSAidan Dodds           m_cmd_name.c_str());
4352018f5a7eSEwan Crawford       result.SetStatus(eReturnStatusFailed);
4353018f5a7eSEwan Crawford       return false;
4354018f5a7eSEwan Crawford     }
4355018f5a7eSEwan Crawford 
43564640cde1SColin Riley     RenderScriptRuntime *runtime =
4357b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4358b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
43594640cde1SColin Riley 
436000f56eebSLuke Drummond     auto &outstream = result.GetOutputStream();
436100f56eebSLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
436200f56eebSLuke Drummond     auto name = command.GetArgumentAtIndex(0);
436300f56eebSLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
436400f56eebSLuke Drummond     if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
436500f56eebSLuke Drummond       result.SetStatus(eReturnStatusFailed);
436600f56eebSLuke Drummond       result.AppendErrorWithFormat(
436700f56eebSLuke Drummond           "Error: unable to set breakpoint on kernel '%s'", name);
436800f56eebSLuke Drummond       return false;
436900f56eebSLuke Drummond     }
43704640cde1SColin Riley 
43714640cde1SColin Riley     result.AppendMessage("Breakpoint(s) created");
43724640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
43734640cde1SColin Riley     return true;
43744640cde1SColin Riley   }
43754640cde1SColin Riley 
4376018f5a7eSEwan Crawford private:
4377018f5a7eSEwan Crawford   CommandOptions m_options;
43784640cde1SColin Riley };
43794640cde1SColin Riley 
4380b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4381b9c1b51eSKate Stone     : public CommandObjectParsed {
43827dc7771cSEwan Crawford public:
4383b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4384b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4385b3f7f69dSAidan Dodds       : CommandObjectParsed(
4386b3f7f69dSAidan Dodds             interpreter, "renderscript kernel breakpoint all",
4387b9c1b51eSKate Stone             "Automatically sets a breakpoint on all renderscript kernels that "
4388b9c1b51eSKate Stone             "are or will be loaded.\n"
4389b9c1b51eSKate Stone             "Disabling option means breakpoints will no longer be set on any "
4390b9c1b51eSKate Stone             "kernels loaded in the future, "
43917dc7771cSEwan Crawford             "but does not remove currently set breakpoints.",
43927dc7771cSEwan Crawford             "renderscript kernel breakpoint all <enable/disable>",
4393b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4394b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
43957dc7771cSEwan Crawford 
4396222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
43977dc7771cSEwan Crawford 
4398b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
43997dc7771cSEwan Crawford     const size_t argc = command.GetArgumentCount();
4400b9c1b51eSKate Stone     if (argc != 1) {
4401b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4402b9c1b51eSKate Stone           "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
44037dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
44047dc7771cSEwan Crawford       return false;
44057dc7771cSEwan Crawford     }
44067dc7771cSEwan Crawford 
4407b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4408b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4409b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
44107dc7771cSEwan Crawford 
44117dc7771cSEwan Crawford     bool do_break = false;
44127dc7771cSEwan Crawford     const char *argument = command.GetArgumentAtIndex(0);
4413b9c1b51eSKate Stone     if (strcmp(argument, "enable") == 0) {
44147dc7771cSEwan Crawford       do_break = true;
44157dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will be set on all kernels.");
4416b9c1b51eSKate Stone     } else if (strcmp(argument, "disable") == 0) {
44177dc7771cSEwan Crawford       do_break = false;
44187dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will not be set on any new kernels.");
4419b9c1b51eSKate Stone     } else {
4420b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4421b9c1b51eSKate Stone           "Argument must be either 'enable' or 'disable'");
44227dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
44237dc7771cSEwan Crawford       return false;
44247dc7771cSEwan Crawford     }
44257dc7771cSEwan Crawford 
44267dc7771cSEwan Crawford     runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
44277dc7771cSEwan Crawford 
44287dc7771cSEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
44297dc7771cSEwan Crawford     return true;
44307dc7771cSEwan Crawford   }
44317dc7771cSEwan Crawford };
44327dc7771cSEwan Crawford 
4433b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReductionBreakpoint
4434b3bbcb12SLuke Drummond     : public CommandObjectMultiword {
4435b3bbcb12SLuke Drummond public:
4436b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReductionBreakpoint(
4437b3bbcb12SLuke Drummond       CommandInterpreter &interpreter)
4438b3bbcb12SLuke Drummond       : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4439b3bbcb12SLuke Drummond                                "Commands that manipulate breakpoints on "
4440b3bbcb12SLuke Drummond                                "renderscript general reductions.",
4441b3bbcb12SLuke Drummond                                nullptr) {
4442b3bbcb12SLuke Drummond     LoadSubCommand(
4443b3bbcb12SLuke Drummond         "set", CommandObjectSP(
4444b3bbcb12SLuke Drummond                    new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4445b3bbcb12SLuke Drummond                        interpreter)));
4446b3bbcb12SLuke Drummond   }
4447b3bbcb12SLuke Drummond 
4448b3bbcb12SLuke Drummond   ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4449b3bbcb12SLuke Drummond };
4450b3bbcb12SLuke Drummond 
4451b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelCoordinate
4452b9c1b51eSKate Stone     : public CommandObjectParsed {
44534f8817c2SEwan Crawford public:
4454b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelCoordinate(
4455b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4456b9c1b51eSKate Stone       : CommandObjectParsed(
4457b9c1b51eSKate Stone             interpreter, "renderscript kernel coordinate",
44584f8817c2SEwan Crawford             "Shows the (x,y,z) coordinate of the current kernel invocation.",
44594f8817c2SEwan Crawford             "renderscript kernel coordinate",
4460b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4461b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
44624f8817c2SEwan Crawford 
44634f8817c2SEwan Crawford   ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
44644f8817c2SEwan Crawford 
4465b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
446600f56eebSLuke Drummond     RSCoordinate coord{};
4467b9c1b51eSKate Stone     bool success = RenderScriptRuntime::GetKernelCoordinate(
4468b9c1b51eSKate Stone         coord, m_exe_ctx.GetThreadPtr());
44694f8817c2SEwan Crawford     Stream &stream = result.GetOutputStream();
44704f8817c2SEwan Crawford 
4471b9c1b51eSKate Stone     if (success) {
447200f56eebSLuke Drummond       stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
44734f8817c2SEwan Crawford       stream.EOL();
44744f8817c2SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4475b9c1b51eSKate Stone     } else {
44764f8817c2SEwan Crawford       stream.Printf("Error: Coordinate could not be found.");
44774f8817c2SEwan Crawford       stream.EOL();
44784f8817c2SEwan Crawford       result.SetStatus(eReturnStatusFailed);
44794f8817c2SEwan Crawford     }
44804f8817c2SEwan Crawford     return true;
44814f8817c2SEwan Crawford   }
44824f8817c2SEwan Crawford };
44834f8817c2SEwan Crawford 
4484b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpoint
4485b9c1b51eSKate Stone     : public CommandObjectMultiword {
44867dc7771cSEwan Crawford public:
4487b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpoint(
4488b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4489b9c1b51eSKate Stone       : CommandObjectMultiword(
4490b9c1b51eSKate Stone             interpreter, "renderscript kernel",
4491b9c1b51eSKate Stone             "Commands that generate breakpoints on renderscript kernels.",
4492b9c1b51eSKate Stone             nullptr) {
4493b9c1b51eSKate Stone     LoadSubCommand(
4494b9c1b51eSKate Stone         "set",
4495b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4496b9c1b51eSKate Stone             interpreter)));
4497b9c1b51eSKate Stone     LoadSubCommand(
4498b9c1b51eSKate Stone         "all",
4499b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4500b9c1b51eSKate Stone             interpreter)));
45017dc7771cSEwan Crawford   }
45027dc7771cSEwan Crawford 
4503222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
45047dc7771cSEwan Crawford };
45057dc7771cSEwan Crawford 
4506b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
45074640cde1SColin Riley public:
45084640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4509b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript kernel",
4510b9c1b51eSKate Stone                                "Commands that deal with RenderScript kernels.",
4511b9c1b51eSKate Stone                                nullptr) {
4512b9c1b51eSKate Stone     LoadSubCommand(
4513b9c1b51eSKate Stone         "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4514b9c1b51eSKate Stone                     interpreter)));
4515b9c1b51eSKate Stone     LoadSubCommand(
4516b9c1b51eSKate Stone         "coordinate",
4517b9c1b51eSKate Stone         CommandObjectSP(
4518b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4519b9c1b51eSKate Stone     LoadSubCommand(
4520b9c1b51eSKate Stone         "breakpoint",
4521b9c1b51eSKate Stone         CommandObjectSP(
4522b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
45234640cde1SColin Riley   }
45244640cde1SColin Riley 
4525222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernel() override = default;
45264640cde1SColin Riley };
45274640cde1SColin Riley 
4528b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
45294640cde1SColin Riley public:
45304640cde1SColin Riley   CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4531b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript context dump",
4532b9c1b51eSKate Stone                             "Dumps renderscript context information.",
4533b9c1b51eSKate Stone                             "renderscript context dump",
4534b9c1b51eSKate Stone                             eCommandRequiresProcess |
4535b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
45364640cde1SColin Riley 
4537222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContextDump() override = default;
45384640cde1SColin Riley 
4539b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
45404640cde1SColin Riley     RenderScriptRuntime *runtime =
4541b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4542b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
45434640cde1SColin Riley     runtime->DumpContexts(result.GetOutputStream());
45444640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
45454640cde1SColin Riley     return true;
45464640cde1SColin Riley   }
45474640cde1SColin Riley };
45484640cde1SColin Riley 
45491f0f5b5bSZachary Turner static OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
45501f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
45511f0f5b5bSZachary Turner      nullptr, nullptr, 0, eArgTypeFilename,
45521f0f5b5bSZachary Turner      "Print results to specified file instead of command line."}};
45531f0f5b5bSZachary Turner 
4554b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
45554640cde1SColin Riley public:
45564640cde1SColin Riley   CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4557b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript context",
4558b9c1b51eSKate Stone                                "Commands that deal with RenderScript contexts.",
4559b9c1b51eSKate Stone                                nullptr) {
4560b9c1b51eSKate Stone     LoadSubCommand(
4561b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4562b9c1b51eSKate Stone                     interpreter)));
45634640cde1SColin Riley   }
45644640cde1SColin Riley 
4565222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContext() override = default;
45664640cde1SColin Riley };
45674640cde1SColin Riley 
4568b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationDump
4569b9c1b51eSKate Stone     : public CommandObjectParsed {
4570a0f08674SEwan Crawford public:
4571b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationDump(
4572b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4573a0f08674SEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation dump",
4574b9c1b51eSKate Stone                             "Displays the contents of a particular allocation",
4575b9c1b51eSKate Stone                             "renderscript allocation dump <ID>",
4576b9c1b51eSKate Stone                             eCommandRequiresProcess |
4577b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched),
4578b9c1b51eSKate Stone         m_options() {}
4579a0f08674SEwan Crawford 
4580222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4581222b937cSEugene Zelenko 
4582b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
4583a0f08674SEwan Crawford 
4584b9c1b51eSKate Stone   class CommandOptions : public Options {
4585a0f08674SEwan Crawford   public:
4586e1cfbc79STodd Fiala     CommandOptions() : Options() {}
4587a0f08674SEwan Crawford 
4588222b937cSEugene Zelenko     ~CommandOptions() override = default;
4589a0f08674SEwan Crawford 
4590b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
4591b3bbcb12SLuke Drummond                          ExecutionContext *exe_ctx) override {
459280af0b9eSLuke Drummond       Error err;
4593a0f08674SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
4594a0f08674SEwan Crawford 
4595b9c1b51eSKate Stone       switch (short_option) {
4596a0f08674SEwan Crawford       case 'f':
4597a0f08674SEwan Crawford         m_outfile.SetFile(option_arg, true);
4598b9c1b51eSKate Stone         if (m_outfile.Exists()) {
4599a0f08674SEwan Crawford           m_outfile.Clear();
460080af0b9eSLuke Drummond           err.SetErrorStringWithFormat("file already exists: '%s'", option_arg);
4601a0f08674SEwan Crawford         }
4602a0f08674SEwan Crawford         break;
4603a0f08674SEwan Crawford       default:
460480af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4605a0f08674SEwan Crawford         break;
4606a0f08674SEwan Crawford       }
460780af0b9eSLuke Drummond       return err;
4608a0f08674SEwan Crawford     }
4609a0f08674SEwan Crawford 
4610b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4611a0f08674SEwan Crawford       m_outfile.Clear();
4612a0f08674SEwan Crawford     }
4613a0f08674SEwan Crawford 
46141f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
461570602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
46161f0f5b5bSZachary Turner     }
4617a0f08674SEwan Crawford 
4618a0f08674SEwan Crawford     FileSpec m_outfile;
4619a0f08674SEwan Crawford   };
4620a0f08674SEwan Crawford 
4621b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4622a0f08674SEwan Crawford     const size_t argc = command.GetArgumentCount();
4623b9c1b51eSKate Stone     if (argc < 1) {
4624b9c1b51eSKate Stone       result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4625b9c1b51eSKate Stone                                    "As well as an optional -f argument",
4626a0f08674SEwan Crawford                                    m_cmd_name.c_str());
4627a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4628a0f08674SEwan Crawford       return false;
4629a0f08674SEwan Crawford     }
4630a0f08674SEwan Crawford 
4631b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4632b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4633b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4634a0f08674SEwan Crawford 
4635a0f08674SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
463680af0b9eSLuke Drummond     bool success = false;
4637b9c1b51eSKate Stone     const uint32_t id =
463880af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
463980af0b9eSLuke Drummond     if (!success) {
4640b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4641b9c1b51eSKate Stone                                    id_cstr);
4642a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4643a0f08674SEwan Crawford       return false;
4644a0f08674SEwan Crawford     }
4645a0f08674SEwan Crawford 
4646a0f08674SEwan Crawford     Stream *output_strm = nullptr;
4647a0f08674SEwan Crawford     StreamFile outfile_stream;
4648b9c1b51eSKate Stone     const FileSpec &outfile_spec =
4649b9c1b51eSKate Stone         m_options.m_outfile; // Dump allocation to file instead
4650b9c1b51eSKate Stone     if (outfile_spec) {
4651a0f08674SEwan Crawford       // Open output file
4652a0f08674SEwan Crawford       char path[256];
4653a0f08674SEwan Crawford       outfile_spec.GetPath(path, sizeof(path));
4654b9c1b51eSKate Stone       if (outfile_stream.GetFile()
4655b9c1b51eSKate Stone               .Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate)
4656b9c1b51eSKate Stone               .Success()) {
4657a0f08674SEwan Crawford         output_strm = &outfile_stream;
4658a0f08674SEwan Crawford         result.GetOutputStream().Printf("Results written to '%s'", path);
4659a0f08674SEwan Crawford         result.GetOutputStream().EOL();
4660b9c1b51eSKate Stone       } else {
4661a0f08674SEwan Crawford         result.AppendErrorWithFormat("Couldn't open file '%s'", path);
4662a0f08674SEwan Crawford         result.SetStatus(eReturnStatusFailed);
4663a0f08674SEwan Crawford         return false;
4664a0f08674SEwan Crawford       }
4665b9c1b51eSKate Stone     } else
4666a0f08674SEwan Crawford       output_strm = &result.GetOutputStream();
4667a0f08674SEwan Crawford 
4668a0f08674SEwan Crawford     assert(output_strm != nullptr);
466980af0b9eSLuke Drummond     bool dumped =
4670b9c1b51eSKate Stone         runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4671a0f08674SEwan Crawford 
467280af0b9eSLuke Drummond     if (dumped)
4673a0f08674SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4674a0f08674SEwan Crawford     else
4675a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4676a0f08674SEwan Crawford 
4677a0f08674SEwan Crawford     return true;
4678a0f08674SEwan Crawford   }
4679a0f08674SEwan Crawford 
4680a0f08674SEwan Crawford private:
4681a0f08674SEwan Crawford   CommandOptions m_options;
4682a0f08674SEwan Crawford };
4683a0f08674SEwan Crawford 
46841f0f5b5bSZachary Turner static OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
46851f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
46861f0f5b5bSZachary Turner      nullptr, 0, eArgTypeIndex,
46871f0f5b5bSZachary Turner      "Only show details of a single allocation with specified id."}};
4688a0f08674SEwan Crawford 
4689b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationList
4690b9c1b51eSKate Stone     : public CommandObjectParsed {
469115f2bd95SEwan Crawford public:
4692b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationList(
4693b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4694b9c1b51eSKate Stone       : CommandObjectParsed(
4695b9c1b51eSKate Stone             interpreter, "renderscript allocation list",
4696b9c1b51eSKate Stone             "List renderscript allocations and their information.",
4697b9c1b51eSKate Stone             "renderscript allocation list",
4698b3f7f69dSAidan Dodds             eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4699b9c1b51eSKate Stone         m_options() {}
470015f2bd95SEwan Crawford 
4701222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4702222b937cSEugene Zelenko 
4703b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
470415f2bd95SEwan Crawford 
4705b9c1b51eSKate Stone   class CommandOptions : public Options {
470615f2bd95SEwan Crawford   public:
4707e1cfbc79STodd Fiala     CommandOptions() : Options(), m_id(0) {}
470815f2bd95SEwan Crawford 
4709222b937cSEugene Zelenko     ~CommandOptions() override = default;
471015f2bd95SEwan Crawford 
4711b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
4712b3bbcb12SLuke Drummond                          ExecutionContext *exe_ctx) override {
471380af0b9eSLuke Drummond       Error err;
471415f2bd95SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
471515f2bd95SEwan Crawford 
4716b9c1b51eSKate Stone       switch (short_option) {
4717b649b005SEwan Crawford       case 'i':
4718b649b005SEwan Crawford         bool success;
4719b649b005SEwan Crawford         m_id = StringConvert::ToUInt32(option_arg, 0, 0, &success);
4720b649b005SEwan Crawford         if (!success)
472180af0b9eSLuke Drummond           err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4722b9c1b51eSKate Stone                                        short_option);
472315f2bd95SEwan Crawford         break;
472480af0b9eSLuke Drummond       default:
472580af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
472680af0b9eSLuke Drummond         break;
472715f2bd95SEwan Crawford       }
472880af0b9eSLuke Drummond       return err;
472915f2bd95SEwan Crawford     }
473015f2bd95SEwan Crawford 
4731b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
473215f2bd95SEwan Crawford 
47331f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
473470602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
47351f0f5b5bSZachary Turner     }
473615f2bd95SEwan Crawford 
4737b649b005SEwan Crawford     uint32_t m_id;
473815f2bd95SEwan Crawford   };
473915f2bd95SEwan Crawford 
4740b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4741b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4742b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4743b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4744b9c1b51eSKate Stone     runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4745b9c1b51eSKate Stone                              m_options.m_id);
474615f2bd95SEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
474715f2bd95SEwan Crawford     return true;
474815f2bd95SEwan Crawford   }
474915f2bd95SEwan Crawford 
475015f2bd95SEwan Crawford private:
475115f2bd95SEwan Crawford   CommandOptions m_options;
475215f2bd95SEwan Crawford };
475315f2bd95SEwan Crawford 
4754b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationLoad
4755b9c1b51eSKate Stone     : public CommandObjectParsed {
475655232f09SEwan Crawford public:
4757b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationLoad(
4758b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4759b3f7f69dSAidan Dodds       : CommandObjectParsed(
4760b9c1b51eSKate Stone             interpreter, "renderscript allocation load",
4761b9c1b51eSKate Stone             "Loads renderscript allocation contents from a file.",
4762b9c1b51eSKate Stone             "renderscript allocation load <ID> <filename>",
4763b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
476455232f09SEwan Crawford 
4765222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
476655232f09SEwan Crawford 
4767b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
476855232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4769b9c1b51eSKate Stone     if (argc != 2) {
4770b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4771b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4772b3f7f69dSAidan Dodds           m_cmd_name.c_str());
477355232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
477455232f09SEwan Crawford       return false;
477555232f09SEwan Crawford     }
477655232f09SEwan Crawford 
4777b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4778b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4779b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
478055232f09SEwan Crawford 
478155232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
478280af0b9eSLuke Drummond     bool success = false;
4783b9c1b51eSKate Stone     const uint32_t id =
478480af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
478580af0b9eSLuke Drummond     if (!success) {
4786b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4787b9c1b51eSKate Stone                                    id_cstr);
478855232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
478955232f09SEwan Crawford       return false;
479055232f09SEwan Crawford     }
479155232f09SEwan Crawford 
479280af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
479380af0b9eSLuke Drummond     bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
479480af0b9eSLuke Drummond                                           m_exe_ctx.GetFramePtr());
479555232f09SEwan Crawford 
479680af0b9eSLuke Drummond     if (loaded)
479755232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
479855232f09SEwan Crawford     else
479955232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
480055232f09SEwan Crawford 
480155232f09SEwan Crawford     return true;
480255232f09SEwan Crawford   }
480355232f09SEwan Crawford };
480455232f09SEwan Crawford 
4805b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationSave
4806b9c1b51eSKate Stone     : public CommandObjectParsed {
480755232f09SEwan Crawford public:
4808b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationSave(
4809b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4810b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript allocation save",
4811b9c1b51eSKate Stone                             "Write renderscript allocation contents to a file.",
4812b9c1b51eSKate Stone                             "renderscript allocation save <ID> <filename>",
4813b9c1b51eSKate Stone                             eCommandRequiresProcess |
4814b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
481555232f09SEwan Crawford 
4816222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
481755232f09SEwan Crawford 
4818b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
481955232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4820b9c1b51eSKate Stone     if (argc != 2) {
4821b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4822b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4823b3f7f69dSAidan Dodds           m_cmd_name.c_str());
482455232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
482555232f09SEwan Crawford       return false;
482655232f09SEwan Crawford     }
482755232f09SEwan Crawford 
4828b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4829b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4830b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
483155232f09SEwan Crawford 
483255232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
483380af0b9eSLuke Drummond     bool success = false;
4834b9c1b51eSKate Stone     const uint32_t id =
483580af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
483680af0b9eSLuke Drummond     if (!success) {
4837b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4838b9c1b51eSKate Stone                                    id_cstr);
483955232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
484055232f09SEwan Crawford       return false;
484155232f09SEwan Crawford     }
484255232f09SEwan Crawford 
484380af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
484480af0b9eSLuke Drummond     bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
484580af0b9eSLuke Drummond                                          m_exe_ctx.GetFramePtr());
484655232f09SEwan Crawford 
484780af0b9eSLuke Drummond     if (saved)
484855232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
484955232f09SEwan Crawford     else
485055232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
485155232f09SEwan Crawford 
485255232f09SEwan Crawford     return true;
485355232f09SEwan Crawford   }
485455232f09SEwan Crawford };
485555232f09SEwan Crawford 
4856b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationRefresh
4857b9c1b51eSKate Stone     : public CommandObjectParsed {
48580d2bfcfbSEwan Crawford public:
4859b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationRefresh(
4860b9c1b51eSKate Stone       CommandInterpreter &interpreter)
48610d2bfcfbSEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4862b9c1b51eSKate Stone                             "Recomputes the details of all allocations.",
4863b9c1b51eSKate Stone                             "renderscript allocation refresh",
4864b9c1b51eSKate Stone                             eCommandRequiresProcess |
4865b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
48660d2bfcfbSEwan Crawford 
48670d2bfcfbSEwan Crawford   ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
48680d2bfcfbSEwan Crawford 
4869b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
48700d2bfcfbSEwan Crawford     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4871b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4872b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
48730d2bfcfbSEwan Crawford 
4874b9c1b51eSKate Stone     bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4875b9c1b51eSKate Stone                                                     m_exe_ctx.GetFramePtr());
48760d2bfcfbSEwan Crawford 
4877b9c1b51eSKate Stone     if (success) {
48780d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
48790d2bfcfbSEwan Crawford       return true;
4880b9c1b51eSKate Stone     } else {
48810d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusFailed);
48820d2bfcfbSEwan Crawford       return false;
48830d2bfcfbSEwan Crawford     }
48840d2bfcfbSEwan Crawford   }
48850d2bfcfbSEwan Crawford };
48860d2bfcfbSEwan Crawford 
4887b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocation
4888b9c1b51eSKate Stone     : public CommandObjectMultiword {
488915f2bd95SEwan Crawford public:
489015f2bd95SEwan Crawford   CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4891b9c1b51eSKate Stone       : CommandObjectMultiword(
4892b9c1b51eSKate Stone             interpreter, "renderscript allocation",
4893b9c1b51eSKate Stone             "Commands that deal with RenderScript allocations.", nullptr) {
4894b9c1b51eSKate Stone     LoadSubCommand(
4895b9c1b51eSKate Stone         "list",
4896b9c1b51eSKate Stone         CommandObjectSP(
4897b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4898b9c1b51eSKate Stone     LoadSubCommand(
4899b9c1b51eSKate Stone         "dump",
4900b9c1b51eSKate Stone         CommandObjectSP(
4901b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4902b9c1b51eSKate Stone     LoadSubCommand(
4903b9c1b51eSKate Stone         "save",
4904b9c1b51eSKate Stone         CommandObjectSP(
4905b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4906b9c1b51eSKate Stone     LoadSubCommand(
4907b9c1b51eSKate Stone         "load",
4908b9c1b51eSKate Stone         CommandObjectSP(
4909b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4910b9c1b51eSKate Stone     LoadSubCommand(
4911b9c1b51eSKate Stone         "refresh",
4912b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4913b9c1b51eSKate Stone             interpreter)));
491415f2bd95SEwan Crawford   }
491515f2bd95SEwan Crawford 
4916222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocation() override = default;
491715f2bd95SEwan Crawford };
491815f2bd95SEwan Crawford 
4919b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
49204640cde1SColin Riley public:
49214640cde1SColin Riley   CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4922b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript status",
4923b9c1b51eSKate Stone                             "Displays current RenderScript runtime status.",
4924b9c1b51eSKate Stone                             "renderscript status",
4925b9c1b51eSKate Stone                             eCommandRequiresProcess |
4926b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
49274640cde1SColin Riley 
4928222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeStatus() override = default;
49294640cde1SColin Riley 
4930b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
49314640cde1SColin Riley     RenderScriptRuntime *runtime =
4932b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4933b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
49344640cde1SColin Riley     runtime->Status(result.GetOutputStream());
49354640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
49364640cde1SColin Riley     return true;
49374640cde1SColin Riley   }
49384640cde1SColin Riley };
49394640cde1SColin Riley 
4940b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReduction
4941b3bbcb12SLuke Drummond     : public CommandObjectMultiword {
4942b3bbcb12SLuke Drummond public:
4943b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
4944b3bbcb12SLuke Drummond       : CommandObjectMultiword(interpreter, "renderscript reduction",
4945b3bbcb12SLuke Drummond                                "Commands that handle general reduction kernels",
4946b3bbcb12SLuke Drummond                                nullptr) {
4947b3bbcb12SLuke Drummond     LoadSubCommand(
4948b3bbcb12SLuke Drummond         "breakpoint",
4949b3bbcb12SLuke Drummond         CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
4950b3bbcb12SLuke Drummond             interpreter)));
4951b3bbcb12SLuke Drummond   }
4952b3bbcb12SLuke Drummond   ~CommandObjectRenderScriptRuntimeReduction() override = default;
4953b3bbcb12SLuke Drummond };
4954b3bbcb12SLuke Drummond 
4955b9c1b51eSKate Stone class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
49565ec532a9SColin Riley public:
49575ec532a9SColin Riley   CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
4958b9c1b51eSKate Stone       : CommandObjectMultiword(
4959b9c1b51eSKate Stone             interpreter, "renderscript",
4960b9c1b51eSKate Stone             "Commands for operating on the RenderScript runtime.",
4961b9c1b51eSKate Stone             "renderscript <subcommand> [<subcommand-options>]") {
4962b9c1b51eSKate Stone     LoadSubCommand(
4963b9c1b51eSKate Stone         "module", CommandObjectSP(
4964b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeModule(interpreter)));
4965b9c1b51eSKate Stone     LoadSubCommand(
4966b9c1b51eSKate Stone         "status", CommandObjectSP(
4967b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeStatus(interpreter)));
4968b9c1b51eSKate Stone     LoadSubCommand(
4969b9c1b51eSKate Stone         "kernel", CommandObjectSP(
4970b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeKernel(interpreter)));
4971b9c1b51eSKate Stone     LoadSubCommand("context",
4972b9c1b51eSKate Stone                    CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
4973b9c1b51eSKate Stone                        interpreter)));
4974b9c1b51eSKate Stone     LoadSubCommand(
4975b9c1b51eSKate Stone         "allocation",
4976b9c1b51eSKate Stone         CommandObjectSP(
4977b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
4978*21fed052SAidan Dodds     LoadSubCommand("scriptgroup",
4979*21fed052SAidan Dodds                    NewCommandObjectRenderScriptScriptGroup(interpreter));
4980b3bbcb12SLuke Drummond     LoadSubCommand(
4981b3bbcb12SLuke Drummond         "reduction",
4982b3bbcb12SLuke Drummond         CommandObjectSP(
4983b3bbcb12SLuke Drummond             new CommandObjectRenderScriptRuntimeReduction(interpreter)));
49845ec532a9SColin Riley   }
49855ec532a9SColin Riley 
4986222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntime() override = default;
49875ec532a9SColin Riley };
4988ef20b08fSColin Riley 
4989b9c1b51eSKate Stone void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
4990ef20b08fSColin Riley 
4991ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
4992b9c1b51eSKate Stone     : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
4993b9c1b51eSKate Stone       m_debuggerPresentFlagged(false), m_breakAllKernels(false),
4994b9c1b51eSKate Stone       m_ir_passes(nullptr) {
49954640cde1SColin Riley   ModulesDidLoad(process->GetTarget().GetImages());
4996ef20b08fSColin Riley }
49974640cde1SColin Riley 
4998b9c1b51eSKate Stone lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
4999b9c1b51eSKate Stone     lldb_private::CommandInterpreter &interpreter) {
50000a66e2f1SEnrico Granata   return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
50014640cde1SColin Riley }
50024640cde1SColin Riley 
500378f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
5004