15ec532a9SColin Riley //===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===//
25ec532a9SColin Riley //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65ec532a9SColin Riley //
75ec532a9SColin Riley //===----------------------------------------------------------------------===//
85ec532a9SColin Riley 
95ec532a9SColin Riley #include "RenderScriptRuntime.h"
1021fed052SAidan Dodds #include "RenderScriptScriptGroup.h"
115ec532a9SColin Riley 
12b3f7f69dSAidan Dodds #include "lldb/Breakpoint/StoppointCallbackContext.h"
135ec532a9SColin Riley #include "lldb/Core/Debugger.h"
1429cb868aSZachary Turner #include "lldb/Core/DumpDataExtractor.h"
155ec532a9SColin Riley #include "lldb/Core/PluginManager.h"
16b3f7f69dSAidan Dodds #include "lldb/Core/ValueObjectVariable.h"
178b244e21SEwan Crawford #include "lldb/DataFormatters/DumpValueObjectOptions.h"
18b3f7f69dSAidan Dodds #include "lldb/Expression/UserExpression.h"
193eb2b44dSZachary Turner #include "lldb/Host/OptionParser.h"
20a0f08674SEwan Crawford #include "lldb/Host/StringConvert.h"
21b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandInterpreter.h"
22b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandObjectMultiword.h"
23b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandReturnObject.h"
24b3f7f69dSAidan Dodds #include "lldb/Interpreter/Options.h"
2521fed052SAidan Dodds #include "lldb/Symbol/Function.h"
265ec532a9SColin Riley #include "lldb/Symbol/Symbol.h"
274640cde1SColin Riley #include "lldb/Symbol/Type.h"
28b3f7f69dSAidan Dodds #include "lldb/Symbol/VariableList.h"
295ec532a9SColin Riley #include "lldb/Target/Process.h"
30b3f7f69dSAidan Dodds #include "lldb/Target/RegisterContext.h"
3121fed052SAidan Dodds #include "lldb/Target/SectionLoadList.h"
325ec532a9SColin Riley #include "lldb/Target/Target.h"
33018f5a7eSEwan Crawford #include "lldb/Target/Thread.h"
34145d95c9SPavel Labath #include "lldb/Utility/Args.h"
35bf9a7730SZachary Turner #include "lldb/Utility/ConstString.h"
366f9e6901SZachary Turner #include "lldb/Utility/Log.h"
37d821c997SPavel Labath #include "lldb/Utility/RegisterValue.h"
38bf9a7730SZachary Turner #include "lldb/Utility/RegularExpression.h"
3997206d57SZachary Turner #include "lldb/Utility/Status.h"
405ec532a9SColin Riley 
41*796ac80bSJonas Devlieghere #include "llvm/ADT/StringSwitch.h"
42*796ac80bSJonas Devlieghere 
43*796ac80bSJonas Devlieghere #include <memory>
44*796ac80bSJonas Devlieghere 
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 
12297206d57SZachary Turner   Status 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;
13597206d57SZachary Turner     Status 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 
16597206d57SZachary Turner   Status 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 
22997206d57SZachary Turner   Status 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 
30997206d57SZachary Turner   Status err;
31017e07c0aSAidan Dodds 
31105097246SAdrian Prantl   // find offset to arguments on the stack (+16 to skip over a0-a3 shadow
31205097246SAdrian Prantl   // space)
31317e07c0aSAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP() + 16;
31417e07c0aSAidan Dodds 
315b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
316f4786785SAidan Dodds     bool success = false;
317f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
318f4786785SAidan Dodds     // arguments passed in registers
31980af0b9eSLuke Drummond     if (i < args_in_reg) {
32080af0b9eSLuke Drummond       const RegisterInfo *reg =
32180af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
32280af0b9eSLuke Drummond       RegisterValue reg_val;
32380af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
32480af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
325f4786785SAidan Dodds     }
326f4786785SAidan Dodds     // arguments passed on the stack
327b9c1b51eSKate Stone     else {
3286dd4b579SAidan Dodds       const size_t arg_size = sizeof(uint32_t);
3296dd4b579SAidan Dodds       arg.value = 0;
330b9c1b51eSKate Stone       size_t bytes_read =
33180af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
33280af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
33367dc3e15SAidan Dodds       // advance the stack pointer
33467dc3e15SAidan Dodds       sp += arg_size;
335f4786785SAidan Dodds     }
336f4786785SAidan Dodds     // fail if we couldn't read this argument
337b9c1b51eSKate Stone     if (!success) {
338f4786785SAidan Dodds       if (log)
33967dc3e15SAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
34080af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
341f4786785SAidan Dodds       return false;
342f4786785SAidan Dodds     }
343f4786785SAidan Dodds   }
344f4786785SAidan Dodds   return true;
345f4786785SAidan Dodds }
346f4786785SAidan Dodds 
347b9c1b51eSKate Stone bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
348f4786785SAidan Dodds   // number of arguments passed in registers
34980af0b9eSLuke Drummond   static const uint32_t args_in_reg = 8;
350f4786785SAidan Dodds   // register file offset to first argument
35180af0b9eSLuke Drummond   static const uint32_t reg_offset = 4;
352f4786785SAidan Dodds 
353f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
354f4786785SAidan Dodds 
35597206d57SZachary Turner   Status err;
35617e07c0aSAidan Dodds 
357f4786785SAidan Dodds   // get the current stack pointer
358f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
359f4786785SAidan Dodds 
360b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
361f4786785SAidan Dodds     bool success = false;
362f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
363f4786785SAidan Dodds     // arguments passed in registers
36480af0b9eSLuke Drummond     if (i < args_in_reg) {
36580af0b9eSLuke Drummond       const RegisterInfo *reg =
36680af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
36780af0b9eSLuke Drummond       RegisterValue reg_val;
36880af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
36980af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
370f4786785SAidan Dodds     }
371f4786785SAidan Dodds     // arguments passed on the stack
372b9c1b51eSKate Stone     else {
373f4786785SAidan Dodds       // get the argument type size
374f4786785SAidan Dodds       const size_t arg_size = sizeof(uint64_t);
375f4786785SAidan Dodds       // clear all 64bits
376f4786785SAidan Dodds       arg.value = 0;
377f4786785SAidan Dodds       // read this argument from memory
378b9c1b51eSKate Stone       size_t bytes_read =
37980af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
38080af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
381f4786785SAidan Dodds       // advance the stack pointer
382f4786785SAidan Dodds       sp += arg_size;
383f4786785SAidan Dodds     }
384f4786785SAidan Dodds     // fail if we couldn't read this argument
385b9c1b51eSKate Stone     if (!success) {
386f4786785SAidan Dodds       if (log)
38717e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
38880af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
389f4786785SAidan Dodds       return false;
390f4786785SAidan Dodds     }
391f4786785SAidan Dodds   }
392f4786785SAidan Dodds   return true;
393f4786785SAidan Dodds }
394f4786785SAidan Dodds 
39580af0b9eSLuke Drummond bool GetArgs(ExecutionContext &exe_ctx, ArgItem *arg_list, size_t num_args) {
396f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
397f4786785SAidan Dodds 
398f4786785SAidan Dodds   // verify that we have a target
39980af0b9eSLuke Drummond   if (!exe_ctx.GetTargetPtr()) {
400f4786785SAidan Dodds     if (log)
401f4786785SAidan Dodds       log->Printf("%s - invalid target", __FUNCTION__);
402f4786785SAidan Dodds     return false;
403f4786785SAidan Dodds   }
404f4786785SAidan Dodds 
40580af0b9eSLuke Drummond   GetArgsCtx ctx = {exe_ctx.GetRegisterContext(), exe_ctx.GetProcessPtr()};
406f4786785SAidan Dodds   assert(ctx.reg_ctx && ctx.process);
407f4786785SAidan Dodds 
408f4786785SAidan Dodds   // dispatch based on architecture
40980af0b9eSLuke Drummond   switch (exe_ctx.GetTargetPtr()->GetArchitecture().GetMachine()) {
410f4786785SAidan Dodds   case llvm::Triple::ArchType::x86:
411f4786785SAidan Dodds     return GetArgsX86(ctx, arg_list, num_args);
412f4786785SAidan Dodds 
413f4786785SAidan Dodds   case llvm::Triple::ArchType::x86_64:
414f4786785SAidan Dodds     return GetArgsX86_64(ctx, arg_list, num_args);
415f4786785SAidan Dodds 
416f4786785SAidan Dodds   case llvm::Triple::ArchType::arm:
417f4786785SAidan Dodds     return GetArgsArm(ctx, arg_list, num_args);
418f4786785SAidan Dodds 
419f4786785SAidan Dodds   case llvm::Triple::ArchType::aarch64:
420f4786785SAidan Dodds     return GetArgsAarch64(ctx, arg_list, num_args);
421f4786785SAidan Dodds 
422f4786785SAidan Dodds   case llvm::Triple::ArchType::mipsel:
423f4786785SAidan Dodds     return GetArgsMipsel(ctx, arg_list, num_args);
424f4786785SAidan Dodds 
425f4786785SAidan Dodds   case llvm::Triple::ArchType::mips64el:
426f4786785SAidan Dodds     return GetArgsMips64el(ctx, arg_list, num_args);
427f4786785SAidan Dodds 
428f4786785SAidan Dodds   default:
429f4786785SAidan Dodds     // unsupported architecture
430b9c1b51eSKate Stone     if (log) {
431b9c1b51eSKate Stone       log->Printf(
432b9c1b51eSKate Stone           "%s - architecture not supported: '%s'", __FUNCTION__,
43380af0b9eSLuke Drummond           exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
434f4786785SAidan Dodds     }
435f4786785SAidan Dodds     return false;
436f4786785SAidan Dodds   }
437f4786785SAidan Dodds }
43800f56eebSLuke Drummond 
439b3bbcb12SLuke Drummond bool IsRenderScriptScriptModule(ModuleSP module) {
440b3bbcb12SLuke Drummond   if (!module)
441b3bbcb12SLuke Drummond     return false;
442b3bbcb12SLuke Drummond   return module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
443b3bbcb12SLuke Drummond                                                 eSymbolTypeData) != nullptr;
444b3bbcb12SLuke Drummond }
445b3bbcb12SLuke Drummond 
44600f56eebSLuke Drummond bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
44705097246SAdrian Prantl   // takes an argument of the form 'num[,num][,num]'. Where 'coord_s' is a
44805097246SAdrian Prantl   // comma separated 1,2 or 3-dimensional coordinate with the whitespace
44905097246SAdrian Prantl   // trimmed. Missing coordinates are defaulted to zero. If parsing of any
45005097246SAdrian Prantl   // elements fails the contents of &coord are undefined and `false` is
45105097246SAdrian Prantl   // 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 }
48121fed052SAidan Dodds 
48221fed052SAidan Dodds bool SkipPrologue(lldb::ModuleSP &module, Address &addr) {
48321fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
48421fed052SAidan Dodds   SymbolContext sc;
48521fed052SAidan Dodds   uint32_t resolved_flags =
48621fed052SAidan Dodds       module->ResolveSymbolContextForAddress(addr, eSymbolContextFunction, sc);
48721fed052SAidan Dodds   if (resolved_flags & eSymbolContextFunction) {
48821fed052SAidan Dodds     if (sc.function) {
48921fed052SAidan Dodds       const uint32_t offset = sc.function->GetPrologueByteSize();
49021fed052SAidan Dodds       ConstString name = sc.GetFunctionName();
49121fed052SAidan Dodds       if (offset)
49221fed052SAidan Dodds         addr.Slide(offset);
49321fed052SAidan Dodds       if (log)
49421fed052SAidan Dodds         log->Printf("%s: Prologue offset for %s is %" PRIu32, __FUNCTION__,
49521fed052SAidan Dodds                     name.AsCString(), offset);
49621fed052SAidan Dodds     }
49721fed052SAidan Dodds     return true;
49821fed052SAidan Dodds   } else
49921fed052SAidan Dodds     return false;
50021fed052SAidan 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>
5924ebdee0aSBruce Mitchener       array_size;        // Number of items in array, only needed for structs
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
63205097246SAdrian Prantl   // ElementHeader's children, each struct is immediately followed by a
63305097246SAdrian Prantl   // sequence of consecutive offsets to the start of its child structs. These
63405097246SAdrian Prantl   // offsets are
63580af0b9eSLuke Drummond   // 4 bytes in size, and the 0 offset signifies no more children.
636b9c1b51eSKate Stone   struct FileHeader {
63755232f09SEwan Crawford     uint8_t ident[4];  // ASCII 'RSAD' identifying the file
63826e52a70SEwan Crawford     uint32_t dims[3];  // Dimensions
63926e52a70SEwan Crawford     uint16_t hdr_size; // Header size in bytes, including all element headers
64026e52a70SEwan Crawford   };
64126e52a70SEwan Crawford 
642b9c1b51eSKate Stone   struct ElementHeader {
64355232f09SEwan Crawford     uint16_t type;         // DataType enum
64455232f09SEwan Crawford     uint32_t kind;         // DataKind enum
64555232f09SEwan Crawford     uint32_t element_size; // Size of a single element, including padding
64626e52a70SEwan Crawford     uint16_t vector_size;  // Vector width
64726e52a70SEwan Crawford     uint32_t array_size;   // Number of elements in array
64855232f09SEwan Crawford   };
64955232f09SEwan Crawford 
65015f2bd95SEwan Crawford   // Monotonically increasing from 1
651b3f7f69dSAidan Dodds   static uint32_t ID;
65215f2bd95SEwan Crawford 
65305097246SAdrian Prantl   // Maps Allocation DataType enum and vector size to printable strings using
65405097246SAdrian Prantl   // mapping from RenderScript numerical types summary documentation
65515f2bd95SEwan Crawford   static const char *RsDataTypeToString[][4];
65615f2bd95SEwan Crawford 
65715f2bd95SEwan Crawford   // Maps Allocation DataKind enum to printable strings
65815f2bd95SEwan Crawford   static const char *RsDataKindToString[];
65915f2bd95SEwan Crawford 
660a0f08674SEwan Crawford   // Maps allocation types to format sizes for printing.
661b3f7f69dSAidan Dodds   static const uint32_t RSTypeToFormat[][3];
662a0f08674SEwan Crawford 
66315f2bd95SEwan Crawford   // Give each allocation an ID as a way
66415f2bd95SEwan Crawford   // for commands to reference it.
665b3f7f69dSAidan Dodds   const uint32_t id;
66615f2bd95SEwan Crawford 
66780af0b9eSLuke Drummond   // Allocation Element type
66880af0b9eSLuke Drummond   RenderScriptRuntime::Element element;
66980af0b9eSLuke Drummond   // Dimensions of the Allocation
67080af0b9eSLuke Drummond   empirical_type<Dimension> dimension;
67180af0b9eSLuke Drummond   // Pointer to address of the RS Allocation
67280af0b9eSLuke Drummond   empirical_type<lldb::addr_t> address;
67380af0b9eSLuke Drummond   // Pointer to the data held by the Allocation
67480af0b9eSLuke Drummond   empirical_type<lldb::addr_t> data_ptr;
67580af0b9eSLuke Drummond   // Pointer to the RS Type of the Allocation
67680af0b9eSLuke Drummond   empirical_type<lldb::addr_t> type_ptr;
67780af0b9eSLuke Drummond   // Pointer to the RS Context of the Allocation
67880af0b9eSLuke Drummond   empirical_type<lldb::addr_t> context;
67980af0b9eSLuke Drummond   // Size of the allocation
68080af0b9eSLuke Drummond   empirical_type<uint32_t> size;
68180af0b9eSLuke Drummond   // Stride between rows of the allocation
68280af0b9eSLuke Drummond   empirical_type<uint32_t> stride;
68315f2bd95SEwan Crawford 
68415f2bd95SEwan Crawford   // Give each allocation an id, so we can reference it in user commands.
685b3f7f69dSAidan Dodds   AllocationDetails() : id(ID++) {}
6868b59062aSEwan Crawford 
68780af0b9eSLuke Drummond   bool ShouldRefresh() const {
6888b59062aSEwan Crawford     bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
6898b59062aSEwan Crawford     valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
690b9c1b51eSKate Stone     return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
69180af0b9eSLuke Drummond            element.ShouldRefresh();
6928b59062aSEwan Crawford   }
69315f2bd95SEwan Crawford };
69415f2bd95SEwan Crawford 
695b9c1b51eSKate Stone const ConstString &RenderScriptRuntime::Element::GetFallbackStructName() {
696fe06b5adSAdrian McCarthy   static const ConstString FallbackStructName("struct");
697fe06b5adSAdrian McCarthy   return FallbackStructName;
698fe06b5adSAdrian McCarthy }
6998b244e21SEwan Crawford 
700b3f7f69dSAidan Dodds uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
70115f2bd95SEwan Crawford 
702b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
703b9c1b51eSKate Stone     "User",       "Undefined",   "Undefined", "Undefined",
704b9c1b51eSKate Stone     "Undefined",  "Undefined",   "Undefined", // Enum jumps from 0 to 7
705b3f7f69dSAidan Dodds     "L Pixel",    "A Pixel",     "LA Pixel",  "RGB Pixel",
706b3f7f69dSAidan Dodds     "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
70715f2bd95SEwan Crawford 
708b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
70915f2bd95SEwan Crawford     {"None", "None", "None", "None"},
71015f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
71115f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
71215f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
71315f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
71415f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
71515f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
71615f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
71715f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
71815f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
71915f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
72015f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
7212e920715SEwan Crawford     {"bool", "bool2", "bool3", "bool4"},
7222e920715SEwan Crawford     {"packed_565", "packed_565", "packed_565", "packed_565"},
7232e920715SEwan Crawford     {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
7242e920715SEwan Crawford     {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
7252e920715SEwan Crawford     {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
7262e920715SEwan Crawford     {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
7272e920715SEwan Crawford     {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
7282e920715SEwan Crawford 
7292e920715SEwan Crawford     // Handlers
7302e920715SEwan Crawford     {"RS Element", "RS Element", "RS Element", "RS Element"},
7312e920715SEwan Crawford     {"RS Type", "RS Type", "RS Type", "RS Type"},
7322e920715SEwan Crawford     {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
7332e920715SEwan Crawford     {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
7342e920715SEwan Crawford     {"RS Script", "RS Script", "RS Script", "RS Script"},
7352e920715SEwan Crawford 
7362e920715SEwan Crawford     // Deprecated
7372e920715SEwan Crawford     {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
738b9c1b51eSKate Stone     {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
739b9c1b51eSKate Stone      "RS Program Fragment"},
740b9c1b51eSKate Stone     {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
741b9c1b51eSKate Stone      "RS Program Vertex"},
742b9c1b51eSKate Stone     {"RS Program Raster", "RS Program Raster", "RS Program Raster",
743b9c1b51eSKate Stone      "RS Program Raster"},
744b9c1b51eSKate Stone     {"RS Program Store", "RS Program Store", "RS Program Store",
745b9c1b51eSKate Stone      "RS Program Store"},
746b3f7f69dSAidan Dodds     {"RS Font", "RS Font", "RS Font", "RS Font"}};
74778f339d1SEwan Crawford 
748a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
749b9c1b51eSKate Stone enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
750a0f08674SEwan Crawford 
751b9c1b51eSKate Stone // { format enum of single element, format enum of element vector, size of
752b9c1b51eSKate Stone // element}
753b3f7f69dSAidan Dodds const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
75480af0b9eSLuke Drummond     // RS_TYPE_NONE
75580af0b9eSLuke Drummond     {eFormatHex, eFormatHex, 1},
75680af0b9eSLuke Drummond     // RS_TYPE_FLOAT_16
75780af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat16, 2},
75880af0b9eSLuke Drummond     // RS_TYPE_FLOAT_32
75980af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
76080af0b9eSLuke Drummond     // RS_TYPE_FLOAT_64
76180af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
76280af0b9eSLuke Drummond     // RS_TYPE_SIGNED_8
76380af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
76480af0b9eSLuke Drummond     // RS_TYPE_SIGNED_16
76580af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
76680af0b9eSLuke Drummond     // RS_TYPE_SIGNED_32
76780af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
76880af0b9eSLuke Drummond     // RS_TYPE_SIGNED_64
76980af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
77080af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_8
77180af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
77280af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_16
77380af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
77480af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_32
77580af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
77680af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_64
77780af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
77880af0b9eSLuke Drummond     // RS_TYPE_BOOL
77980af0b9eSLuke Drummond     {eFormatBoolean, eFormatBoolean, 1},
78080af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_5_6_5
78180af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
78280af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_5_5_5_1
78380af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
78480af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_4_4_4_4
78580af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
78680af0b9eSLuke Drummond     // RS_TYPE_MATRIX_4X4
78780af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
78880af0b9eSLuke Drummond     // RS_TYPE_MATRIX_3X3
78980af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
79080af0b9eSLuke Drummond     // RS_TYPE_MATRIX_2X2
79180af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
792a0f08674SEwan Crawford 
7935ec532a9SColin Riley //------------------------------------------------------------------
7945ec532a9SColin Riley // Static Functions
7955ec532a9SColin Riley //------------------------------------------------------------------
7965ec532a9SColin Riley LanguageRuntime *
797b9c1b51eSKate Stone RenderScriptRuntime::CreateInstance(Process *process,
798b9c1b51eSKate Stone                                     lldb::LanguageType language) {
7995ec532a9SColin Riley 
8005ec532a9SColin Riley   if (language == eLanguageTypeExtRenderScript)
8015ec532a9SColin Riley     return new RenderScriptRuntime(process);
8025ec532a9SColin Riley   else
803b3f7f69dSAidan Dodds     return nullptr;
8045ec532a9SColin Riley }
8055ec532a9SColin Riley 
80680af0b9eSLuke Drummond // Callback with a module to search for matching symbols. We first check that
80780af0b9eSLuke Drummond // the module contains RS kernels. Then look for a symbol which matches our
80880af0b9eSLuke Drummond // kernel name. The breakpoint address is finally set using the address of this
80980af0b9eSLuke Drummond // symbol.
81098156583SEwan Crawford Searcher::CallbackReturn
811b9c1b51eSKate Stone RSBreakpointResolver::SearchCallback(SearchFilter &filter,
812b9c1b51eSKate Stone                                      SymbolContext &context, Address *, bool) {
81398156583SEwan Crawford   ModuleSP module = context.module_sp;
81498156583SEwan Crawford 
815b3bbcb12SLuke Drummond   if (!module || !IsRenderScriptScriptModule(module))
81698156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
81798156583SEwan Crawford 
818b9c1b51eSKate Stone   // Attempt to set a breakpoint on the kernel name symbol within the module
81980af0b9eSLuke Drummond   // library. If it's not found, it's likely debug info is unavailable - try to
82080af0b9eSLuke Drummond   // set a breakpoint on <name>.expand.
821b9c1b51eSKate Stone   const Symbol *kernel_sym =
822b9c1b51eSKate Stone       module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
823b9c1b51eSKate Stone   if (!kernel_sym) {
82498156583SEwan Crawford     std::string kernel_name_expanded(m_kernel_name.AsCString());
82598156583SEwan Crawford     kernel_name_expanded.append(".expand");
826b9c1b51eSKate Stone     kernel_sym = module->FindFirstSymbolWithNameAndType(
827b9c1b51eSKate Stone         ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
82898156583SEwan Crawford   }
82998156583SEwan Crawford 
830b9c1b51eSKate Stone   if (kernel_sym) {
83198156583SEwan Crawford     Address bp_addr = kernel_sym->GetAddress();
83298156583SEwan Crawford     if (filter.AddressPasses(bp_addr))
83398156583SEwan Crawford       m_breakpoint->AddLocation(bp_addr);
83498156583SEwan Crawford   }
83598156583SEwan Crawford 
83698156583SEwan Crawford   return Searcher::eCallbackReturnContinue;
83798156583SEwan Crawford }
83898156583SEwan Crawford 
839b3bbcb12SLuke Drummond Searcher::CallbackReturn
840b3bbcb12SLuke Drummond RSReduceBreakpointResolver::SearchCallback(lldb_private::SearchFilter &filter,
841b3bbcb12SLuke Drummond                                            lldb_private::SymbolContext &context,
842b3bbcb12SLuke Drummond                                            Address *, bool) {
843b3bbcb12SLuke Drummond   // We need to have access to the list of reductions currently parsed, as
84405097246SAdrian Prantl   // reduce names don't actually exist as symbols in a module. They are only
84505097246SAdrian Prantl   // identifiable by parsing the .rs.info packet, or finding the expand symbol.
84605097246SAdrian Prantl   // We therefore need access to the list of parsed rs modules to properly
84705097246SAdrian Prantl   // resolve 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;
88681fc84faSLuke Drummond           if (!SkipPrologue(module, address)) {
88781fc84faSLuke Drummond             if (log)
88881fc84faSLuke Drummond               log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
88981fc84faSLuke Drummond           }
890b3bbcb12SLuke Drummond           m_breakpoint->AddLocation(address, &new_bp);
891b3bbcb12SLuke Drummond           if (log)
892b3bbcb12SLuke Drummond             log->Printf("%s: %s reduction breakpoint on %s in %s", __FUNCTION__,
893b3bbcb12SLuke Drummond                         new_bp ? "new" : "existing", kernel_name.GetCString(),
894b3bbcb12SLuke Drummond                         address.GetModule()->GetFileSpec().GetCString());
895b3bbcb12SLuke Drummond         }
896b3bbcb12SLuke Drummond       }
897b3bbcb12SLuke Drummond     }
898b3bbcb12SLuke Drummond   }
899b3bbcb12SLuke Drummond   return eCallbackReturnContinue;
900b3bbcb12SLuke Drummond }
901b3bbcb12SLuke Drummond 
90221fed052SAidan Dodds Searcher::CallbackReturn RSScriptGroupBreakpointResolver::SearchCallback(
90321fed052SAidan Dodds     SearchFilter &filter, SymbolContext &context, Address *addr,
90421fed052SAidan Dodds     bool containing) {
90521fed052SAidan Dodds 
90621fed052SAidan Dodds   if (!m_breakpoint)
90721fed052SAidan Dodds     return eCallbackReturnContinue;
90821fed052SAidan Dodds 
90921fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
91021fed052SAidan Dodds   ModuleSP &module = context.module_sp;
91121fed052SAidan Dodds 
91221fed052SAidan Dodds   if (!module || !IsRenderScriptScriptModule(module))
91321fed052SAidan Dodds     return Searcher::eCallbackReturnContinue;
91421fed052SAidan Dodds 
91521fed052SAidan Dodds   std::vector<std::string> names;
91621fed052SAidan Dodds   m_breakpoint->GetNames(names);
91721fed052SAidan Dodds   if (names.empty())
91821fed052SAidan Dodds     return eCallbackReturnContinue;
91921fed052SAidan Dodds 
92021fed052SAidan Dodds   for (auto &name : names) {
92121fed052SAidan Dodds     const RSScriptGroupDescriptorSP sg = FindScriptGroup(ConstString(name));
92221fed052SAidan Dodds     if (!sg) {
92321fed052SAidan Dodds       if (log)
92421fed052SAidan Dodds         log->Printf("%s: could not find script group for %s", __FUNCTION__,
92521fed052SAidan Dodds                     name.c_str());
92621fed052SAidan Dodds       continue;
92721fed052SAidan Dodds     }
92821fed052SAidan Dodds 
92921fed052SAidan Dodds     if (log)
93021fed052SAidan Dodds       log->Printf("%s: Found ScriptGroup for %s", __FUNCTION__, name.c_str());
93121fed052SAidan Dodds 
93221fed052SAidan Dodds     for (const RSScriptGroupDescriptor::Kernel &k : sg->m_kernels) {
93321fed052SAidan Dodds       if (log) {
93421fed052SAidan Dodds         log->Printf("%s: Adding breakpoint for %s", __FUNCTION__,
93521fed052SAidan Dodds                     k.m_name.AsCString());
93621fed052SAidan Dodds         log->Printf("%s: Kernel address 0x%" PRIx64, __FUNCTION__, k.m_addr);
93721fed052SAidan Dodds       }
93821fed052SAidan Dodds 
93921fed052SAidan Dodds       const lldb_private::Symbol *sym =
94021fed052SAidan Dodds           module->FindFirstSymbolWithNameAndType(k.m_name, eSymbolTypeCode);
94121fed052SAidan Dodds       if (!sym) {
94221fed052SAidan Dodds         if (log)
94321fed052SAidan Dodds           log->Printf("%s: Unable to find symbol for %s", __FUNCTION__,
94421fed052SAidan Dodds                       k.m_name.AsCString());
94521fed052SAidan Dodds         continue;
94621fed052SAidan Dodds       }
94721fed052SAidan Dodds 
94821fed052SAidan Dodds       if (log) {
94921fed052SAidan Dodds         log->Printf("%s: Found symbol name is %s", __FUNCTION__,
95021fed052SAidan Dodds                     sym->GetName().AsCString());
95121fed052SAidan Dodds       }
95221fed052SAidan Dodds 
95321fed052SAidan Dodds       auto address = sym->GetAddress();
95421fed052SAidan Dodds       if (!SkipPrologue(module, address)) {
95521fed052SAidan Dodds         if (log)
95621fed052SAidan Dodds           log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
95721fed052SAidan Dodds       }
95821fed052SAidan Dodds 
95921fed052SAidan Dodds       bool new_bp;
96021fed052SAidan Dodds       m_breakpoint->AddLocation(address, &new_bp);
96121fed052SAidan Dodds 
96221fed052SAidan Dodds       if (log)
96321fed052SAidan Dodds         log->Printf("%s: Placed %sbreakpoint on %s", __FUNCTION__,
96421fed052SAidan Dodds                     new_bp ? "new " : "", k.m_name.AsCString());
96521fed052SAidan Dodds 
96605097246SAdrian Prantl       // exit after placing the first breakpoint if we do not intend to stop on
96705097246SAdrian Prantl       // all kernels making up this script group
96821fed052SAidan Dodds       if (!m_stop_on_all)
96921fed052SAidan Dodds         break;
97021fed052SAidan Dodds     }
97121fed052SAidan Dodds   }
97221fed052SAidan Dodds 
97321fed052SAidan Dodds   return eCallbackReturnContinue;
97421fed052SAidan Dodds }
97521fed052SAidan Dodds 
976b9c1b51eSKate Stone void RenderScriptRuntime::Initialize() {
977b9c1b51eSKate Stone   PluginManager::RegisterPlugin(GetPluginNameStatic(),
978b9c1b51eSKate Stone                                 "RenderScript language support", CreateInstance,
979b3f7f69dSAidan Dodds                                 GetCommandObject);
9805ec532a9SColin Riley }
9815ec532a9SColin Riley 
982b9c1b51eSKate Stone void RenderScriptRuntime::Terminate() {
9835ec532a9SColin Riley   PluginManager::UnregisterPlugin(CreateInstance);
9845ec532a9SColin Riley }
9855ec532a9SColin Riley 
986b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginNameStatic() {
98780af0b9eSLuke Drummond   static ConstString plugin_name("renderscript");
98880af0b9eSLuke Drummond   return plugin_name;
9895ec532a9SColin Riley }
9905ec532a9SColin Riley 
991ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
992b9c1b51eSKate Stone RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
993b9c1b51eSKate Stone   if (module_sp) {
994b3bbcb12SLuke Drummond     if (IsRenderScriptScriptModule(module_sp))
995ef20b08fSColin Riley       return eModuleKindKernelObj;
9964640cde1SColin Riley 
9974640cde1SColin Riley     // Is this the main RS runtime library
9984640cde1SColin Riley     const ConstString rs_lib("libRS.so");
999b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
10004640cde1SColin Riley       return eModuleKindLibRS;
10014640cde1SColin Riley     }
10024640cde1SColin Riley 
10034640cde1SColin Riley     const ConstString rs_driverlib("libRSDriver.so");
1004b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
10054640cde1SColin Riley       return eModuleKindDriver;
10064640cde1SColin Riley     }
10074640cde1SColin Riley 
100815f2bd95SEwan Crawford     const ConstString rs_cpureflib("libRSCpuRef.so");
1009b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
10104640cde1SColin Riley       return eModuleKindImpl;
10114640cde1SColin Riley     }
1012ef20b08fSColin Riley   }
1013ef20b08fSColin Riley   return eModuleKindIgnored;
1014ef20b08fSColin Riley }
1015ef20b08fSColin Riley 
1016b9c1b51eSKate Stone bool RenderScriptRuntime::IsRenderScriptModule(
1017b9c1b51eSKate Stone     const lldb::ModuleSP &module_sp) {
1018ef20b08fSColin Riley   return GetModuleKind(module_sp) != eModuleKindIgnored;
1019ef20b08fSColin Riley }
1020ef20b08fSColin Riley 
1021b9c1b51eSKate Stone void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
1022bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1023ef20b08fSColin Riley 
1024ef20b08fSColin Riley   size_t num_modules = module_list.GetSize();
1025b9c1b51eSKate Stone   for (size_t i = 0; i < num_modules; i++) {
1026ef20b08fSColin Riley     auto mod = module_list.GetModuleAtIndex(i);
1027b9c1b51eSKate Stone     if (IsRenderScriptModule(mod)) {
1028ef20b08fSColin Riley       LoadModule(mod);
1029ef20b08fSColin Riley     }
1030ef20b08fSColin Riley   }
1031ef20b08fSColin Riley }
1032ef20b08fSColin Riley 
10335ec532a9SColin Riley //------------------------------------------------------------------
10345ec532a9SColin Riley // PluginInterface protocol
10355ec532a9SColin Riley //------------------------------------------------------------------
1036b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginName() {
10375ec532a9SColin Riley   return GetPluginNameStatic();
10385ec532a9SColin Riley }
10395ec532a9SColin Riley 
1040b9c1b51eSKate Stone uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; }
10415ec532a9SColin Riley 
1042b9c1b51eSKate Stone bool RenderScriptRuntime::IsVTableName(const char *name) { return false; }
10435ec532a9SColin Riley 
1044b9c1b51eSKate Stone bool RenderScriptRuntime::GetDynamicTypeAndAddress(
1045b9c1b51eSKate Stone     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
10465f57b6eeSEnrico Granata     TypeAndOrName &class_type_or_name, Address &address,
1047b9c1b51eSKate Stone     Value::ValueType &value_type) {
10485ec532a9SColin Riley   return false;
10495ec532a9SColin Riley }
10505ec532a9SColin Riley 
1051c74275bcSEnrico Granata TypeAndOrName
1052b9c1b51eSKate Stone RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
1053b9c1b51eSKate Stone                                       ValueObject &static_value) {
1054c74275bcSEnrico Granata   return type_and_or_name;
1055c74275bcSEnrico Granata }
1056c74275bcSEnrico Granata 
1057b9c1b51eSKate Stone bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
10585ec532a9SColin Riley   return false;
10595ec532a9SColin Riley }
10605ec532a9SColin Riley 
10615ec532a9SColin Riley lldb::BreakpointResolverSP
106280af0b9eSLuke Drummond RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bp, bool catch_bp,
1063b9c1b51eSKate Stone                                              bool throw_bp) {
10645ec532a9SColin Riley   BreakpointResolverSP resolver_sp;
10655ec532a9SColin Riley   return resolver_sp;
10665ec532a9SColin Riley }
10675ec532a9SColin Riley 
1068b9c1b51eSKate Stone const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
1069b9c1b51eSKate Stone     {
10704640cde1SColin Riley         // rsdScript
1071b9c1b51eSKate Stone         {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
1072b9c1b51eSKate Stone                           "NS0_7ScriptCEPKcS7_PKhjj",
1073b9c1b51eSKate Stone          "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
1074b9c1b51eSKate Stone          "7ScriptCEPKcS7_PKhmj",
1075b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1076b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInit},
1077b9c1b51eSKate Stone         {"rsdScriptInvokeForEachMulti",
1078b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1079b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
1080b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1081b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
1082b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1083b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
1084b9c1b51eSKate Stone         {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
1085b9c1b51eSKate Stone                                   "script7ContextEPKNS0_6ScriptEjPvj",
1086b9c1b51eSKate Stone          "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
1087b9c1b51eSKate Stone          "6ScriptEjPvm",
1088b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1089b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
10904640cde1SColin Riley 
10914640cde1SColin Riley         // rsdAllocation
1092b9c1b51eSKate Stone         {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
1093b9c1b51eSKate Stone                               "ontextEPNS0_10AllocationEb",
1094b9c1b51eSKate Stone          "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
1095b9c1b51eSKate Stone          "10AllocationEb",
1096b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1097b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
1098b9c1b51eSKate Stone         {"rsdAllocationRead2D",
1099b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1100b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1101b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1102b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1103b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1104b9c1b51eSKate Stone         {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1105b9c1b51eSKate Stone                                  "ript7ContextEPNS0_10AllocationE",
1106b9c1b51eSKate Stone          "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1107b9c1b51eSKate Stone          "10AllocationE",
1108b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1109b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
111021fed052SAidan Dodds 
111121fed052SAidan Dodds         // renderscript script groups
111221fed052SAidan Dodds         {"rsdDebugHintScriptGroup2", "_ZN7android12renderscript21debugHintScrip"
111321fed052SAidan Dodds                                      "tGroup2EPKcjPKPFvPK24RsExpandKernelDriver"
111421fed052SAidan Dodds                                      "InfojjjEj",
111521fed052SAidan Dodds          "_ZN7android12renderscript21debugHintScriptGroup2EPKcjPKPFvPK24RsExpan"
111621fed052SAidan Dodds          "dKernelDriverInfojjjEj",
111721fed052SAidan Dodds          0, RenderScriptRuntime::eModuleKindImpl,
111821fed052SAidan Dodds          &lldb_private::RenderScriptRuntime::CaptureDebugHintScriptGroup2}};
11194640cde1SColin Riley 
1120b9c1b51eSKate Stone const size_t RenderScriptRuntime::s_runtimeHookCount =
1121b9c1b51eSKate Stone     sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
11224640cde1SColin Riley 
1123b9c1b51eSKate Stone bool RenderScriptRuntime::HookCallback(void *baton,
1124b9c1b51eSKate Stone                                        StoppointCallbackContext *ctx,
1125b9c1b51eSKate Stone                                        lldb::user_id_t break_id,
1126b9c1b51eSKate Stone                                        lldb::user_id_t break_loc_id) {
112780af0b9eSLuke Drummond   RuntimeHook *hook = (RuntimeHook *)baton;
112880af0b9eSLuke Drummond   ExecutionContext exe_ctx(ctx->exe_ctx_ref);
11294640cde1SColin Riley 
1130b3f7f69dSAidan Dodds   RenderScriptRuntime *lang_rt =
113180af0b9eSLuke Drummond       (RenderScriptRuntime *)exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1132b9c1b51eSKate Stone           eLanguageTypeExtRenderScript);
11334640cde1SColin Riley 
113480af0b9eSLuke Drummond   lang_rt->HookCallback(hook, exe_ctx);
11354640cde1SColin Riley 
11364640cde1SColin Riley   return false;
11374640cde1SColin Riley }
11384640cde1SColin Riley 
113980af0b9eSLuke Drummond void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
114080af0b9eSLuke Drummond                                        ExecutionContext &exe_ctx) {
11414640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11424640cde1SColin Riley 
11434640cde1SColin Riley   if (log)
114480af0b9eSLuke Drummond     log->Printf("%s - '%s'", __FUNCTION__, hook->defn->name);
11454640cde1SColin Riley 
114680af0b9eSLuke Drummond   if (hook->defn->grabber) {
114780af0b9eSLuke Drummond     (this->*(hook->defn->grabber))(hook, exe_ctx);
11484640cde1SColin Riley   }
11494640cde1SColin Riley }
11504640cde1SColin Riley 
115121fed052SAidan Dodds void RenderScriptRuntime::CaptureDebugHintScriptGroup2(
115221fed052SAidan Dodds     RuntimeHook *hook_info, ExecutionContext &context) {
115321fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
115421fed052SAidan Dodds 
115521fed052SAidan Dodds   enum {
115621fed052SAidan Dodds     eGroupName = 0,
115721fed052SAidan Dodds     eGroupNameSize,
115821fed052SAidan Dodds     eKernel,
115921fed052SAidan Dodds     eKernelCount,
116021fed052SAidan Dodds   };
116121fed052SAidan Dodds 
116221fed052SAidan Dodds   std::array<ArgItem, 4> args{{
116321fed052SAidan Dodds       {ArgItem::ePointer, 0}, // const char         *groupName
116421fed052SAidan Dodds       {ArgItem::eInt32, 0},   // const uint32_t      groupNameSize
116521fed052SAidan Dodds       {ArgItem::ePointer, 0}, // const ExpandFuncTy *kernel
116621fed052SAidan Dodds       {ArgItem::eInt32, 0},   // const uint32_t      kernelCount
116721fed052SAidan Dodds   }};
116821fed052SAidan Dodds 
116921fed052SAidan Dodds   if (!GetArgs(context, args.data(), args.size())) {
117021fed052SAidan Dodds     if (log)
117121fed052SAidan Dodds       log->Printf("%s - Error while reading the function parameters",
117221fed052SAidan Dodds                   __FUNCTION__);
117321fed052SAidan Dodds     return;
117421fed052SAidan Dodds   } else if (log) {
117521fed052SAidan Dodds     log->Printf("%s - groupName    : 0x%" PRIx64, __FUNCTION__,
117621fed052SAidan Dodds                 addr_t(args[eGroupName]));
117721fed052SAidan Dodds     log->Printf("%s - groupNameSize: %" PRIu64, __FUNCTION__,
117821fed052SAidan Dodds                 uint64_t(args[eGroupNameSize]));
117921fed052SAidan Dodds     log->Printf("%s - kernel       : 0x%" PRIx64, __FUNCTION__,
118021fed052SAidan Dodds                 addr_t(args[eKernel]));
118121fed052SAidan Dodds     log->Printf("%s - kernelCount  : %" PRIu64, __FUNCTION__,
118221fed052SAidan Dodds                 uint64_t(args[eKernelCount]));
118321fed052SAidan Dodds   }
118421fed052SAidan Dodds 
118521fed052SAidan Dodds   // parse script group name
118621fed052SAidan Dodds   ConstString group_name;
118721fed052SAidan Dodds   {
118897206d57SZachary Turner     Status err;
118921fed052SAidan Dodds     const uint64_t len = uint64_t(args[eGroupNameSize]);
119021fed052SAidan Dodds     std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]);
119121fed052SAidan Dodds     m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err);
119221fed052SAidan Dodds     buffer.get()[len] = '\0';
119321fed052SAidan Dodds     if (!err.Success()) {
119421fed052SAidan Dodds       if (log)
119521fed052SAidan Dodds         log->Printf("Error reading scriptgroup name from target");
119621fed052SAidan Dodds       return;
119721fed052SAidan Dodds     } else {
119821fed052SAidan Dodds       if (log)
119921fed052SAidan Dodds         log->Printf("Extracted scriptgroup name %s", buffer.get());
120021fed052SAidan Dodds     }
120121fed052SAidan Dodds     // write back the script group name
120221fed052SAidan Dodds     group_name.SetCString(buffer.get());
120321fed052SAidan Dodds   }
120421fed052SAidan Dodds 
120521fed052SAidan Dodds   // create or access existing script group
120621fed052SAidan Dodds   RSScriptGroupDescriptorSP group;
120721fed052SAidan Dodds   {
120821fed052SAidan Dodds     // search for existing script group
120921fed052SAidan Dodds     for (auto sg : m_scriptGroups) {
121021fed052SAidan Dodds       if (sg->m_name == group_name) {
121121fed052SAidan Dodds         group = sg;
121221fed052SAidan Dodds         break;
121321fed052SAidan Dodds       }
121421fed052SAidan Dodds     }
121521fed052SAidan Dodds     if (!group) {
1216*796ac80bSJonas Devlieghere       group = std::make_shared<RSScriptGroupDescriptor>();
121721fed052SAidan Dodds       group->m_name = group_name;
121821fed052SAidan Dodds       m_scriptGroups.push_back(group);
121921fed052SAidan Dodds     } else {
122021fed052SAidan Dodds       // already have this script group
122121fed052SAidan Dodds       if (log)
122221fed052SAidan Dodds         log->Printf("Attempt to add duplicate script group %s",
122321fed052SAidan Dodds                     group_name.AsCString());
122421fed052SAidan Dodds       return;
122521fed052SAidan Dodds     }
122621fed052SAidan Dodds   }
122721fed052SAidan Dodds   assert(group);
122821fed052SAidan Dodds 
122921fed052SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
123021fed052SAidan Dodds   std::vector<addr_t> kernels;
123121fed052SAidan Dodds   // parse kernel addresses in script group
123221fed052SAidan Dodds   for (uint64_t i = 0; i < uint64_t(args[eKernelCount]); ++i) {
123321fed052SAidan Dodds     RSScriptGroupDescriptor::Kernel kernel;
123421fed052SAidan Dodds     // extract script group kernel addresses from the target
123521fed052SAidan Dodds     const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size;
123621fed052SAidan Dodds     uint64_t kernel_addr = 0;
123797206d57SZachary Turner     Status err;
123821fed052SAidan Dodds     size_t read =
123921fed052SAidan Dodds         m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err);
124021fed052SAidan Dodds     if (!err.Success() || read != target_ptr_size) {
124121fed052SAidan Dodds       if (log)
124221fed052SAidan Dodds         log->Printf("Error parsing kernel address %" PRIu64 " in script group",
124321fed052SAidan Dodds                     i);
124421fed052SAidan Dodds       return;
124521fed052SAidan Dodds     }
124621fed052SAidan Dodds     if (log)
124721fed052SAidan Dodds       log->Printf("Extracted scriptgroup kernel address - 0x%" PRIx64,
124821fed052SAidan Dodds                   kernel_addr);
124921fed052SAidan Dodds     kernel.m_addr = kernel_addr;
125021fed052SAidan Dodds 
125121fed052SAidan Dodds     // try to resolve the associated kernel name
125221fed052SAidan Dodds     if (!ResolveKernelName(kernel.m_addr, kernel.m_name)) {
125321fed052SAidan Dodds       if (log)
125421fed052SAidan Dodds         log->Printf("Parsed scriptgroup kernel %" PRIu64 " - 0x%" PRIx64, i,
125521fed052SAidan Dodds                     kernel_addr);
125621fed052SAidan Dodds       return;
125721fed052SAidan Dodds     }
125821fed052SAidan Dodds 
125921fed052SAidan Dodds     // try to find the non '.expand' function
126021fed052SAidan Dodds     {
126121fed052SAidan Dodds       const llvm::StringRef expand(".expand");
126221fed052SAidan Dodds       const llvm::StringRef name_ref = kernel.m_name.GetStringRef();
126321fed052SAidan Dodds       if (name_ref.endswith(expand)) {
126421fed052SAidan Dodds         const ConstString base_kernel(name_ref.drop_back(expand.size()));
126521fed052SAidan Dodds         // verify this function is a valid kernel
126621fed052SAidan Dodds         if (IsKnownKernel(base_kernel)) {
126721fed052SAidan Dodds           kernel.m_name = base_kernel;
126821fed052SAidan Dodds           if (log)
126921fed052SAidan Dodds             log->Printf("%s - found non expand version '%s'", __FUNCTION__,
127021fed052SAidan Dodds                         base_kernel.GetCString());
127121fed052SAidan Dodds         }
127221fed052SAidan Dodds       }
127321fed052SAidan Dodds     }
127421fed052SAidan Dodds     // add to a list of script group kernels we know about
127521fed052SAidan Dodds     group->m_kernels.push_back(kernel);
127621fed052SAidan Dodds   }
127721fed052SAidan Dodds 
127821fed052SAidan Dodds   // Resolve any pending scriptgroup breakpoints
127921fed052SAidan Dodds   {
128021fed052SAidan Dodds     Target &target = m_process->GetTarget();
128121fed052SAidan Dodds     const BreakpointList &list = target.GetBreakpointList();
128221fed052SAidan Dodds     const size_t num_breakpoints = list.GetSize();
128321fed052SAidan Dodds     if (log)
128421fed052SAidan Dodds       log->Printf("Resolving %zu breakpoints", num_breakpoints);
128521fed052SAidan Dodds     for (size_t i = 0; i < num_breakpoints; ++i) {
128621fed052SAidan Dodds       const BreakpointSP bp = list.GetBreakpointAtIndex(i);
128721fed052SAidan Dodds       if (bp) {
128821fed052SAidan Dodds         if (bp->MatchesName(group_name.AsCString())) {
128921fed052SAidan Dodds           if (log)
129021fed052SAidan Dodds             log->Printf("Found breakpoint with name %s",
129121fed052SAidan Dodds                         group_name.AsCString());
129221fed052SAidan Dodds           bp->ResolveBreakpoint();
129321fed052SAidan Dodds         }
129421fed052SAidan Dodds       }
129521fed052SAidan Dodds     }
129621fed052SAidan Dodds   }
129721fed052SAidan Dodds }
129821fed052SAidan Dodds 
1299b9c1b51eSKate Stone void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
130080af0b9eSLuke Drummond     RuntimeHook *hook, ExecutionContext &exe_ctx) {
1301e09c44b6SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1302e09c44b6SAidan Dodds 
1303b9c1b51eSKate Stone   enum {
1304f4786785SAidan Dodds     eRsContext = 0,
1305f4786785SAidan Dodds     eRsScript,
1306f4786785SAidan Dodds     eRsSlot,
1307f4786785SAidan Dodds     eRsAIns,
1308f4786785SAidan Dodds     eRsInLen,
1309f4786785SAidan Dodds     eRsAOut,
1310f4786785SAidan Dodds     eRsUsr,
1311f4786785SAidan Dodds     eRsUsrLen,
1312f4786785SAidan Dodds     eRsSc,
1313f4786785SAidan Dodds   };
1314e09c44b6SAidan Dodds 
13151ee07253SSaleem Abdulrasool   std::array<ArgItem, 9> args{{
1316f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Context       *rsc
1317f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Script              *s
1318f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // uint32_t             slot
1319f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Allocation   **aIns
1320f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               inLen
1321f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Allocation          *aout
1322f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const void          *usr
1323f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               usrLen
1324f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall  *sc
13251ee07253SSaleem Abdulrasool   }};
1326e09c44b6SAidan Dodds 
132780af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1328b9c1b51eSKate Stone   if (!success) {
1329e09c44b6SAidan Dodds     if (log)
1330b9c1b51eSKate Stone       log->Printf("%s - Error while reading the function parameters",
1331b9c1b51eSKate Stone                   __FUNCTION__);
1332e09c44b6SAidan Dodds     return;
1333e09c44b6SAidan Dodds   }
1334e09c44b6SAidan Dodds 
1335e09c44b6SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
133697206d57SZachary Turner   Status err;
1337e09c44b6SAidan Dodds   std::vector<uint64_t> allocs;
1338e09c44b6SAidan Dodds 
1339e09c44b6SAidan Dodds   // traverse allocation list
1340b9c1b51eSKate Stone   for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1341e09c44b6SAidan Dodds     // calculate offest to allocation pointer
1342f4786785SAidan Dodds     const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1343e09c44b6SAidan Dodds 
134480af0b9eSLuke Drummond     // Note: due to little endian layout, reading 32bits or 64bits into res
134580af0b9eSLuke Drummond     // will give the correct results.
134680af0b9eSLuke Drummond     uint64_t result = 0;
134780af0b9eSLuke Drummond     size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
134880af0b9eSLuke Drummond     if (read != target_ptr_size || !err.Success()) {
1349e09c44b6SAidan Dodds       if (log)
1350b9c1b51eSKate Stone         log->Printf(
1351b9c1b51eSKate Stone             "%s - Error while reading allocation list argument %" PRIu64,
1352b9c1b51eSKate Stone             __FUNCTION__, i);
1353b9c1b51eSKate Stone     } else {
135480af0b9eSLuke Drummond       allocs.push_back(result);
1355e09c44b6SAidan Dodds     }
1356e09c44b6SAidan Dodds   }
1357e09c44b6SAidan Dodds 
1358e09c44b6SAidan Dodds   // if there is an output allocation track it
135980af0b9eSLuke Drummond   if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
136080af0b9eSLuke Drummond     allocs.push_back(alloc_out);
1361e09c44b6SAidan Dodds   }
1362e09c44b6SAidan Dodds 
1363e09c44b6SAidan Dodds   // for all allocations we have found
1364b9c1b51eSKate Stone   for (const uint64_t alloc_addr : allocs) {
13655d057637SLuke Drummond     AllocationDetails *alloc = LookUpAllocation(alloc_addr);
13665d057637SLuke Drummond     if (!alloc)
13675d057637SLuke Drummond       alloc = CreateAllocation(alloc_addr);
13685d057637SLuke Drummond 
1369b9c1b51eSKate Stone     if (alloc) {
1370e09c44b6SAidan Dodds       // save the allocation address
1371b9c1b51eSKate Stone       if (alloc->address.isValid()) {
1372e09c44b6SAidan Dodds         // check the allocation address we already have matches
1373e09c44b6SAidan Dodds         assert(*alloc->address.get() == alloc_addr);
1374b9c1b51eSKate Stone       } else {
1375e09c44b6SAidan Dodds         alloc->address = alloc_addr;
1376e09c44b6SAidan Dodds       }
1377e09c44b6SAidan Dodds 
1378e09c44b6SAidan Dodds       // save the context
1379b9c1b51eSKate Stone       if (log) {
1380b9c1b51eSKate Stone         if (alloc->context.isValid() &&
1381b9c1b51eSKate Stone             *alloc->context.get() != addr_t(args[eRsContext]))
1382b9c1b51eSKate Stone           log->Printf("%s - Allocation used by multiple contexts",
1383b9c1b51eSKate Stone                       __FUNCTION__);
1384e09c44b6SAidan Dodds       }
1385f4786785SAidan Dodds       alloc->context = addr_t(args[eRsContext]);
1386e09c44b6SAidan Dodds     }
1387e09c44b6SAidan Dodds   }
1388e09c44b6SAidan Dodds 
1389e09c44b6SAidan Dodds   // make sure we track this script object
1390b9c1b51eSKate Stone   if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1391b9c1b51eSKate Stone           LookUpScript(addr_t(args[eRsScript]), true)) {
1392b9c1b51eSKate Stone     if (log) {
1393b9c1b51eSKate Stone       if (script->context.isValid() &&
1394b9c1b51eSKate Stone           *script->context.get() != addr_t(args[eRsContext]))
1395b3f7f69dSAidan Dodds         log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1396e09c44b6SAidan Dodds     }
1397f4786785SAidan Dodds     script->context = addr_t(args[eRsContext]);
1398e09c44b6SAidan Dodds   }
1399e09c44b6SAidan Dodds }
1400e09c44b6SAidan Dodds 
140180af0b9eSLuke Drummond void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1402b9c1b51eSKate Stone                                               ExecutionContext &context) {
14034640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14044640cde1SColin Riley 
1405b9c1b51eSKate Stone   enum {
1406f4786785SAidan Dodds     eRsContext,
1407f4786785SAidan Dodds     eRsScript,
1408f4786785SAidan Dodds     eRsId,
1409f4786785SAidan Dodds     eRsData,
1410f4786785SAidan Dodds     eRsLength,
1411f4786785SAidan Dodds   };
14124640cde1SColin Riley 
14131ee07253SSaleem Abdulrasool   std::array<ArgItem, 5> args{{
1414f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1415f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsScript
1416f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsId
1417f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsData
1418f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsLength
14191ee07253SSaleem Abdulrasool   }};
14204640cde1SColin Riley 
1421f4786785SAidan Dodds   bool success = GetArgs(context, &args[0], args.size());
1422b9c1b51eSKate Stone   if (!success) {
142382780287SAidan Dodds     if (log)
1424b3f7f69dSAidan Dodds       log->Printf("%s - error reading the function parameters.", __FUNCTION__);
142582780287SAidan Dodds     return;
142682780287SAidan Dodds   }
14274640cde1SColin Riley 
1428b9c1b51eSKate Stone   if (log) {
1429b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1430b9c1b51eSKate Stone                 ":%" PRIu64 "bytes.",
1431b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1432b9c1b51eSKate Stone                 uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1433f4786785SAidan Dodds                 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
14344640cde1SColin Riley 
1435f4786785SAidan Dodds     addr_t script_addr = addr_t(args[eRsScript]);
1436b9c1b51eSKate Stone     if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
14374640cde1SColin Riley       auto rsm = m_scriptMappings[script_addr];
1438b9c1b51eSKate Stone       if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1439f4786785SAidan Dodds         auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1440b9c1b51eSKate Stone         log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__,
1441b9c1b51eSKate Stone                     rsg.m_name.AsCString(),
1442f4786785SAidan Dodds                     rsm->m_module->GetFileSpec().GetFilename().AsCString());
14434640cde1SColin Riley       }
14444640cde1SColin Riley     }
14454640cde1SColin Riley   }
14464640cde1SColin Riley }
14474640cde1SColin Riley 
144880af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
144980af0b9eSLuke Drummond                                                 ExecutionContext &exe_ctx) {
14504640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14514640cde1SColin Riley 
1452b9c1b51eSKate Stone   enum { eRsContext, eRsAlloc, eRsForceZero };
14534640cde1SColin Riley 
14541ee07253SSaleem Abdulrasool   std::array<ArgItem, 3> args{{
1455f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1456f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1457f4786785SAidan Dodds       ArgItem{ArgItem::eBool, 0},    // eRsForceZero
14581ee07253SSaleem Abdulrasool   }};
14594640cde1SColin Riley 
146080af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
146180af0b9eSLuke Drummond   if (!success) {
146282780287SAidan Dodds     if (log)
1463b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters",
1464b9c1b51eSKate Stone                   __FUNCTION__);
146580af0b9eSLuke Drummond     return;
146682780287SAidan Dodds   }
14674640cde1SColin Riley 
14684640cde1SColin Riley   if (log)
1469b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1470b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1471f4786785SAidan Dodds                 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
147278f339d1SEwan Crawford 
14735d057637SLuke Drummond   AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
147478f339d1SEwan Crawford   if (alloc)
1475f4786785SAidan Dodds     alloc->context = uint64_t(args[eRsContext]);
14764640cde1SColin Riley }
14774640cde1SColin Riley 
147880af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
147980af0b9eSLuke Drummond                                                    ExecutionContext &exe_ctx) {
1480e69df382SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1481e69df382SEwan Crawford 
1482b9c1b51eSKate Stone   enum {
1483f4786785SAidan Dodds     eRsContext,
1484f4786785SAidan Dodds     eRsAlloc,
1485f4786785SAidan Dodds   };
1486e69df382SEwan Crawford 
14871ee07253SSaleem Abdulrasool   std::array<ArgItem, 2> args{{
1488f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1489f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
14901ee07253SSaleem Abdulrasool   }};
1491f4786785SAidan Dodds 
149280af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1493b9c1b51eSKate Stone   if (!success) {
1494e69df382SEwan Crawford     if (log)
1495b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1496b9c1b51eSKate Stone                   __FUNCTION__);
1497b3f7f69dSAidan Dodds     return;
1498e69df382SEwan Crawford   }
1499e69df382SEwan Crawford 
1500e69df382SEwan Crawford   if (log)
1501b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1502b9c1b51eSKate Stone                 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1503e69df382SEwan Crawford 
1504b9c1b51eSKate Stone   for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1505e69df382SEwan Crawford     auto &allocation_ap = *iter; // get the unique pointer
1506b9c1b51eSKate Stone     if (allocation_ap->address.isValid() &&
1507b9c1b51eSKate Stone         *allocation_ap->address.get() == addr_t(args[eRsAlloc])) {
1508e69df382SEwan Crawford       m_allocations.erase(iter);
1509e69df382SEwan Crawford       if (log)
1510b3f7f69dSAidan Dodds         log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1511e69df382SEwan Crawford       return;
1512e69df382SEwan Crawford     }
1513e69df382SEwan Crawford   }
1514e69df382SEwan Crawford 
1515e69df382SEwan Crawford   if (log)
1516b3f7f69dSAidan Dodds     log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1517e69df382SEwan Crawford }
1518e69df382SEwan Crawford 
151980af0b9eSLuke Drummond void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
152080af0b9eSLuke Drummond                                             ExecutionContext &exe_ctx) {
15214640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
15224640cde1SColin Riley 
152397206d57SZachary Turner   Status err;
152480af0b9eSLuke Drummond   Process *process = exe_ctx.GetProcessPtr();
15254640cde1SColin Riley 
1526b9c1b51eSKate Stone   enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
15274640cde1SColin Riley 
1528b9c1b51eSKate Stone   std::array<ArgItem, 4> args{
1529b9c1b51eSKate Stone       {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
15301ee07253SSaleem Abdulrasool        ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
153180af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1532b9c1b51eSKate Stone   if (!success) {
153382780287SAidan Dodds     if (log)
1534b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1535b9c1b51eSKate Stone                   __FUNCTION__);
153682780287SAidan Dodds     return;
153782780287SAidan Dodds   }
153882780287SAidan Dodds 
153980af0b9eSLuke Drummond   std::string res_name;
154080af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
154180af0b9eSLuke Drummond   if (err.Fail()) {
15424640cde1SColin Riley     if (log)
154380af0b9eSLuke Drummond       log->Printf("%s - error reading res_name: %s.", __FUNCTION__,
154480af0b9eSLuke Drummond                   err.AsCString());
15454640cde1SColin Riley   }
15464640cde1SColin Riley 
154780af0b9eSLuke Drummond   std::string cache_dir;
154880af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
154980af0b9eSLuke Drummond   if (err.Fail()) {
15504640cde1SColin Riley     if (log)
155180af0b9eSLuke Drummond       log->Printf("%s - error reading cache_dir: %s.", __FUNCTION__,
155280af0b9eSLuke Drummond                   err.AsCString());
15534640cde1SColin Riley   }
15544640cde1SColin Riley 
15554640cde1SColin Riley   if (log)
1556b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1557b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
155880af0b9eSLuke Drummond                 uint64_t(args[eRsScript]), res_name.c_str(), cache_dir.c_str());
15594640cde1SColin Riley 
156080af0b9eSLuke Drummond   if (res_name.size() > 0) {
15614640cde1SColin Riley     StreamString strm;
156280af0b9eSLuke Drummond     strm.Printf("librs.%s.so", res_name.c_str());
15634640cde1SColin Riley 
1564f4786785SAidan Dodds     ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1565b9c1b51eSKate Stone     if (script) {
156678f339d1SEwan Crawford       script->type = ScriptDetails::eScriptC;
156780af0b9eSLuke Drummond       script->cache_dir = cache_dir;
156880af0b9eSLuke Drummond       script->res_name = res_name;
1569c156427dSZachary Turner       script->shared_lib = strm.GetString();
1570f4786785SAidan Dodds       script->context = addr_t(args[eRsContext]);
157178f339d1SEwan Crawford     }
15724640cde1SColin Riley 
15734640cde1SColin Riley     if (log)
1574b9c1b51eSKate Stone       log->Printf("%s - '%s' tagged with context 0x%" PRIx64
1575b9c1b51eSKate Stone                   " and script 0x%" PRIx64 ".",
1576b9c1b51eSKate Stone                   __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1577b9c1b51eSKate Stone                   uint64_t(args[eRsScript]));
1578b9c1b51eSKate Stone   } else if (log) {
1579b3f7f69dSAidan Dodds     log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
15804640cde1SColin Riley   }
15814640cde1SColin Riley }
15824640cde1SColin Riley 
1583b9c1b51eSKate Stone void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1584b9c1b51eSKate Stone                                            ModuleKind kind) {
15854640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
15864640cde1SColin Riley 
1587b9c1b51eSKate Stone   if (!module) {
15884640cde1SColin Riley     return;
15894640cde1SColin Riley   }
15904640cde1SColin Riley 
159182780287SAidan Dodds   Target &target = GetProcess()->GetTarget();
159221fed052SAidan Dodds   const llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
159382780287SAidan Dodds 
159480af0b9eSLuke Drummond   if (machine != llvm::Triple::ArchType::x86 &&
159580af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::arm &&
159680af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::aarch64 &&
159780af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mipsel &&
159880af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mips64el &&
159980af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::x86_64) {
16004640cde1SColin Riley     if (log)
1601b3f7f69dSAidan Dodds       log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
16024640cde1SColin Riley     return;
16034640cde1SColin Riley   }
16044640cde1SColin Riley 
160521fed052SAidan Dodds   const uint32_t target_ptr_size =
160621fed052SAidan Dodds       target.GetArchitecture().GetAddressByteSize();
160721fed052SAidan Dodds 
160821fed052SAidan Dodds   std::array<bool, s_runtimeHookCount> hook_placed;
160921fed052SAidan Dodds   hook_placed.fill(false);
16104640cde1SColin Riley 
1611b9c1b51eSKate Stone   for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
16124640cde1SColin Riley     const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1613b9c1b51eSKate Stone     if (hook_defn->kind != kind) {
16144640cde1SColin Riley       continue;
16154640cde1SColin Riley     }
16164640cde1SColin Riley 
161780af0b9eSLuke Drummond     const char *symbol_name = (target_ptr_size == 4)
161880af0b9eSLuke Drummond                                   ? hook_defn->symbol_name_m32
1619b9c1b51eSKate Stone                                   : hook_defn->symbol_name_m64;
162082780287SAidan Dodds 
1621b9c1b51eSKate Stone     const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1622b9c1b51eSKate Stone         ConstString(symbol_name), eSymbolTypeCode);
1623b9c1b51eSKate Stone     if (!sym) {
1624b9c1b51eSKate Stone       if (log) {
1625b3f7f69dSAidan Dodds         log->Printf("%s - symbol '%s' related to the function %s not found",
1626b3f7f69dSAidan Dodds                     __FUNCTION__, symbol_name, hook_defn->name);
162782780287SAidan Dodds       }
162882780287SAidan Dodds       continue;
162982780287SAidan Dodds     }
16304640cde1SColin Riley 
1631358cf1eaSGreg Clayton     addr_t addr = sym->GetLoadAddress(&target);
1632b9c1b51eSKate Stone     if (addr == LLDB_INVALID_ADDRESS) {
16334640cde1SColin Riley       if (log)
1634b9c1b51eSKate Stone         log->Printf("%s - unable to resolve the address of hook function '%s' "
1635b9c1b51eSKate Stone                     "with symbol '%s'.",
1636b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, symbol_name);
16374640cde1SColin Riley       continue;
1638b9c1b51eSKate Stone     } else {
163982780287SAidan Dodds       if (log)
1640b3f7f69dSAidan Dodds         log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1641b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, addr);
164282780287SAidan Dodds     }
16434640cde1SColin Riley 
16444640cde1SColin Riley     RuntimeHookSP hook(new RuntimeHook());
16454640cde1SColin Riley     hook->address = addr;
16464640cde1SColin Riley     hook->defn = hook_defn;
16474640cde1SColin Riley     hook->bp_sp = target.CreateBreakpoint(addr, true, false);
16484640cde1SColin Riley     hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
16494640cde1SColin Riley     m_runtimeHooks[addr] = hook;
1650b9c1b51eSKate Stone     if (log) {
1651b9c1b51eSKate Stone       log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64
1652b9c1b51eSKate Stone                   " at 0x%" PRIx64 ".",
1653b9c1b51eSKate Stone                   __FUNCTION__, hook_defn->name,
1654b9c1b51eSKate Stone                   module->GetFileSpec().GetFilename().AsCString(),
1655b3f7f69dSAidan Dodds                   (uint64_t)hook_defn->version, (uint64_t)addr);
16564640cde1SColin Riley     }
165721fed052SAidan Dodds     hook_placed[idx] = true;
165821fed052SAidan Dodds   }
165921fed052SAidan Dodds 
166021fed052SAidan Dodds   // log any unhooked function
166121fed052SAidan Dodds   if (log) {
166221fed052SAidan Dodds     for (size_t i = 0; i < hook_placed.size(); ++i) {
166321fed052SAidan Dodds       if (hook_placed[i])
166421fed052SAidan Dodds         continue;
166521fed052SAidan Dodds       const HookDefn &hook_defn = s_runtimeHookDefns[i];
166621fed052SAidan Dodds       if (hook_defn.kind != kind)
166721fed052SAidan Dodds         continue;
166821fed052SAidan Dodds       log->Printf("%s - function %s was not hooked", __FUNCTION__,
166921fed052SAidan Dodds                   hook_defn.name);
167021fed052SAidan Dodds     }
16714640cde1SColin Riley   }
16724640cde1SColin Riley }
16734640cde1SColin Riley 
1674b9c1b51eSKate Stone void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
16754640cde1SColin Riley   if (!rsmodule_sp)
16764640cde1SColin Riley     return;
16774640cde1SColin Riley 
16784640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
16794640cde1SColin Riley 
16804640cde1SColin Riley   const ModuleSP module = rsmodule_sp->m_module;
16814640cde1SColin Riley   const FileSpec &file = module->GetPlatformFileSpec();
16824640cde1SColin Riley 
168305097246SAdrian Prantl   // Iterate over all of the scripts that we currently know of. Note: We cant
168405097246SAdrian Prantl   // push or pop to m_scripts here or it may invalidate rs_script.
1685b9c1b51eSKate Stone   for (const auto &rs_script : m_scripts) {
168678f339d1SEwan Crawford     // Extract the expected .so file path for this script.
168780af0b9eSLuke Drummond     std::string shared_lib;
168880af0b9eSLuke Drummond     if (!rs_script->shared_lib.get(shared_lib))
168978f339d1SEwan Crawford       continue;
169078f339d1SEwan Crawford 
169178f339d1SEwan Crawford     // Only proceed if the module that has loaded corresponds to this script.
169280af0b9eSLuke Drummond     if (file.GetFilename() != ConstString(shared_lib.c_str()))
169378f339d1SEwan Crawford       continue;
169478f339d1SEwan Crawford 
169578f339d1SEwan Crawford     // Obtain the script address which we use as a key.
169678f339d1SEwan Crawford     lldb::addr_t script;
169778f339d1SEwan Crawford     if (!rs_script->script.get(script))
169878f339d1SEwan Crawford       continue;
169978f339d1SEwan Crawford 
170078f339d1SEwan Crawford     // If we have a script mapping for the current script.
1701b9c1b51eSKate Stone     if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
170278f339d1SEwan Crawford       // if the module we have stored is different to the one we just received.
1703b9c1b51eSKate Stone       if (m_scriptMappings[script] != rsmodule_sp) {
17044640cde1SColin Riley         if (log)
1705b9c1b51eSKate Stone           log->Printf(
1706b9c1b51eSKate Stone               "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1707b9c1b51eSKate Stone               __FUNCTION__, (uint64_t)script,
1708b9c1b51eSKate Stone               rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
17094640cde1SColin Riley       }
17104640cde1SColin Riley     }
171178f339d1SEwan Crawford     // We don't have a script mapping for the current script.
1712b9c1b51eSKate Stone     else {
171378f339d1SEwan Crawford       // Obtain the script resource name.
171480af0b9eSLuke Drummond       std::string res_name;
171580af0b9eSLuke Drummond       if (rs_script->res_name.get(res_name))
171678f339d1SEwan Crawford         // Set the modules resource name.
171780af0b9eSLuke Drummond         rsmodule_sp->m_resname = res_name;
171878f339d1SEwan Crawford       // Add Script/Module pair to map.
171978f339d1SEwan Crawford       m_scriptMappings[script] = rsmodule_sp;
17204640cde1SColin Riley       if (log)
1721b9c1b51eSKate Stone         log->Printf(
1722b9c1b51eSKate Stone             "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1723b9c1b51eSKate Stone             __FUNCTION__, (uint64_t)script,
1724b9c1b51eSKate Stone             rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
17254640cde1SColin Riley     }
17264640cde1SColin Riley   }
17274640cde1SColin Riley }
17284640cde1SColin Riley 
1729b9c1b51eSKate Stone // Uses the Target API to evaluate the expression passed as a parameter to the
173080af0b9eSLuke Drummond // function The result of that expression is returned an unsigned 64 bit int,
173180af0b9eSLuke Drummond // via the result* parameter. Function returns true on success, and false on
173280af0b9eSLuke Drummond // failure
173380af0b9eSLuke Drummond bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1734b9c1b51eSKate Stone                                            StackFrame *frame_ptr,
1735b9c1b51eSKate Stone                                            uint64_t *result) {
173615f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
173715f2bd95SEwan Crawford   if (log)
173880af0b9eSLuke Drummond     log->Printf("%s(%s)", __FUNCTION__, expr);
173915f2bd95SEwan Crawford 
174015f2bd95SEwan Crawford   ValueObjectSP expr_result;
17418433fdbeSAidan Dodds   EvaluateExpressionOptions options;
17428433fdbeSAidan Dodds   options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
174315f2bd95SEwan Crawford   // Perform the actual expression evaluation
174480af0b9eSLuke Drummond   auto &target = GetProcess()->GetTarget();
174580af0b9eSLuke Drummond   target.EvaluateExpression(expr, frame_ptr, expr_result, options);
174615f2bd95SEwan Crawford 
1747b9c1b51eSKate Stone   if (!expr_result) {
174815f2bd95SEwan Crawford     if (log)
1749b3f7f69dSAidan Dodds       log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
175015f2bd95SEwan Crawford     return false;
175115f2bd95SEwan Crawford   }
175215f2bd95SEwan Crawford 
175315f2bd95SEwan Crawford   // The result of the expression is invalid
1754b9c1b51eSKate Stone   if (!expr_result->GetError().Success()) {
175597206d57SZachary Turner     Status err = expr_result->GetError();
175680af0b9eSLuke Drummond     // Expression returned is void, so this is actually a success
1757a35912daSKrasimir Georgiev     if (err.GetError() == UserExpression::kNoResult) {
175815f2bd95SEwan Crawford       if (log)
1759b3f7f69dSAidan Dodds         log->Printf("%s - expression returned void.", __FUNCTION__);
176015f2bd95SEwan Crawford 
176115f2bd95SEwan Crawford       result = nullptr;
176215f2bd95SEwan Crawford       return true;
176315f2bd95SEwan Crawford     }
176415f2bd95SEwan Crawford 
176515f2bd95SEwan Crawford     if (log)
1766b3f7f69dSAidan Dodds       log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1767b3f7f69dSAidan Dodds                   err.AsCString());
176815f2bd95SEwan Crawford     return false;
176915f2bd95SEwan Crawford   }
177015f2bd95SEwan Crawford 
177115f2bd95SEwan Crawford   bool success = false;
177280af0b9eSLuke Drummond   // We only read the result as an uint32_t.
177380af0b9eSLuke Drummond   *result = expr_result->GetValueAsUnsigned(0, &success);
177415f2bd95SEwan Crawford 
1775b9c1b51eSKate Stone   if (!success) {
177615f2bd95SEwan Crawford     if (log)
1777b9c1b51eSKate Stone       log->Printf("%s - couldn't convert expression result to uint32_t",
1778b9c1b51eSKate Stone                   __FUNCTION__);
177915f2bd95SEwan Crawford     return false;
178015f2bd95SEwan Crawford   }
178115f2bd95SEwan Crawford 
178215f2bd95SEwan Crawford   return true;
178315f2bd95SEwan Crawford }
178415f2bd95SEwan Crawford 
1785b9c1b51eSKate Stone namespace {
1786836d9651SEwan Crawford // Used to index expression format strings
1787b9c1b51eSKate Stone enum ExpressionStrings {
1788836d9651SEwan Crawford   eExprGetOffsetPtr = 0,
1789836d9651SEwan Crawford   eExprAllocGetType,
1790836d9651SEwan Crawford   eExprTypeDimX,
1791836d9651SEwan Crawford   eExprTypeDimY,
1792836d9651SEwan Crawford   eExprTypeDimZ,
1793836d9651SEwan Crawford   eExprTypeElemPtr,
1794836d9651SEwan Crawford   eExprElementType,
1795836d9651SEwan Crawford   eExprElementKind,
1796836d9651SEwan Crawford   eExprElementVec,
1797836d9651SEwan Crawford   eExprElementFieldCount,
1798836d9651SEwan Crawford   eExprSubelementsId,
1799836d9651SEwan Crawford   eExprSubelementsName,
1800ea0636b5SEwan Crawford   eExprSubelementsArrSize,
1801ea0636b5SEwan Crawford 
180280af0b9eSLuke Drummond   _eExprLast // keep at the end, implicit size of the array runtime_expressions
1803836d9651SEwan Crawford };
180415f2bd95SEwan Crawford 
1805ea0636b5SEwan Crawford // max length of an expanded expression
1806ea0636b5SEwan Crawford const int jit_max_expr_size = 512;
1807ea0636b5SEwan Crawford 
1808ea0636b5SEwan Crawford // Retrieve the string to JIT for the given expression
180936d783ebSDavid Gross #define JIT_TEMPLATE_CONTEXT "void* ctxt = (void*)rsDebugGetContextWrapper(0x%" PRIx64 "); "
1810b9c1b51eSKate Stone const char *JITTemplate(ExpressionStrings e) {
1811ea0636b5SEwan Crawford   // Format strings containing the expressions we may need to evaluate.
181280af0b9eSLuke Drummond   static std::array<const char *, _eExprLast> runtime_expressions = {
1813b9c1b51eSKate Stone       {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1814b9c1b51eSKate Stone        "(int*)_"
1815b9c1b51eSKate Stone        "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1816b9c1b51eSKate Stone        "CubemapFace"
181736d783ebSDavid Gross        "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)", // eExprGetOffsetPtr
181815f2bd95SEwan Crawford 
181915f2bd95SEwan Crawford        // Type* rsaAllocationGetType(Context*, Allocation*)
182036d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "(void*)rsaAllocationGetType(ctxt, 0x%" PRIx64 ")", // eExprAllocGetType
182115f2bd95SEwan Crawford 
182280af0b9eSLuke Drummond        // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
182380af0b9eSLuke Drummond        // data in the following way mHal.state.dimX; mHal.state.dimY;
182405097246SAdrian Prantl        // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement;
182505097246SAdrian Prantl        // into typeData Need to specify 32 or 64 bit for uint_t since this
182605097246SAdrian Prantl        // differs between devices
182736d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
182836d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
182936d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[0]", // eExprTypeDimX
183036d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
183136d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
183236d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[1]", // eExprTypeDimY
183336d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
183436d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
183536d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[2]", // eExprTypeDimZ
183636d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
183736d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
183836d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[5]", // eExprTypeElemPtr
183915f2bd95SEwan Crawford 
184015f2bd95SEwan Crawford        // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1841b9c1b51eSKate Stone        // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1842b9c1b51eSKate Stone        // elemData
184336d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
184436d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
184536d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[0]", // eExprElementType
184636d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
184736d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
184836d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[1]", // eExprElementKind
184936d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
185036d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
185136d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[3]", // eExprElementVec
185236d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
185336d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
185436d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[4]", // eExprElementFieldCount
18558b244e21SEwan Crawford 
1856b9c1b51eSKate Stone        // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
185780af0b9eSLuke Drummond        // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1858b9c1b51eSKate Stone        // Needed for Allocations of structs to gather details about
185980af0b9eSLuke Drummond        // fields/Subelements Element* of field
186036d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1861b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
186236d783ebSDavid Gross        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
186336d783ebSDavid Gross        ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]", // eExprSubelementsId
18648b244e21SEwan Crawford 
1865577570b4SAidan Dodds        // Name of field
186636d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1867b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
186836d783ebSDavid Gross        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
186936d783ebSDavid Gross        ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]", // eExprSubelementsName
18708b244e21SEwan Crawford 
1871577570b4SAidan Dodds        // Array size of field
187236d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1873b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
187436d783ebSDavid Gross        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
187536d783ebSDavid Gross        ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}}; // eExprSubelementsArrSize
1876ea0636b5SEwan Crawford 
187780af0b9eSLuke Drummond   return runtime_expressions[e];
1878ea0636b5SEwan Crawford }
1879ea0636b5SEwan Crawford } // end of the anonymous namespace
1880ea0636b5SEwan Crawford 
188105097246SAdrian Prantl // JITs the RS runtime for the internal data pointer of an allocation. Is
188205097246SAdrian Prantl // passed x,y,z coordinates for the pointer to a specific element. Then sets
188305097246SAdrian Prantl // the data_ptr member in Allocation with the result. Returns true on success,
188405097246SAdrian Prantl // false otherwise
188580af0b9eSLuke Drummond bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1886b9c1b51eSKate Stone                                          StackFrame *frame_ptr, uint32_t x,
1887b9c1b51eSKate Stone                                          uint32_t y, uint32_t z) {
188815f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
188915f2bd95SEwan Crawford 
189080af0b9eSLuke Drummond   if (!alloc->address.isValid()) {
189115f2bd95SEwan Crawford     if (log)
1892b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
189315f2bd95SEwan Crawford     return false;
189415f2bd95SEwan Crawford   }
189515f2bd95SEwan Crawford 
189680af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
189780af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
189815f2bd95SEwan Crawford 
189980af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
190080af0b9eSLuke Drummond                          *alloc->address.get(), x, y, z);
190180af0b9eSLuke Drummond   if (written < 0) {
190215f2bd95SEwan Crawford     if (log)
1903b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
190415f2bd95SEwan Crawford     return false;
190580af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
190615f2bd95SEwan Crawford     if (log)
1907b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
190815f2bd95SEwan Crawford     return false;
190915f2bd95SEwan Crawford   }
191015f2bd95SEwan Crawford 
191115f2bd95SEwan Crawford   uint64_t result = 0;
191280af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
191315f2bd95SEwan Crawford     return false;
191415f2bd95SEwan Crawford 
191580af0b9eSLuke Drummond   addr_t data_ptr = static_cast<lldb::addr_t>(result);
191680af0b9eSLuke Drummond   alloc->data_ptr = data_ptr;
191715f2bd95SEwan Crawford 
191815f2bd95SEwan Crawford   return true;
191915f2bd95SEwan Crawford }
192015f2bd95SEwan Crawford 
192115f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
192280af0b9eSLuke Drummond // Then sets the type_ptr member in Allocation with the result. Returns true on
192380af0b9eSLuke Drummond // success, false otherwise
192480af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1925b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
192615f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
192715f2bd95SEwan Crawford 
192880af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->context.isValid()) {
192915f2bd95SEwan Crawford     if (log)
1930b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
193115f2bd95SEwan Crawford     return false;
193215f2bd95SEwan Crawford   }
193315f2bd95SEwan Crawford 
193480af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprAllocGetType);
193580af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
193615f2bd95SEwan Crawford 
193780af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
193880af0b9eSLuke Drummond                          *alloc->context.get(), *alloc->address.get());
193980af0b9eSLuke Drummond   if (written < 0) {
194015f2bd95SEwan Crawford     if (log)
1941b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
194215f2bd95SEwan Crawford     return false;
194380af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
194415f2bd95SEwan Crawford     if (log)
1945b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
194615f2bd95SEwan Crawford     return false;
194715f2bd95SEwan Crawford   }
194815f2bd95SEwan Crawford 
194915f2bd95SEwan Crawford   uint64_t result = 0;
195080af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
195115f2bd95SEwan Crawford     return false;
195215f2bd95SEwan Crawford 
195315f2bd95SEwan Crawford   addr_t type_ptr = static_cast<lldb::addr_t>(result);
195480af0b9eSLuke Drummond   alloc->type_ptr = type_ptr;
195515f2bd95SEwan Crawford 
195615f2bd95SEwan Crawford   return true;
195715f2bd95SEwan Crawford }
195815f2bd95SEwan Crawford 
1959b9c1b51eSKate Stone // JITs the RS runtime for information about the dimensions and type of an
196005097246SAdrian Prantl // allocation Then sets dimension and element_ptr members in Allocation with
196105097246SAdrian Prantl // the result. Returns true on success, false otherwise
196280af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1963b9c1b51eSKate Stone                                         StackFrame *frame_ptr) {
196415f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
196515f2bd95SEwan Crawford 
196680af0b9eSLuke Drummond   if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
196715f2bd95SEwan Crawford     if (log)
1968b3f7f69dSAidan Dodds       log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
196915f2bd95SEwan Crawford     return false;
197015f2bd95SEwan Crawford   }
197115f2bd95SEwan Crawford 
197215f2bd95SEwan Crawford   // Expression is different depending on if device is 32 or 64 bit
197380af0b9eSLuke Drummond   uint32_t target_ptr_size =
1974b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
197580af0b9eSLuke Drummond   const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
197615f2bd95SEwan Crawford 
197715f2bd95SEwan Crawford   // We want 4 elements from packed data
1978b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
1979b9c1b51eSKate Stone   assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) &&
1980b9c1b51eSKate Stone          "Invalid number of expressions");
198115f2bd95SEwan Crawford 
198280af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
198315f2bd95SEwan Crawford   uint64_t results[num_exprs];
198415f2bd95SEwan Crawford 
1985b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; ++i) {
198680af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
198736d783ebSDavid Gross     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str,
198836d783ebSDavid Gross                            *alloc->context.get(), bits, *alloc->type_ptr.get());
198980af0b9eSLuke Drummond     if (written < 0) {
199015f2bd95SEwan Crawford       if (log)
1991b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
199215f2bd95SEwan Crawford       return false;
199380af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
199415f2bd95SEwan Crawford       if (log)
1995b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
199615f2bd95SEwan Crawford       return false;
199715f2bd95SEwan Crawford     }
199815f2bd95SEwan Crawford 
199915f2bd95SEwan Crawford     // Perform expression evaluation
200080af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
200115f2bd95SEwan Crawford       return false;
200215f2bd95SEwan Crawford   }
200315f2bd95SEwan Crawford 
200415f2bd95SEwan Crawford   // Assign results to allocation members
200515f2bd95SEwan Crawford   AllocationDetails::Dimension dims;
200615f2bd95SEwan Crawford   dims.dim_1 = static_cast<uint32_t>(results[0]);
200715f2bd95SEwan Crawford   dims.dim_2 = static_cast<uint32_t>(results[1]);
200815f2bd95SEwan Crawford   dims.dim_3 = static_cast<uint32_t>(results[2]);
200980af0b9eSLuke Drummond   alloc->dimension = dims;
201015f2bd95SEwan Crawford 
201180af0b9eSLuke Drummond   addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
201280af0b9eSLuke Drummond   alloc->element.element_ptr = element_ptr;
201315f2bd95SEwan Crawford 
201415f2bd95SEwan Crawford   if (log)
2015b9c1b51eSKate Stone     log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
2016b9c1b51eSKate Stone                 ") Element*: 0x%" PRIx64 ".",
201780af0b9eSLuke Drummond                 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
201815f2bd95SEwan Crawford 
201915f2bd95SEwan Crawford   return true;
202015f2bd95SEwan Crawford }
202115f2bd95SEwan Crawford 
202280af0b9eSLuke Drummond // JITs the RS runtime for information about the Element of an allocation Then
202380af0b9eSLuke Drummond // sets type, type_vec_size, field_count and type_kind members in Element with
202480af0b9eSLuke Drummond // the result. Returns true on success, false otherwise
2025b9c1b51eSKate Stone bool RenderScriptRuntime::JITElementPacked(Element &elem,
2026b9c1b51eSKate Stone                                            const lldb::addr_t context,
2027b9c1b51eSKate Stone                                            StackFrame *frame_ptr) {
202815f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
202915f2bd95SEwan Crawford 
2030b9c1b51eSKate Stone   if (!elem.element_ptr.isValid()) {
203115f2bd95SEwan Crawford     if (log)
2032b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
203315f2bd95SEwan Crawford     return false;
203415f2bd95SEwan Crawford   }
203515f2bd95SEwan Crawford 
20368b244e21SEwan Crawford   // We want 4 elements from packed data
2037b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
2038b9c1b51eSKate Stone   assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) &&
2039b9c1b51eSKate Stone          "Invalid number of expressions");
204015f2bd95SEwan Crawford 
204180af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
204215f2bd95SEwan Crawford   uint64_t results[num_exprs];
204315f2bd95SEwan Crawford 
2044b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; i++) {
204580af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
204680af0b9eSLuke Drummond     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
204780af0b9eSLuke Drummond                            *elem.element_ptr.get());
204880af0b9eSLuke Drummond     if (written < 0) {
204915f2bd95SEwan Crawford       if (log)
2050b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
205115f2bd95SEwan Crawford       return false;
205280af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
205315f2bd95SEwan Crawford       if (log)
2054b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
205515f2bd95SEwan Crawford       return false;
205615f2bd95SEwan Crawford     }
205715f2bd95SEwan Crawford 
205815f2bd95SEwan Crawford     // Perform expression evaluation
205980af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
206015f2bd95SEwan Crawford       return false;
206115f2bd95SEwan Crawford   }
206215f2bd95SEwan Crawford 
206315f2bd95SEwan Crawford   // Assign results to allocation members
20648b244e21SEwan Crawford   elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
2065b9c1b51eSKate Stone   elem.type_kind =
2066b9c1b51eSKate Stone       static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
20678b244e21SEwan Crawford   elem.type_vec_size = static_cast<uint32_t>(results[2]);
20688b244e21SEwan Crawford   elem.field_count = static_cast<uint32_t>(results[3]);
206915f2bd95SEwan Crawford 
207015f2bd95SEwan Crawford   if (log)
2071b9c1b51eSKate Stone     log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32
2072b9c1b51eSKate Stone                 ", vector size %" PRIu32 ", field count %" PRIu32,
2073b9c1b51eSKate Stone                 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
2074b9c1b51eSKate Stone                 *elem.type_vec_size.get(), *elem.field_count.get());
20758b244e21SEwan Crawford 
2076b9c1b51eSKate Stone   // If this Element has subelements then JIT rsaElementGetSubElements() for
2077b9c1b51eSKate Stone   // details about its fields
2078a6682a41SJonas Devlieghere   return !(*elem.field_count.get() > 0 &&
2079a6682a41SJonas Devlieghere            !JITSubelements(elem, context, frame_ptr));
20808b244e21SEwan Crawford }
20818b244e21SEwan Crawford 
2082b9c1b51eSKate Stone // JITs the RS runtime for information about the subelements/fields of a struct
208380af0b9eSLuke Drummond // allocation This is necessary for infering the struct type so we can pretty
208480af0b9eSLuke Drummond // print the allocation's contents. Returns true on success, false otherwise
2085b9c1b51eSKate Stone bool RenderScriptRuntime::JITSubelements(Element &elem,
2086b9c1b51eSKate Stone                                          const lldb::addr_t context,
2087b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
20888b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
20898b244e21SEwan Crawford 
2090b9c1b51eSKate Stone   if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
20918b244e21SEwan Crawford     if (log)
2092b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
20938b244e21SEwan Crawford     return false;
20948b244e21SEwan Crawford   }
20958b244e21SEwan Crawford 
20968b244e21SEwan Crawford   const short num_exprs = 3;
2097b9c1b51eSKate Stone   assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) &&
2098b9c1b51eSKate Stone          "Invalid number of expressions");
20998b244e21SEwan Crawford 
2100ea0636b5SEwan Crawford   char expr_buffer[jit_max_expr_size];
21018b244e21SEwan Crawford   uint64_t results;
21028b244e21SEwan Crawford 
21038b244e21SEwan Crawford   // Iterate over struct fields.
21048b244e21SEwan Crawford   const uint32_t field_count = *elem.field_count.get();
2105b9c1b51eSKate Stone   for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
21068b244e21SEwan Crawford     Element child;
2107b9c1b51eSKate Stone     for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
210880af0b9eSLuke Drummond       const char *fmt_str =
2109b9c1b51eSKate Stone           JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
211080af0b9eSLuke Drummond       int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
211136d783ebSDavid Gross                              context, field_count, field_count, field_count,
211280af0b9eSLuke Drummond                              *elem.element_ptr.get(), field_count, field_index);
211380af0b9eSLuke Drummond       if (written < 0) {
21148b244e21SEwan Crawford         if (log)
2115b3f7f69dSAidan Dodds           log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
21168b244e21SEwan Crawford         return false;
211780af0b9eSLuke Drummond       } else if (written >= jit_max_expr_size) {
21188b244e21SEwan Crawford         if (log)
2119b3f7f69dSAidan Dodds           log->Printf("%s - expression too long.", __FUNCTION__);
21208b244e21SEwan Crawford         return false;
21218b244e21SEwan Crawford       }
21228b244e21SEwan Crawford 
21238b244e21SEwan Crawford       // Perform expression evaluation
21248b244e21SEwan Crawford       if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
21258b244e21SEwan Crawford         return false;
21268b244e21SEwan Crawford 
21278b244e21SEwan Crawford       if (log)
2128b3f7f69dSAidan Dodds         log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
21298b244e21SEwan Crawford 
2130b9c1b51eSKate Stone       switch (expr_index) {
21318b244e21SEwan Crawford       case 0: // Element* of child
21328b244e21SEwan Crawford         child.element_ptr = static_cast<addr_t>(results);
21338b244e21SEwan Crawford         break;
21348b244e21SEwan Crawford       case 1: // Name of child
21358b244e21SEwan Crawford       {
21368b244e21SEwan Crawford         lldb::addr_t address = static_cast<addr_t>(results);
213797206d57SZachary Turner         Status err;
21388b244e21SEwan Crawford         std::string name;
21398b244e21SEwan Crawford         GetProcess()->ReadCStringFromMemory(address, name, err);
21408b244e21SEwan Crawford         if (!err.Fail())
21418b244e21SEwan Crawford           child.type_name = ConstString(name);
2142b9c1b51eSKate Stone         else {
21438b244e21SEwan Crawford           if (log)
2144b9c1b51eSKate Stone             log->Printf("%s - warning: Couldn't read field name.",
2145b9c1b51eSKate Stone                         __FUNCTION__);
21468b244e21SEwan Crawford         }
21478b244e21SEwan Crawford         break;
21488b244e21SEwan Crawford       }
21498b244e21SEwan Crawford       case 2: // Array size of child
21508b244e21SEwan Crawford         child.array_size = static_cast<uint32_t>(results);
21518b244e21SEwan Crawford         break;
21528b244e21SEwan Crawford       }
21538b244e21SEwan Crawford     }
21548b244e21SEwan Crawford 
21558b244e21SEwan Crawford     // We need to recursively JIT each Element field of the struct since
21568b244e21SEwan Crawford     // structs can be nested inside structs.
21578b244e21SEwan Crawford     if (!JITElementPacked(child, context, frame_ptr))
21588b244e21SEwan Crawford       return false;
21598b244e21SEwan Crawford     elem.children.push_back(child);
21608b244e21SEwan Crawford   }
21618b244e21SEwan Crawford 
2162b9c1b51eSKate Stone   // Try to infer the name of the struct type so we can pretty print the
2163b9c1b51eSKate Stone   // allocation contents.
21648b244e21SEwan Crawford   FindStructTypeName(elem, frame_ptr);
216515f2bd95SEwan Crawford 
216615f2bd95SEwan Crawford   return true;
216715f2bd95SEwan Crawford }
216815f2bd95SEwan Crawford 
2169a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
2170b9c1b51eSKate Stone // The `elem_size` parameter represents the size of a single element, including
217180af0b9eSLuke Drummond // padding. Which is needed as an offset from the last element pointer. Using
217280af0b9eSLuke Drummond // this offset minus the starting address we can calculate the size of the
217380af0b9eSLuke Drummond // allocation. Returns true on success, false otherwise
217480af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
2175b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
2176a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2177a0f08674SEwan Crawford 
217880af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
217980af0b9eSLuke Drummond       !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
2180a0f08674SEwan Crawford     if (log)
2181b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2182a0f08674SEwan Crawford     return false;
2183a0f08674SEwan Crawford   }
2184a0f08674SEwan Crawford 
2185a0f08674SEwan Crawford   // Find dimensions
218680af0b9eSLuke Drummond   uint32_t dim_x = alloc->dimension.get()->dim_1;
218780af0b9eSLuke Drummond   uint32_t dim_y = alloc->dimension.get()->dim_2;
218880af0b9eSLuke Drummond   uint32_t dim_z = alloc->dimension.get()->dim_3;
2189a0f08674SEwan Crawford 
2190b9c1b51eSKate Stone   // Our plan of jitting the last element address doesn't seem to work for
219180af0b9eSLuke Drummond   // struct Allocations` Instead try to infer the size ourselves without any
219280af0b9eSLuke Drummond   // inter element padding.
219380af0b9eSLuke Drummond   if (alloc->element.children.size() > 0) {
2194b9c1b51eSKate Stone     if (dim_x == 0)
2195b9c1b51eSKate Stone       dim_x = 1;
2196b9c1b51eSKate Stone     if (dim_y == 0)
2197b9c1b51eSKate Stone       dim_y = 1;
2198b9c1b51eSKate Stone     if (dim_z == 0)
2199b9c1b51eSKate Stone       dim_z = 1;
22008b244e21SEwan Crawford 
220180af0b9eSLuke Drummond     alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
22028b244e21SEwan Crawford 
22038b244e21SEwan Crawford     if (log)
2204b9c1b51eSKate Stone       log->Printf("%s - inferred size of struct allocation %" PRIu32 ".",
220580af0b9eSLuke Drummond                   __FUNCTION__, *alloc->size.get());
22068b244e21SEwan Crawford     return true;
22078b244e21SEwan Crawford   }
22088b244e21SEwan Crawford 
220980af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
221080af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
22118b244e21SEwan Crawford 
2212a0f08674SEwan Crawford   // Calculate last element
2213a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 0 : dim_x - 1;
2214a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 0 : dim_y - 1;
2215a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 0 : dim_z - 1;
2216a0f08674SEwan Crawford 
221780af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
221880af0b9eSLuke Drummond                          *alloc->address.get(), dim_x, dim_y, dim_z);
221980af0b9eSLuke Drummond   if (written < 0) {
2220a0f08674SEwan Crawford     if (log)
2221b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2222a0f08674SEwan Crawford     return false;
222380af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
2224a0f08674SEwan Crawford     if (log)
2225b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
2226a0f08674SEwan Crawford     return false;
2227a0f08674SEwan Crawford   }
2228a0f08674SEwan Crawford 
2229a0f08674SEwan Crawford   uint64_t result = 0;
223080af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2231a0f08674SEwan Crawford     return false;
2232a0f08674SEwan Crawford 
2233a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2234a0f08674SEwan Crawford   // Find pointer to last element and add on size of an element
223580af0b9eSLuke Drummond   alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
223680af0b9eSLuke Drummond                 *alloc->element.datum_size.get();
2237a0f08674SEwan Crawford 
2238a0f08674SEwan Crawford   return true;
2239a0f08674SEwan Crawford }
2240a0f08674SEwan Crawford 
2241b9c1b51eSKate Stone // JITs the RS runtime for information about the stride between rows in the
224205097246SAdrian Prantl // allocation. This is done to detect padding, since allocated memory is
224305097246SAdrian Prantl // 16-byte aligned. Returns true on success, false otherwise
224480af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
2245b9c1b51eSKate Stone                                               StackFrame *frame_ptr) {
2246a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2247a0f08674SEwan Crawford 
224880af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
2249a0f08674SEwan Crawford     if (log)
2250b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2251a0f08674SEwan Crawford     return false;
2252a0f08674SEwan Crawford   }
2253a0f08674SEwan Crawford 
225480af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
225580af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
2256a0f08674SEwan Crawford 
225780af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
225880af0b9eSLuke Drummond                          *alloc->address.get(), 0, 1, 0);
225980af0b9eSLuke Drummond   if (written < 0) {
2260a0f08674SEwan Crawford     if (log)
2261b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2262a0f08674SEwan Crawford     return false;
226380af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
2264a0f08674SEwan Crawford     if (log)
2265b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
2266a0f08674SEwan Crawford     return false;
2267a0f08674SEwan Crawford   }
2268a0f08674SEwan Crawford 
2269a0f08674SEwan Crawford   uint64_t result = 0;
227080af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2271a0f08674SEwan Crawford     return false;
2272a0f08674SEwan Crawford 
2273a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
227480af0b9eSLuke Drummond   alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
2275a0f08674SEwan Crawford 
2276a0f08674SEwan Crawford   return true;
2277a0f08674SEwan Crawford }
2278a0f08674SEwan Crawford 
227915f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
228080af0b9eSLuke Drummond bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2281b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
228215f2bd95SEwan Crawford   // GetOffsetPointer()
228380af0b9eSLuke Drummond   if (!JITDataPointer(alloc, frame_ptr))
228415f2bd95SEwan Crawford     return false;
228515f2bd95SEwan Crawford 
228615f2bd95SEwan Crawford   // rsaAllocationGetType()
228780af0b9eSLuke Drummond   if (!JITTypePointer(alloc, frame_ptr))
228815f2bd95SEwan Crawford     return false;
228915f2bd95SEwan Crawford 
229015f2bd95SEwan Crawford   // rsaTypeGetNativeData()
229180af0b9eSLuke Drummond   if (!JITTypePacked(alloc, frame_ptr))
229215f2bd95SEwan Crawford     return false;
229315f2bd95SEwan Crawford 
229415f2bd95SEwan Crawford   // rsaElementGetNativeData()
229580af0b9eSLuke Drummond   if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
229615f2bd95SEwan Crawford     return false;
229715f2bd95SEwan Crawford 
22988b244e21SEwan Crawford   // Sets the datum_size member in Element
229980af0b9eSLuke Drummond   SetElementSize(alloc->element);
23008b244e21SEwan Crawford 
230155232f09SEwan Crawford   // Use GetOffsetPointer() to infer size of the allocation
2302a6682a41SJonas Devlieghere   return JITAllocationSize(alloc, frame_ptr);
230355232f09SEwan Crawford }
230455232f09SEwan Crawford 
2305b9c1b51eSKate Stone // Function attempts to set the type_name member of the paramaterised Element
230605097246SAdrian Prantl // object. This string should be the name of the struct type the Element
230705097246SAdrian Prantl // represents. We need this string for pretty printing the Element to users.
2308b9c1b51eSKate Stone void RenderScriptRuntime::FindStructTypeName(Element &elem,
2309b9c1b51eSKate Stone                                              StackFrame *frame_ptr) {
23108b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
23118b244e21SEwan Crawford 
23128b244e21SEwan Crawford   if (!elem.type_name.IsEmpty()) // Name already set
23138b244e21SEwan Crawford     return;
23148b244e21SEwan Crawford   else
2315b9c1b51eSKate Stone     elem.type_name = Element::GetFallbackStructName(); // Default type name if
2316b9c1b51eSKate Stone                                                        // we don't succeed
23178b244e21SEwan Crawford 
23188b244e21SEwan Crawford   // Find all the global variables from the script rs modules
231980af0b9eSLuke Drummond   VariableList var_list;
23208b244e21SEwan Crawford   for (auto module_sp : m_rsmodules)
232195eae423SZachary Turner     module_sp->m_module->FindGlobalVariables(
232234cda14bSPavel Labath         RegularExpression(llvm::StringRef(".")), UINT32_MAX, var_list);
23238b244e21SEwan Crawford 
2324b9c1b51eSKate Stone   // Iterate over all the global variables looking for one with a matching type
232505097246SAdrian Prantl   // to the Element. We make the assumption a match exists since there needs to
232605097246SAdrian Prantl   // be a global variable to reflect the struct type back into java host code.
232780af0b9eSLuke Drummond   for (uint32_t i = 0; i < var_list.GetSize(); ++i) {
232880af0b9eSLuke Drummond     const VariableSP var_sp(var_list.GetVariableAtIndex(i));
23298b244e21SEwan Crawford     if (!var_sp)
23308b244e21SEwan Crawford       continue;
23318b244e21SEwan Crawford 
23328b244e21SEwan Crawford     ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
23338b244e21SEwan Crawford     if (!valobj_sp)
23348b244e21SEwan Crawford       continue;
23358b244e21SEwan Crawford 
23368b244e21SEwan Crawford     // Find the number of variable fields.
2337b9c1b51eSKate Stone     // If it has no fields, or more fields than our Element, then it can't be
233805097246SAdrian Prantl     // the struct we're looking for. Don't check for equality since RS can add
233905097246SAdrian Prantl     // extra struct members for padding.
23408b244e21SEwan Crawford     size_t num_children = valobj_sp->GetNumChildren();
23418b244e21SEwan Crawford     if (num_children > elem.children.size() || num_children == 0)
23428b244e21SEwan Crawford       continue;
23438b244e21SEwan Crawford 
234405097246SAdrian Prantl     // Iterate over children looking for members with matching field names. If
234505097246SAdrian Prantl     // all the field names match, this is likely the struct we want.
2346b9c1b51eSKate Stone     //   TODO: This could be made more robust by also checking children data
2347b9c1b51eSKate Stone     //   sizes, or array size
23488b244e21SEwan Crawford     bool found = true;
234980af0b9eSLuke Drummond     for (size_t i = 0; i < num_children; ++i) {
235080af0b9eSLuke Drummond       ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
235180af0b9eSLuke Drummond       if (!child || (child->GetName() != elem.children[i].type_name)) {
23528b244e21SEwan Crawford         found = false;
23538b244e21SEwan Crawford         break;
23548b244e21SEwan Crawford       }
23558b244e21SEwan Crawford     }
23568b244e21SEwan Crawford 
2357b9c1b51eSKate Stone     // RS can add extra struct members for padding in the format
2358b9c1b51eSKate Stone     // '#rs_padding_[0-9]+'
2359b9c1b51eSKate Stone     if (found && num_children < elem.children.size()) {
2360b3f7f69dSAidan Dodds       const uint32_t size_diff = elem.children.size() - num_children;
23618b244e21SEwan Crawford       if (log)
2362b9c1b51eSKate Stone         log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2363b9c1b51eSKate Stone                     size_diff);
23648b244e21SEwan Crawford 
236580af0b9eSLuke Drummond       for (uint32_t i = 0; i < size_diff; ++i) {
236680af0b9eSLuke Drummond         const ConstString &name = elem.children[num_children + i].type_name;
23678b244e21SEwan Crawford         if (strcmp(name.AsCString(), "#rs_padding") < 0)
23688b244e21SEwan Crawford           found = false;
23698b244e21SEwan Crawford       }
23708b244e21SEwan Crawford     }
23718b244e21SEwan Crawford 
237280af0b9eSLuke Drummond     // We've found a global variable with matching type
2373b9c1b51eSKate Stone     if (found) {
23748b244e21SEwan Crawford       // Dereference since our Element type isn't a pointer.
2375b9c1b51eSKate Stone       if (valobj_sp->IsPointerType()) {
237697206d57SZachary Turner         Status err;
23778b244e21SEwan Crawford         ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
23788b244e21SEwan Crawford         if (!err.Fail())
23798b244e21SEwan Crawford           valobj_sp = deref_valobj;
23808b244e21SEwan Crawford       }
23818b244e21SEwan Crawford 
23828b244e21SEwan Crawford       // Save name of variable in Element.
23838b244e21SEwan Crawford       elem.type_name = valobj_sp->GetTypeName();
23848b244e21SEwan Crawford       if (log)
2385b9c1b51eSKate Stone         log->Printf("%s - element name set to %s", __FUNCTION__,
2386b9c1b51eSKate Stone                     elem.type_name.AsCString());
23878b244e21SEwan Crawford 
23888b244e21SEwan Crawford       return;
23898b244e21SEwan Crawford     }
23908b244e21SEwan Crawford   }
23918b244e21SEwan Crawford }
23928b244e21SEwan Crawford 
2393b9c1b51eSKate Stone // Function sets the datum_size member of Element. Representing the size of a
239405097246SAdrian Prantl // single instance including padding. Assumes the relevant allocation
239505097246SAdrian Prantl // information has already been jitted.
2396b9c1b51eSKate Stone void RenderScriptRuntime::SetElementSize(Element &elem) {
23978b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
23988b244e21SEwan Crawford   const Element::DataType type = *elem.type.get();
2399b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2400b9c1b51eSKate Stone          "Invalid allocation type");
240155232f09SEwan Crawford 
2402b3f7f69dSAidan Dodds   const uint32_t vec_size = *elem.type_vec_size.get();
2403b3f7f69dSAidan Dodds   uint32_t data_size = 0;
2404b3f7f69dSAidan Dodds   uint32_t padding = 0;
240555232f09SEwan Crawford 
24068b244e21SEwan Crawford   // Element is of a struct type, calculate size recursively.
2407b9c1b51eSKate Stone   if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2408b9c1b51eSKate Stone     for (Element &child : elem.children) {
24098b244e21SEwan Crawford       SetElementSize(child);
2410b9c1b51eSKate Stone       const uint32_t array_size =
2411b9c1b51eSKate Stone           child.array_size.isValid() ? *child.array_size.get() : 1;
24128b244e21SEwan Crawford       data_size += *child.datum_size.get() * array_size;
24138b244e21SEwan Crawford     }
24148b244e21SEwan Crawford   }
2415b3f7f69dSAidan Dodds   // These have been packed already
2416b3f7f69dSAidan Dodds   else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2417b3f7f69dSAidan Dodds            type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2418b9c1b51eSKate Stone            type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
24192e920715SEwan Crawford     data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2420b9c1b51eSKate Stone   } else if (type < Element::RS_TYPE_ELEMENT) {
2421b9c1b51eSKate Stone     data_size =
2422b9c1b51eSKate Stone         vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
24232e920715SEwan Crawford     if (vec_size == 3)
24242e920715SEwan Crawford       padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2425b9c1b51eSKate Stone   } else
2426b9c1b51eSKate Stone     data_size =
2427b9c1b51eSKate Stone         GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
24288b244e21SEwan Crawford 
24298b244e21SEwan Crawford   elem.padding = padding;
24308b244e21SEwan Crawford   elem.datum_size = data_size + padding;
24318b244e21SEwan Crawford   if (log)
2432b9c1b51eSKate Stone     log->Printf("%s - element size set to %" PRIu32, __FUNCTION__,
2433b9c1b51eSKate Stone                 data_size + padding);
243455232f09SEwan Crawford }
243555232f09SEwan Crawford 
243605097246SAdrian Prantl // Given an allocation, this function copies the allocation contents from
243705097246SAdrian Prantl // device into a buffer on the heap. Returning a shared pointer to the buffer
243805097246SAdrian Prantl // containing the data.
243955232f09SEwan Crawford std::shared_ptr<uint8_t>
244080af0b9eSLuke Drummond RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2441b9c1b51eSKate Stone                                        StackFrame *frame_ptr) {
244255232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
244355232f09SEwan Crawford 
244455232f09SEwan Crawford   // JIT all the allocation details
244580af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
244655232f09SEwan Crawford     if (log)
2447b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info",
2448b9c1b51eSKate Stone                   __FUNCTION__);
244955232f09SEwan Crawford 
245080af0b9eSLuke Drummond     if (!RefreshAllocation(alloc, frame_ptr)) {
245155232f09SEwan Crawford       if (log)
2452b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
245355232f09SEwan Crawford       return nullptr;
245455232f09SEwan Crawford     }
245555232f09SEwan Crawford   }
245655232f09SEwan Crawford 
245780af0b9eSLuke Drummond   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
245880af0b9eSLuke Drummond          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
245980af0b9eSLuke Drummond          "Allocation information not available");
246055232f09SEwan Crawford 
246155232f09SEwan Crawford   // Allocate a buffer to copy data into
246280af0b9eSLuke Drummond   const uint32_t size = *alloc->size.get();
246355232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2464b9c1b51eSKate Stone   if (!buffer) {
246555232f09SEwan Crawford     if (log)
2466b9c1b51eSKate Stone       log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer",
2467b9c1b51eSKate Stone                   __FUNCTION__, size);
246855232f09SEwan Crawford     return nullptr;
246955232f09SEwan Crawford   }
247055232f09SEwan Crawford 
247155232f09SEwan Crawford   // Read the inferior memory
247297206d57SZachary Turner   Status err;
247380af0b9eSLuke Drummond   lldb::addr_t data_ptr = *alloc->data_ptr.get();
247480af0b9eSLuke Drummond   GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
247580af0b9eSLuke Drummond   if (err.Fail()) {
247655232f09SEwan Crawford     if (log)
2477b9c1b51eSKate Stone       log->Printf("%s - '%s' Couldn't read %" PRIu32
2478b9c1b51eSKate Stone                   " bytes of allocation data from 0x%" PRIx64,
247980af0b9eSLuke Drummond                   __FUNCTION__, err.AsCString(), size, data_ptr);
248055232f09SEwan Crawford     return nullptr;
248155232f09SEwan Crawford   }
248255232f09SEwan Crawford 
248355232f09SEwan Crawford   return buffer;
248455232f09SEwan Crawford }
248555232f09SEwan Crawford 
248605097246SAdrian Prantl // Function copies data from a binary file into an allocation. There is a
248705097246SAdrian Prantl // header at the start of the file, FileHeader, before the data content itself.
2488b9c1b51eSKate Stone // Information from this header is used to display warnings to the user about
2489b9c1b51eSKate Stone // incompatibilities
2490b9c1b51eSKate Stone bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
249180af0b9eSLuke Drummond                                          const char *path,
2492b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
249355232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
249455232f09SEwan Crawford 
249555232f09SEwan Crawford   // Find allocation with the given id
249655232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
249755232f09SEwan Crawford   if (!alloc)
249855232f09SEwan Crawford     return false;
249955232f09SEwan Crawford 
250055232f09SEwan Crawford   if (log)
2501b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2502b9c1b51eSKate Stone                 *alloc->address.get());
250355232f09SEwan Crawford 
250455232f09SEwan Crawford   // JIT all the allocation details
250580af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
250655232f09SEwan Crawford     if (log)
2507b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2508b9c1b51eSKate Stone                   __FUNCTION__);
250955232f09SEwan Crawford 
2510b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
251155232f09SEwan Crawford       if (log)
2512b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
25134cfc9198SSylvestre Ledru       return false;
251455232f09SEwan Crawford     }
251555232f09SEwan Crawford   }
251655232f09SEwan Crawford 
2517b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2518b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2519b9c1b51eSKate Stone          alloc->element.datum_size.isValid() &&
2520b9c1b51eSKate Stone          "Allocation information not available");
252155232f09SEwan Crawford 
252255232f09SEwan Crawford   // Check we can read from file
25238f3be7a3SJonas Devlieghere   FileSpec file(path);
25248f3be7a3SJonas Devlieghere   FileSystem::Instance().Resolve(file);
2525dbd7fabaSJonas Devlieghere   if (!FileSystem::Instance().Exists(file)) {
252680af0b9eSLuke Drummond     strm.Printf("Error: File %s does not exist", path);
252755232f09SEwan Crawford     strm.EOL();
252855232f09SEwan Crawford     return false;
252955232f09SEwan Crawford   }
253055232f09SEwan Crawford 
25317c5310bbSJonas Devlieghere   if (!FileSystem::Instance().Readable(file)) {
253280af0b9eSLuke Drummond     strm.Printf("Error: File %s does not have readable permissions", path);
253355232f09SEwan Crawford     strm.EOL();
253455232f09SEwan Crawford     return false;
253555232f09SEwan Crawford   }
253655232f09SEwan Crawford 
253755232f09SEwan Crawford   // Read file into data buffer
253887e403aaSJonas Devlieghere   auto data_sp = FileSystem::Instance().CreateDataBuffer(file.GetPath());
253955232f09SEwan Crawford 
254055232f09SEwan Crawford   // Cast start of buffer to FileHeader and use pointer to read metadata
254180af0b9eSLuke Drummond   void *file_buf = data_sp->GetBytes();
254280af0b9eSLuke Drummond   if (file_buf == nullptr ||
2543b9c1b51eSKate Stone       data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2544b9c1b51eSKate Stone                                 sizeof(AllocationDetails::ElementHeader))) {
254580af0b9eSLuke Drummond     strm.Printf("Error: File %s does not contain enough data for header", path);
254626e52a70SEwan Crawford     strm.EOL();
254726e52a70SEwan Crawford     return false;
254826e52a70SEwan Crawford   }
2549b9c1b51eSKate Stone   const AllocationDetails::FileHeader *file_header =
255080af0b9eSLuke Drummond       static_cast<AllocationDetails::FileHeader *>(file_buf);
255155232f09SEwan Crawford 
255226e52a70SEwan Crawford   // Check file starts with ascii characters "RSAD"
2553b9c1b51eSKate Stone   if (memcmp(file_header->ident, "RSAD", 4)) {
2554b9c1b51eSKate Stone     strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2555b9c1b51eSKate Stone                 "dump. Are you sure this is the correct file?");
255626e52a70SEwan Crawford     strm.EOL();
255726e52a70SEwan Crawford     return false;
255826e52a70SEwan Crawford   }
255926e52a70SEwan Crawford 
256026e52a70SEwan Crawford   // Look at the type of the root element in the header
256180af0b9eSLuke Drummond   AllocationDetails::ElementHeader root_el_hdr;
256280af0b9eSLuke Drummond   memcpy(&root_el_hdr, static_cast<uint8_t *>(file_buf) +
2563b9c1b51eSKate Stone                            sizeof(AllocationDetails::FileHeader),
256426e52a70SEwan Crawford          sizeof(AllocationDetails::ElementHeader));
256555232f09SEwan Crawford 
256655232f09SEwan Crawford   if (log)
2567b9c1b51eSKate Stone     log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32,
256880af0b9eSLuke Drummond                 __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
256955232f09SEwan Crawford 
2570b9c1b51eSKate Stone   // Check if the target allocation and file both have the same number of bytes
2571b9c1b51eSKate Stone   // for an Element
257280af0b9eSLuke Drummond   if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2573b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2574b9c1b51eSKate Stone                 " bytes, allocation %" PRIu32 " bytes",
257580af0b9eSLuke Drummond                 root_el_hdr.element_size, *alloc->element.datum_size.get());
257655232f09SEwan Crawford     strm.EOL();
257755232f09SEwan Crawford   }
257855232f09SEwan Crawford 
257926e52a70SEwan Crawford   // Check if the target allocation and file both have the same type
2580b3f7f69dSAidan Dodds   const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
258180af0b9eSLuke Drummond   const uint32_t file_type = root_el_hdr.type;
258226e52a70SEwan Crawford 
2583b9c1b51eSKate Stone   if (file_type > Element::RS_TYPE_FONT) {
258426e52a70SEwan Crawford     strm.Printf("Warning: File has unknown allocation type");
258526e52a70SEwan Crawford     strm.EOL();
2586b9c1b51eSKate Stone   } else if (alloc_type != file_type) {
2587b9c1b51eSKate Stone     // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2588b9c1b51eSKate Stone     // array
258980af0b9eSLuke Drummond     uint32_t target_type_name_idx = alloc_type;
259080af0b9eSLuke Drummond     uint32_t head_type_name_idx = file_type;
2591b9c1b51eSKate Stone     if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2592b9c1b51eSKate Stone         alloc_type <= Element::RS_TYPE_FONT)
259380af0b9eSLuke Drummond       target_type_name_idx = static_cast<Element::DataType>(
2594b9c1b51eSKate Stone           (alloc_type - Element::RS_TYPE_ELEMENT) +
2595b3f7f69dSAidan Dodds           Element::RS_TYPE_MATRIX_2X2 + 1);
25962e920715SEwan Crawford 
2597b9c1b51eSKate Stone     if (file_type >= Element::RS_TYPE_ELEMENT &&
2598b9c1b51eSKate Stone         file_type <= Element::RS_TYPE_FONT)
259980af0b9eSLuke Drummond       head_type_name_idx = static_cast<Element::DataType>(
2600b9c1b51eSKate Stone           (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2601b9c1b51eSKate Stone           1);
26022e920715SEwan Crawford 
260380af0b9eSLuke Drummond     const char *head_type_name =
260480af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
260580af0b9eSLuke Drummond     const char *target_type_name =
260680af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
260755232f09SEwan Crawford 
2608b9c1b51eSKate Stone     strm.Printf(
2609b9c1b51eSKate Stone         "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
261080af0b9eSLuke Drummond         head_type_name, target_type_name);
261155232f09SEwan Crawford     strm.EOL();
261255232f09SEwan Crawford   }
261355232f09SEwan Crawford 
261426e52a70SEwan Crawford   // Advance buffer past header
261580af0b9eSLuke Drummond   file_buf = static_cast<uint8_t *>(file_buf) + file_header->hdr_size;
261626e52a70SEwan Crawford 
261755232f09SEwan Crawford   // Calculate size of allocation data in file
261880af0b9eSLuke Drummond   size_t size = data_sp->GetByteSize() - file_header->hdr_size;
261955232f09SEwan Crawford 
262005097246SAdrian Prantl   // Check if the target allocation and file both have the same total data
262105097246SAdrian Prantl   // size.
2622b3f7f69dSAidan Dodds   const uint32_t alloc_size = *alloc->size.get();
262380af0b9eSLuke Drummond   if (alloc_size != size) {
2624b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2625b9c1b51eSKate Stone                 " bytes, allocation 0x%" PRIx32 " bytes",
262680af0b9eSLuke Drummond                 (uint64_t)size, alloc_size);
262755232f09SEwan Crawford     strm.EOL();
262880af0b9eSLuke Drummond     // Set length to copy to minimum
262980af0b9eSLuke Drummond     size = alloc_size < size ? alloc_size : size;
263055232f09SEwan Crawford   }
263155232f09SEwan Crawford 
263255232f09SEwan Crawford   // Copy file data from our buffer into the target allocation.
263355232f09SEwan Crawford   lldb::addr_t alloc_data = *alloc->data_ptr.get();
263497206d57SZachary Turner   Status err;
263580af0b9eSLuke Drummond   size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
263680af0b9eSLuke Drummond   if (!err.Success() || written != size) {
263780af0b9eSLuke Drummond     strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
263855232f09SEwan Crawford     strm.EOL();
263955232f09SEwan Crawford     return false;
264055232f09SEwan Crawford   }
264155232f09SEwan Crawford 
264280af0b9eSLuke Drummond   strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2643b9c1b51eSKate Stone               alloc->id);
264455232f09SEwan Crawford   strm.EOL();
264555232f09SEwan Crawford 
264655232f09SEwan Crawford   return true;
264755232f09SEwan Crawford }
264855232f09SEwan Crawford 
2649b9c1b51eSKate Stone // Function takes as parameters a byte buffer, which will eventually be written
265080af0b9eSLuke Drummond // to file as the element header, an offset into that buffer, and an Element
265105097246SAdrian Prantl // that will be saved into the buffer at the parametrised offset. Return value
265205097246SAdrian Prantl // is the new offset after writing the element into the buffer. Elements are
265305097246SAdrian Prantl // saved to the file as the ElementHeader struct followed by offsets to the
265405097246SAdrian Prantl // structs of all the element's children.
2655b9c1b51eSKate Stone size_t RenderScriptRuntime::PopulateElementHeaders(
2656b9c1b51eSKate Stone     const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2657b9c1b51eSKate Stone     const Element &elem) {
265805097246SAdrian Prantl   // File struct for an element header with all the relevant details copied
265905097246SAdrian Prantl   // from elem. We assume members are valid already.
266026e52a70SEwan Crawford   AllocationDetails::ElementHeader elem_header;
266126e52a70SEwan Crawford   elem_header.type = *elem.type.get();
266226e52a70SEwan Crawford   elem_header.kind = *elem.type_kind.get();
266326e52a70SEwan Crawford   elem_header.element_size = *elem.datum_size.get();
266426e52a70SEwan Crawford   elem_header.vector_size = *elem.type_vec_size.get();
2665b9c1b51eSKate Stone   elem_header.array_size =
2666b9c1b51eSKate Stone       elem.array_size.isValid() ? *elem.array_size.get() : 0;
266726e52a70SEwan Crawford   const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
266826e52a70SEwan Crawford 
266905097246SAdrian Prantl   // Copy struct into buffer and advance offset We assume that header_buffer
267005097246SAdrian Prantl   // has been checked for nullptr before this method is called
267126e52a70SEwan Crawford   memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
267226e52a70SEwan Crawford   offset += elem_header_size;
267326e52a70SEwan Crawford 
267426e52a70SEwan Crawford   // Starting offset of child ElementHeader struct
2675b9c1b51eSKate Stone   size_t child_offset =
2676b9c1b51eSKate Stone       offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2677b9c1b51eSKate Stone   for (const RenderScriptRuntime::Element &child : elem.children) {
2678b9c1b51eSKate Stone     // Recursively populate the buffer with the element header structs of
267980af0b9eSLuke Drummond     // children. Then save the offsets where they were set after the parent
268080af0b9eSLuke Drummond     // element header.
268126e52a70SEwan Crawford     memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
268226e52a70SEwan Crawford     offset += sizeof(uint32_t);
268326e52a70SEwan Crawford 
268426e52a70SEwan Crawford     child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
268526e52a70SEwan Crawford   }
268626e52a70SEwan Crawford 
268726e52a70SEwan Crawford   // Zero indicates no more children
268826e52a70SEwan Crawford   memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
268926e52a70SEwan Crawford 
269026e52a70SEwan Crawford   return child_offset;
269126e52a70SEwan Crawford }
269226e52a70SEwan Crawford 
2693b9c1b51eSKate Stone // Given an Element object this function returns the total size needed in the
269480af0b9eSLuke Drummond // file header to store the element's details. Taking into account the size of
269580af0b9eSLuke Drummond // the element header struct, plus the offsets to all the element's children.
2696b9c1b51eSKate Stone // Function is recursive so that the size of all ancestors is taken into
2697b9c1b51eSKate Stone // account.
2698b9c1b51eSKate Stone size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
269980af0b9eSLuke Drummond   // Offsets to children plus zero terminator
270080af0b9eSLuke Drummond   size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
270180af0b9eSLuke Drummond   // Size of header struct with type details
270280af0b9eSLuke Drummond   size += sizeof(AllocationDetails::ElementHeader);
270326e52a70SEwan Crawford 
270426e52a70SEwan Crawford   // Calculate recursively for all descendants
270526e52a70SEwan Crawford   for (const Element &child : elem.children)
270626e52a70SEwan Crawford     size += CalculateElementHeaderSize(child);
270726e52a70SEwan Crawford 
270826e52a70SEwan Crawford   return size;
270926e52a70SEwan Crawford }
271026e52a70SEwan Crawford 
271105097246SAdrian Prantl // Function copies allocation contents into a binary file. This file can then
271205097246SAdrian Prantl // be loaded later into a different allocation. There is a header, FileHeader,
271380af0b9eSLuke Drummond // before the allocation data containing meta-data.
2714b9c1b51eSKate Stone bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
271580af0b9eSLuke Drummond                                          const char *path,
2716b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
271755232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
271855232f09SEwan Crawford 
271955232f09SEwan Crawford   // Find allocation with the given id
272055232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
272155232f09SEwan Crawford   if (!alloc)
272255232f09SEwan Crawford     return false;
272355232f09SEwan Crawford 
272455232f09SEwan Crawford   if (log)
2725b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2726b9c1b51eSKate Stone                 *alloc->address.get());
272755232f09SEwan Crawford 
272855232f09SEwan Crawford   // JIT all the allocation details
272980af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
273055232f09SEwan Crawford     if (log)
2731b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2732b9c1b51eSKate Stone                   __FUNCTION__);
273355232f09SEwan Crawford 
2734b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
273555232f09SEwan Crawford       if (log)
2736b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
27374cfc9198SSylvestre Ledru       return false;
273855232f09SEwan Crawford     }
273955232f09SEwan Crawford   }
274055232f09SEwan Crawford 
2741b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2742b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() &&
2743b9c1b51eSKate Stone          alloc->element.datum_size.get() &&
2744b9c1b51eSKate Stone          alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2745b3f7f69dSAidan Dodds          "Allocation information not available");
274655232f09SEwan Crawford 
274755232f09SEwan Crawford   // Check we can create writable file
27488f3be7a3SJonas Devlieghere   FileSpec file_spec(path);
27498f3be7a3SJonas Devlieghere   FileSystem::Instance().Resolve(file_spec);
275050bc1ed2SJonas Devlieghere   File file;
275150bc1ed2SJonas Devlieghere   FileSystem::Instance().Open(file, file_spec,
275250bc1ed2SJonas Devlieghere                               File::eOpenOptionWrite |
275350bc1ed2SJonas Devlieghere                                   File::eOpenOptionCanCreate |
2754b9c1b51eSKate Stone                                   File::eOpenOptionTruncate);
275550bc1ed2SJonas Devlieghere 
2756b9c1b51eSKate Stone   if (!file) {
275780af0b9eSLuke Drummond     strm.Printf("Error: Failed to open '%s' for writing", path);
275855232f09SEwan Crawford     strm.EOL();
275955232f09SEwan Crawford     return false;
276055232f09SEwan Crawford   }
276155232f09SEwan Crawford 
276255232f09SEwan Crawford   // Read allocation into buffer of heap memory
276355232f09SEwan Crawford   const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2764b9c1b51eSKate Stone   if (!buffer) {
276555232f09SEwan Crawford     strm.Printf("Error: Couldn't read allocation data into buffer");
276655232f09SEwan Crawford     strm.EOL();
276755232f09SEwan Crawford     return false;
276855232f09SEwan Crawford   }
276955232f09SEwan Crawford 
277055232f09SEwan Crawford   // Create the file header
277155232f09SEwan Crawford   AllocationDetails::FileHeader head;
2772b3f7f69dSAidan Dodds   memcpy(head.ident, "RSAD", 4);
27732d62328aSEwan Crawford   head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
27742d62328aSEwan Crawford   head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
27752d62328aSEwan Crawford   head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
277626e52a70SEwan Crawford 
277726e52a70SEwan Crawford   const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2778b9c1b51eSKate Stone   assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2779b9c1b51eSKate Stone              UINT16_MAX &&
2780b9c1b51eSKate Stone          "Element header too large");
2781b9c1b51eSKate Stone   head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2782b9c1b51eSKate Stone                                         element_header_size);
278355232f09SEwan Crawford 
278455232f09SEwan Crawford   // Write the file header
278555232f09SEwan Crawford   size_t num_bytes = sizeof(AllocationDetails::FileHeader);
278626e52a70SEwan Crawford   if (log)
2787b9c1b51eSKate Stone     log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2788b9c1b51eSKate Stone                 (uint64_t)num_bytes);
278926e52a70SEwan Crawford 
279097206d57SZachary Turner   Status err = file.Write(&head, num_bytes);
2791b9c1b51eSKate Stone   if (!err.Success()) {
279280af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
279326e52a70SEwan Crawford     strm.EOL();
279426e52a70SEwan Crawford     return false;
279526e52a70SEwan Crawford   }
279626e52a70SEwan Crawford 
279726e52a70SEwan Crawford   // Create the headers describing the element type of the allocation.
2798b9c1b51eSKate Stone   std::shared_ptr<uint8_t> element_header_buffer(
2799b9c1b51eSKate Stone       new uint8_t[element_header_size]);
2800b9c1b51eSKate Stone   if (element_header_buffer == nullptr) {
2801b9c1b51eSKate Stone     strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2802b9c1b51eSKate Stone                 " bytes on the heap",
2803b9c1b51eSKate Stone                 (uint64_t)element_header_size);
280426e52a70SEwan Crawford     strm.EOL();
280526e52a70SEwan Crawford     return false;
280626e52a70SEwan Crawford   }
280726e52a70SEwan Crawford 
280826e52a70SEwan Crawford   PopulateElementHeaders(element_header_buffer, 0, alloc->element);
280926e52a70SEwan Crawford 
281026e52a70SEwan Crawford   // Write headers for allocation element type to file
281126e52a70SEwan Crawford   num_bytes = element_header_size;
281226e52a70SEwan Crawford   if (log)
2813b9c1b51eSKate Stone     log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.",
2814b9c1b51eSKate Stone                 __FUNCTION__, (uint64_t)num_bytes);
281526e52a70SEwan Crawford 
281626e52a70SEwan Crawford   err = file.Write(element_header_buffer.get(), num_bytes);
2817b9c1b51eSKate Stone   if (!err.Success()) {
281880af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
281955232f09SEwan Crawford     strm.EOL();
282055232f09SEwan Crawford     return false;
282155232f09SEwan Crawford   }
282255232f09SEwan Crawford 
282355232f09SEwan Crawford   // Write allocation data to file
282455232f09SEwan Crawford   num_bytes = static_cast<size_t>(*alloc->size.get());
282555232f09SEwan Crawford   if (log)
2826b9c1b51eSKate Stone     log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2827b9c1b51eSKate Stone                 (uint64_t)num_bytes);
282855232f09SEwan Crawford 
282955232f09SEwan Crawford   err = file.Write(buffer.get(), num_bytes);
2830b9c1b51eSKate Stone   if (!err.Success()) {
283180af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
283255232f09SEwan Crawford     strm.EOL();
283355232f09SEwan Crawford     return false;
283455232f09SEwan Crawford   }
283555232f09SEwan Crawford 
283680af0b9eSLuke Drummond   strm.Printf("Allocation written to file '%s'", path);
283755232f09SEwan Crawford   strm.EOL();
283815f2bd95SEwan Crawford   return true;
283915f2bd95SEwan Crawford }
284015f2bd95SEwan Crawford 
2841b9c1b51eSKate Stone bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
28424640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
28434640cde1SColin Riley 
2844b9c1b51eSKate Stone   if (module_sp) {
2845b9c1b51eSKate Stone     for (const auto &rs_module : m_rsmodules) {
2846b9c1b51eSKate Stone       if (rs_module->m_module == module_sp) {
284705097246SAdrian Prantl         // Check if the user has enabled automatically breaking on all RS
284805097246SAdrian Prantl         // kernels.
28497dc7771cSEwan Crawford         if (m_breakAllKernels)
28507dc7771cSEwan Crawford           BreakOnModuleKernels(rs_module);
28517dc7771cSEwan Crawford 
28525ec532a9SColin Riley         return false;
28535ec532a9SColin Riley       }
28547dc7771cSEwan Crawford     }
2855ef20b08fSColin Riley     bool module_loaded = false;
2856b9c1b51eSKate Stone     switch (GetModuleKind(module_sp)) {
2857b9c1b51eSKate Stone     case eModuleKindKernelObj: {
28584640cde1SColin Riley       RSModuleDescriptorSP module_desc;
2859*796ac80bSJonas Devlieghere       module_desc = std::make_shared<RSModuleDescriptor>(module_sp);
2860b9c1b51eSKate Stone       if (module_desc->ParseRSInfo()) {
28615ec532a9SColin Riley         m_rsmodules.push_back(module_desc);
286247d64161SLuke Drummond         module_desc->WarnIfVersionMismatch(GetProcess()
286347d64161SLuke Drummond                                                ->GetTarget()
286447d64161SLuke Drummond                                                .GetDebugger()
286547d64161SLuke Drummond                                                .GetAsyncOutputStream()
286647d64161SLuke Drummond                                                .get());
2867ef20b08fSColin Riley         module_loaded = true;
28685ec532a9SColin Riley       }
2869b9c1b51eSKate Stone       if (module_loaded) {
28704640cde1SColin Riley         FixupScriptDetails(module_desc);
28714640cde1SColin Riley       }
2872ef20b08fSColin Riley       break;
2873ef20b08fSColin Riley     }
2874b9c1b51eSKate Stone     case eModuleKindDriver: {
2875b9c1b51eSKate Stone       if (!m_libRSDriver) {
28764640cde1SColin Riley         m_libRSDriver = module_sp;
28774640cde1SColin Riley         LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
28784640cde1SColin Riley       }
28794640cde1SColin Riley       break;
28804640cde1SColin Riley     }
2881b9c1b51eSKate Stone     case eModuleKindImpl: {
288221fed052SAidan Dodds       if (!m_libRSCpuRef) {
28834640cde1SColin Riley         m_libRSCpuRef = module_sp;
288421fed052SAidan Dodds         LoadRuntimeHooks(m_libRSCpuRef, RenderScriptRuntime::eModuleKindImpl);
288521fed052SAidan Dodds       }
28864640cde1SColin Riley       break;
28874640cde1SColin Riley     }
2888b9c1b51eSKate Stone     case eModuleKindLibRS: {
2889b9c1b51eSKate Stone       if (!m_libRS) {
28904640cde1SColin Riley         m_libRS = module_sp;
28914640cde1SColin Riley         static ConstString gDbgPresentStr("gDebuggerPresent");
2892b9c1b51eSKate Stone         const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2893b9c1b51eSKate Stone             gDbgPresentStr, eSymbolTypeData);
2894b9c1b51eSKate Stone         if (debug_present) {
289597206d57SZachary Turner           Status err;
28964640cde1SColin Riley           uint32_t flag = 0x00000001U;
28974640cde1SColin Riley           Target &target = GetProcess()->GetTarget();
2898358cf1eaSGreg Clayton           addr_t addr = debug_present->GetLoadAddress(&target);
289980af0b9eSLuke Drummond           GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
290080af0b9eSLuke Drummond           if (err.Success()) {
29014640cde1SColin Riley             if (log)
2902b9c1b51eSKate Stone               log->Printf("%s - debugger present flag set on debugee.",
2903b9c1b51eSKate Stone                           __FUNCTION__);
29044640cde1SColin Riley 
29054640cde1SColin Riley             m_debuggerPresentFlagged = true;
2906b9c1b51eSKate Stone           } else if (log) {
2907b9c1b51eSKate Stone             log->Printf("%s - error writing debugger present flags '%s' ",
290880af0b9eSLuke Drummond                         __FUNCTION__, err.AsCString());
29094640cde1SColin Riley           }
2910b9c1b51eSKate Stone         } else if (log) {
2911b9c1b51eSKate Stone           log->Printf(
2912b9c1b51eSKate Stone               "%s - error writing debugger present flags - symbol not found",
2913b9c1b51eSKate Stone               __FUNCTION__);
29144640cde1SColin Riley         }
29154640cde1SColin Riley       }
29164640cde1SColin Riley       break;
29174640cde1SColin Riley     }
2918ef20b08fSColin Riley     default:
2919ef20b08fSColin Riley       break;
2920ef20b08fSColin Riley     }
2921ef20b08fSColin Riley     if (module_loaded)
2922ef20b08fSColin Riley       Update();
2923ef20b08fSColin Riley     return module_loaded;
29245ec532a9SColin Riley   }
29255ec532a9SColin Riley   return false;
29265ec532a9SColin Riley }
29275ec532a9SColin Riley 
2928b9c1b51eSKate Stone void RenderScriptRuntime::Update() {
2929b9c1b51eSKate Stone   if (m_rsmodules.size() > 0) {
2930b9c1b51eSKate Stone     if (!m_initiated) {
2931ef20b08fSColin Riley       Initiate();
2932ef20b08fSColin Riley     }
2933ef20b08fSColin Riley   }
2934ef20b08fSColin Riley }
2935ef20b08fSColin Riley 
293647d64161SLuke Drummond void RSModuleDescriptor::WarnIfVersionMismatch(lldb_private::Stream *s) const {
293747d64161SLuke Drummond   if (!s)
293847d64161SLuke Drummond     return;
293947d64161SLuke Drummond 
294047d64161SLuke Drummond   if (m_slang_version.empty() || m_bcc_version.empty()) {
294147d64161SLuke Drummond     s->PutCString("WARNING: Unknown bcc or slang (llvm-rs-cc) version; debug "
294247d64161SLuke Drummond                   "experience may be unreliable");
294347d64161SLuke Drummond     s->EOL();
294447d64161SLuke Drummond   } else if (m_slang_version != m_bcc_version) {
294547d64161SLuke Drummond     s->Printf("WARNING: The debug info emitted by the slang frontend "
294647d64161SLuke Drummond               "(llvm-rs-cc) used to build this module (%s) does not match the "
294747d64161SLuke Drummond               "version of bcc used to generate the debug information (%s). "
294847d64161SLuke Drummond               "This is an unsupported configuration and may result in a poor "
294947d64161SLuke Drummond               "debugging experience; proceed with caution",
295047d64161SLuke Drummond               m_slang_version.c_str(), m_bcc_version.c_str());
295147d64161SLuke Drummond     s->EOL();
295247d64161SLuke Drummond   }
295347d64161SLuke Drummond }
295447d64161SLuke Drummond 
29557f193d69SLuke Drummond bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
29567f193d69SLuke Drummond                                           size_t n_lines) {
29577f193d69SLuke Drummond   // Skip the pragma prototype line
29587f193d69SLuke Drummond   ++lines;
29597f193d69SLuke Drummond   for (; n_lines--; ++lines) {
29607f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
29617f193d69SLuke Drummond     m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
29627f193d69SLuke Drummond   }
29637f193d69SLuke Drummond   return true;
29647f193d69SLuke Drummond }
29657f193d69SLuke Drummond 
29667f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
29677f193d69SLuke Drummond                                                 size_t n_lines) {
29687f193d69SLuke Drummond   // The list of reduction kernels in the `.rs.info` symbol is of the form
29697f193d69SLuke Drummond   // "signature - accumulatordatasize - reduction_name - initializer_name -
297005097246SAdrian Prantl   // accumulator_name - combiner_name - outconverter_name - halter_name" Where
297105097246SAdrian Prantl   // a function is not explicitly named by the user, or is not generated by the
297205097246SAdrian Prantl   // compiler, it is named "." so the dash separated list should always be 8
297305097246SAdrian Prantl   // items long
29747f193d69SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
29757f193d69SLuke Drummond   // Skip the exportReduceCount line
29767f193d69SLuke Drummond   ++lines;
29777f193d69SLuke Drummond   for (; n_lines--; ++lines) {
29787f193d69SLuke Drummond     llvm::SmallVector<llvm::StringRef, 8> spec;
29797f193d69SLuke Drummond     lines->split(spec, " - ");
29807f193d69SLuke Drummond     if (spec.size() != 8) {
29817f193d69SLuke Drummond       if (spec.size() < 8) {
29827f193d69SLuke Drummond         if (log)
29837f193d69SLuke Drummond           log->Error("Error parsing RenderScript reduction spec. wrong number "
29847f193d69SLuke Drummond                      "of fields");
29857f193d69SLuke Drummond         return false;
29867f193d69SLuke Drummond       } else if (log)
29877f193d69SLuke Drummond         log->Warning("Extraneous members in reduction spec: '%s'",
29887f193d69SLuke Drummond                      lines->str().c_str());
29897f193d69SLuke Drummond     }
29907f193d69SLuke Drummond 
29917f193d69SLuke Drummond     const auto sig_s = spec[0];
29927f193d69SLuke Drummond     uint32_t sig;
29937f193d69SLuke Drummond     if (sig_s.getAsInteger(10, sig)) {
29947f193d69SLuke Drummond       if (log)
29957f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid kernel "
29967f193d69SLuke Drummond                    "signature: '%s'",
29977f193d69SLuke Drummond                    sig_s.str().c_str());
29987f193d69SLuke Drummond       return false;
29997f193d69SLuke Drummond     }
30007f193d69SLuke Drummond 
30017f193d69SLuke Drummond     const auto accum_data_size_s = spec[1];
30027f193d69SLuke Drummond     uint32_t accum_data_size;
30037f193d69SLuke Drummond     if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
30047f193d69SLuke Drummond       if (log)
30057f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid "
30067f193d69SLuke Drummond                    "accumulator data size %s",
30077f193d69SLuke Drummond                    accum_data_size_s.str().c_str());
30087f193d69SLuke Drummond       return false;
30097f193d69SLuke Drummond     }
30107f193d69SLuke Drummond 
30117f193d69SLuke Drummond     if (log)
30127f193d69SLuke Drummond       log->Printf("Found RenderScript reduction '%s'", spec[2].str().c_str());
30137f193d69SLuke Drummond 
30147f193d69SLuke Drummond     m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
30157f193d69SLuke Drummond                                                  spec[2], spec[3], spec[4],
30167f193d69SLuke Drummond                                                  spec[5], spec[6], spec[7]));
30177f193d69SLuke Drummond   }
30187f193d69SLuke Drummond   return true;
30197f193d69SLuke Drummond }
30207f193d69SLuke Drummond 
302147d64161SLuke Drummond bool RSModuleDescriptor::ParseVersionInfo(llvm::StringRef *lines,
302247d64161SLuke Drummond                                           size_t n_lines) {
302347d64161SLuke Drummond   // Skip the versionInfo line
302447d64161SLuke Drummond   ++lines;
302547d64161SLuke Drummond   for (; n_lines--; ++lines) {
302647d64161SLuke Drummond     // We're only interested in bcc and slang versions, and ignore all other
302747d64161SLuke Drummond     // versionInfo lines
302847d64161SLuke Drummond     const auto kv_pair = lines->split(" - ");
302947d64161SLuke Drummond     if (kv_pair.first == "slang")
303047d64161SLuke Drummond       m_slang_version = kv_pair.second.str();
303147d64161SLuke Drummond     else if (kv_pair.first == "bcc")
303247d64161SLuke Drummond       m_bcc_version = kv_pair.second.str();
303347d64161SLuke Drummond   }
303447d64161SLuke Drummond   return true;
303547d64161SLuke Drummond }
303647d64161SLuke Drummond 
30377f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
30387f193d69SLuke Drummond                                                  size_t n_lines) {
30397f193d69SLuke Drummond   // Skip the exportForeachCount line
30407f193d69SLuke Drummond   ++lines;
30417f193d69SLuke Drummond   for (; n_lines--; ++lines) {
30427f193d69SLuke Drummond     uint32_t slot;
30437f193d69SLuke Drummond     // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
30447f193d69SLuke Drummond     // pair per line
30457f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
30467f193d69SLuke Drummond     if (kv_pair.first.getAsInteger(10, slot))
30477f193d69SLuke Drummond       return false;
30487f193d69SLuke Drummond     m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
30497f193d69SLuke Drummond   }
30507f193d69SLuke Drummond   return true;
30517f193d69SLuke Drummond }
30527f193d69SLuke Drummond 
30537f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
30547f193d69SLuke Drummond                                              size_t n_lines) {
30557f193d69SLuke Drummond   // Skip the ExportVarCount line
30567f193d69SLuke Drummond   ++lines;
30577f193d69SLuke Drummond   for (; n_lines--; ++lines)
30587f193d69SLuke Drummond     m_globals.push_back(RSGlobalDescriptor(this, *lines));
30597f193d69SLuke Drummond   return true;
30607f193d69SLuke Drummond }
30615ec532a9SColin Riley 
3062b9c1b51eSKate Stone // The .rs.info symbol in renderscript modules contains a string which needs to
306305097246SAdrian Prantl // be parsed. The string is basic and is parsed on a line by line basis.
3064b9c1b51eSKate Stone bool RSModuleDescriptor::ParseRSInfo() {
3065b0be30f7SAidan Dodds   assert(m_module);
30667f193d69SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3067b9c1b51eSKate Stone   const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
3068b9c1b51eSKate Stone       ConstString(".rs.info"), eSymbolTypeData);
3069b0be30f7SAidan Dodds   if (!info_sym)
3070b0be30f7SAidan Dodds     return false;
3071b0be30f7SAidan Dodds 
3072358cf1eaSGreg Clayton   const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
3073b0be30f7SAidan Dodds   if (addr == LLDB_INVALID_ADDRESS)
3074b0be30f7SAidan Dodds     return false;
3075b0be30f7SAidan Dodds 
30765ec532a9SColin Riley   const addr_t size = info_sym->GetByteSize();
30775ec532a9SColin Riley   const FileSpec fs = m_module->GetFileSpec();
30785ec532a9SColin Riley 
307987e403aaSJonas Devlieghere   auto buffer =
308087e403aaSJonas Devlieghere       FileSystem::Instance().CreateDataBuffer(fs.GetPath(), size, addr);
30815ec532a9SColin Riley   if (!buffer)
30825ec532a9SColin Riley     return false;
30835ec532a9SColin Riley 
3084b0be30f7SAidan Dodds   // split rs.info. contents into lines
30857f193d69SLuke Drummond   llvm::SmallVector<llvm::StringRef, 128> info_lines;
30865ec532a9SColin Riley   {
30877f193d69SLuke Drummond     const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
30887f193d69SLuke Drummond     raw_rs_info.split(info_lines, '\n');
30897f193d69SLuke Drummond     if (log)
30907f193d69SLuke Drummond       log->Printf("'.rs.info symbol for '%s':\n%s",
30917f193d69SLuke Drummond                   m_module->GetFileSpec().GetCString(),
30927f193d69SLuke Drummond                   raw_rs_info.str().c_str());
3093b0be30f7SAidan Dodds   }
3094b0be30f7SAidan Dodds 
30957f193d69SLuke Drummond   enum {
30967f193d69SLuke Drummond     eExportVar,
30977f193d69SLuke Drummond     eExportForEach,
30987f193d69SLuke Drummond     eExportReduce,
30997f193d69SLuke Drummond     ePragma,
31007f193d69SLuke Drummond     eBuildChecksum,
310147d64161SLuke Drummond     eObjectSlot,
310247d64161SLuke Drummond     eVersionInfo,
31037f193d69SLuke Drummond   };
31047f193d69SLuke Drummond 
3105b3bbcb12SLuke Drummond   const auto rs_info_handler = [](llvm::StringRef name) -> int {
3106b3bbcb12SLuke Drummond     return llvm::StringSwitch<int>(name)
3107b3bbcb12SLuke Drummond         // The number of visible global variables in the script
3108b3bbcb12SLuke Drummond         .Case("exportVarCount", eExportVar)
31097f193d69SLuke Drummond         // The number of RenderScrip `forEach` kernels __attribute__((kernel))
3110b3bbcb12SLuke Drummond         .Case("exportForEachCount", eExportForEach)
3111b3bbcb12SLuke Drummond         // The number of generalreductions: This marked in the script by
3112b3bbcb12SLuke Drummond         // `#pragma reduce()`
3113b3bbcb12SLuke Drummond         .Case("exportReduceCount", eExportReduce)
3114b3bbcb12SLuke Drummond         // Total count of all RenderScript specific `#pragmas` used in the
3115b3bbcb12SLuke Drummond         // script
3116b3bbcb12SLuke Drummond         .Case("pragmaCount", ePragma)
3117b3bbcb12SLuke Drummond         .Case("objectSlotCount", eObjectSlot)
311847d64161SLuke Drummond         .Case("versionInfo", eVersionInfo)
3119b3bbcb12SLuke Drummond         .Default(-1);
3120b3bbcb12SLuke Drummond   };
3121b0be30f7SAidan Dodds 
3122b0be30f7SAidan Dodds   // parse all text lines of .rs.info
3123b9c1b51eSKate Stone   for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
31247f193d69SLuke Drummond     const auto kv_pair = line->split(": ");
31257f193d69SLuke Drummond     const auto key = kv_pair.first;
31267f193d69SLuke Drummond     const auto val = kv_pair.second.trim();
31275ec532a9SColin Riley 
3128b3bbcb12SLuke Drummond     const auto handler = rs_info_handler(key);
3129b3bbcb12SLuke Drummond     if (handler == -1)
31307f193d69SLuke Drummond       continue;
313105097246SAdrian Prantl     // getAsInteger returns `true` on an error condition - we're only
313205097246SAdrian Prantl     // interested in numeric fields at the moment
31337f193d69SLuke Drummond     uint64_t n_lines;
31347f193d69SLuke Drummond     if (val.getAsInteger(10, n_lines)) {
31356302bf6aSPavel Labath       LLDB_LOGV(log, "Failed to parse non-numeric '.rs.info' section {0}",
31366302bf6aSPavel Labath                 line->str());
31377f193d69SLuke Drummond       continue;
31387f193d69SLuke Drummond     }
31397f193d69SLuke Drummond     if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
31407f193d69SLuke Drummond       return false;
31417f193d69SLuke Drummond 
31427f193d69SLuke Drummond     bool success = false;
3143b3bbcb12SLuke Drummond     switch (handler) {
31447f193d69SLuke Drummond     case eExportVar:
31457f193d69SLuke Drummond       success = ParseExportVarCount(line, n_lines);
31467f193d69SLuke Drummond       break;
31477f193d69SLuke Drummond     case eExportForEach:
31487f193d69SLuke Drummond       success = ParseExportForeachCount(line, n_lines);
31497f193d69SLuke Drummond       break;
31507f193d69SLuke Drummond     case eExportReduce:
31517f193d69SLuke Drummond       success = ParseExportReduceCount(line, n_lines);
31527f193d69SLuke Drummond       break;
31537f193d69SLuke Drummond     case ePragma:
31547f193d69SLuke Drummond       success = ParsePragmaCount(line, n_lines);
31557f193d69SLuke Drummond       break;
315647d64161SLuke Drummond     case eVersionInfo:
315747d64161SLuke Drummond       success = ParseVersionInfo(line, n_lines);
315847d64161SLuke Drummond       break;
31597f193d69SLuke Drummond     default: {
31607f193d69SLuke Drummond       if (log)
31617f193d69SLuke Drummond         log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__,
31627f193d69SLuke Drummond                     line->str().c_str());
31637f193d69SLuke Drummond       continue;
31647f193d69SLuke Drummond     }
31657f193d69SLuke Drummond     }
31667f193d69SLuke Drummond     if (!success)
31677f193d69SLuke Drummond       return false;
31687f193d69SLuke Drummond     line += n_lines;
31697f193d69SLuke Drummond   }
31707f193d69SLuke Drummond   return info_lines.size() > 0;
31715ec532a9SColin Riley }
31725ec532a9SColin Riley 
317397206d57SZachary Turner void RenderScriptRuntime::DumpStatus(Stream &strm) const {
3174b9c1b51eSKate Stone   if (m_libRS) {
31754640cde1SColin Riley     strm.Printf("Runtime Library discovered.");
31764640cde1SColin Riley     strm.EOL();
31774640cde1SColin Riley   }
3178b9c1b51eSKate Stone   if (m_libRSDriver) {
31794640cde1SColin Riley     strm.Printf("Runtime Driver discovered.");
31804640cde1SColin Riley     strm.EOL();
31814640cde1SColin Riley   }
3182b9c1b51eSKate Stone   if (m_libRSCpuRef) {
31834640cde1SColin Riley     strm.Printf("CPU Reference Implementation discovered.");
31844640cde1SColin Riley     strm.EOL();
31854640cde1SColin Riley   }
31864640cde1SColin Riley 
3187b9c1b51eSKate Stone   if (m_runtimeHooks.size()) {
31884640cde1SColin Riley     strm.Printf("Runtime functions hooked:");
31894640cde1SColin Riley     strm.EOL();
3190b9c1b51eSKate Stone     for (auto b : m_runtimeHooks) {
31914640cde1SColin Riley       strm.Indent(b.second->defn->name);
31924640cde1SColin Riley       strm.EOL();
31934640cde1SColin Riley     }
3194b9c1b51eSKate Stone   } else {
31954640cde1SColin Riley     strm.Printf("Runtime is not hooked.");
31964640cde1SColin Riley     strm.EOL();
31974640cde1SColin Riley   }
31984640cde1SColin Riley }
31994640cde1SColin Riley 
3200b9c1b51eSKate Stone void RenderScriptRuntime::DumpContexts(Stream &strm) const {
32014640cde1SColin Riley   strm.Printf("Inferred RenderScript Contexts:");
32024640cde1SColin Riley   strm.EOL();
32034640cde1SColin Riley   strm.IndentMore();
32044640cde1SColin Riley 
32054640cde1SColin Riley   std::map<addr_t, uint64_t> contextReferences;
32064640cde1SColin Riley 
320705097246SAdrian Prantl   // Iterate over all of the currently discovered scripts. Note: We cant push
320805097246SAdrian Prantl   // or pop from m_scripts inside this loop or it may invalidate script.
3209b9c1b51eSKate Stone   for (const auto &script : m_scripts) {
321078f339d1SEwan Crawford     if (!script->context.isValid())
321178f339d1SEwan Crawford       continue;
321278f339d1SEwan Crawford     lldb::addr_t context = *script->context;
321378f339d1SEwan Crawford 
3214b9c1b51eSKate Stone     if (contextReferences.find(context) != contextReferences.end()) {
321578f339d1SEwan Crawford       contextReferences[context]++;
3216b9c1b51eSKate Stone     } else {
321778f339d1SEwan Crawford       contextReferences[context] = 1;
32184640cde1SColin Riley     }
32194640cde1SColin Riley   }
32204640cde1SColin Riley 
3221b9c1b51eSKate Stone   for (const auto &cRef : contextReferences) {
3222b9c1b51eSKate Stone     strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
3223b9c1b51eSKate Stone                 cRef.first, cRef.second);
32244640cde1SColin Riley     strm.EOL();
32254640cde1SColin Riley   }
32264640cde1SColin Riley   strm.IndentLess();
32274640cde1SColin Riley }
32284640cde1SColin Riley 
3229b9c1b51eSKate Stone void RenderScriptRuntime::DumpKernels(Stream &strm) const {
32304640cde1SColin Riley   strm.Printf("RenderScript Kernels:");
32314640cde1SColin Riley   strm.EOL();
32324640cde1SColin Riley   strm.IndentMore();
3233b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
32344640cde1SColin Riley     strm.Printf("Resource '%s':", module->m_resname.c_str());
32354640cde1SColin Riley     strm.EOL();
3236b9c1b51eSKate Stone     for (const auto &kernel : module->m_kernels) {
32374640cde1SColin Riley       strm.Indent(kernel.m_name.AsCString());
32384640cde1SColin Riley       strm.EOL();
32394640cde1SColin Riley     }
32404640cde1SColin Riley   }
32414640cde1SColin Riley   strm.IndentLess();
32424640cde1SColin Riley }
32434640cde1SColin Riley 
3244a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails *
3245b9c1b51eSKate Stone RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
3246a0f08674SEwan Crawford   AllocationDetails *alloc = nullptr;
3247a0f08674SEwan Crawford 
3248a0f08674SEwan Crawford   // See if we can find allocation using id as an index;
3249b9c1b51eSKate Stone   if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
3250b9c1b51eSKate Stone       m_allocations[alloc_id - 1]->id == alloc_id) {
3251a0f08674SEwan Crawford     alloc = m_allocations[alloc_id - 1].get();
3252a0f08674SEwan Crawford     return alloc;
3253a0f08674SEwan Crawford   }
3254a0f08674SEwan Crawford 
3255a0f08674SEwan Crawford   // Fallback to searching
3256b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
3257b9c1b51eSKate Stone     if (a->id == alloc_id) {
3258a0f08674SEwan Crawford       alloc = a.get();
3259a0f08674SEwan Crawford       break;
3260a0f08674SEwan Crawford     }
3261a0f08674SEwan Crawford   }
3262a0f08674SEwan Crawford 
3263b9c1b51eSKate Stone   if (alloc == nullptr) {
3264b9c1b51eSKate Stone     strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
3265b9c1b51eSKate Stone                 alloc_id);
3266a0f08674SEwan Crawford     strm.EOL();
3267a0f08674SEwan Crawford   }
3268a0f08674SEwan Crawford 
3269a0f08674SEwan Crawford   return alloc;
3270a0f08674SEwan Crawford }
3271a0f08674SEwan Crawford 
3272b9c1b51eSKate Stone // Prints the contents of an allocation to the output stream, which may be a
3273b9c1b51eSKate Stone // file
3274b9c1b51eSKate Stone bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
3275b9c1b51eSKate Stone                                          const uint32_t id) {
3276a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3277a0f08674SEwan Crawford 
3278a0f08674SEwan Crawford   // Check we can find the desired allocation
3279a0f08674SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, id);
3280a0f08674SEwan Crawford   if (!alloc)
3281a0f08674SEwan Crawford     return false; // FindAllocByID() will print error message for us here
3282a0f08674SEwan Crawford 
3283a0f08674SEwan Crawford   if (log)
3284b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
3285b9c1b51eSKate Stone                 *alloc->address.get());
3286a0f08674SEwan Crawford 
3287a0f08674SEwan Crawford   // Check we have information about the allocation, if not calculate it
328880af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
3289a0f08674SEwan Crawford     if (log)
3290b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
3291b9c1b51eSKate Stone                   __FUNCTION__);
3292a0f08674SEwan Crawford 
3293a0f08674SEwan Crawford     // JIT all the allocation information
3294b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
3295a0f08674SEwan Crawford       strm.Printf("Error: Couldn't JIT allocation details");
3296a0f08674SEwan Crawford       strm.EOL();
3297a0f08674SEwan Crawford       return false;
3298a0f08674SEwan Crawford     }
3299a0f08674SEwan Crawford   }
3300a0f08674SEwan Crawford 
3301a0f08674SEwan Crawford   // Establish format and size of each data element
3302b3f7f69dSAidan Dodds   const uint32_t vec_size = *alloc->element.type_vec_size.get();
33038b244e21SEwan Crawford   const Element::DataType type = *alloc->element.type.get();
3304a0f08674SEwan Crawford 
3305b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
3306b9c1b51eSKate Stone          "Invalid allocation type");
3307a0f08674SEwan Crawford 
33082e920715SEwan Crawford   lldb::Format format;
33092e920715SEwan Crawford   if (type >= Element::RS_TYPE_ELEMENT)
33102e920715SEwan Crawford     format = eFormatHex;
33112e920715SEwan Crawford   else
3312b9c1b51eSKate Stone     format = vec_size == 1
3313b9c1b51eSKate Stone                  ? static_cast<lldb::Format>(
3314b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatSingle])
3315b9c1b51eSKate Stone                  : static_cast<lldb::Format>(
3316b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatVector]);
3317a0f08674SEwan Crawford 
3318b3f7f69dSAidan Dodds   const uint32_t data_size = *alloc->element.datum_size.get();
3319a0f08674SEwan Crawford 
3320a0f08674SEwan Crawford   if (log)
3321b9c1b51eSKate Stone     log->Printf("%s - element size %" PRIu32 " bytes, including padding",
3322b9c1b51eSKate Stone                 __FUNCTION__, data_size);
3323a0f08674SEwan Crawford 
332455232f09SEwan Crawford   // Allocate a buffer to copy data into
332555232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3326b9c1b51eSKate Stone   if (!buffer) {
33272e920715SEwan Crawford     strm.Printf("Error: Couldn't read allocation data");
332855232f09SEwan Crawford     strm.EOL();
332955232f09SEwan Crawford     return false;
333055232f09SEwan Crawford   }
333155232f09SEwan Crawford 
3332a0f08674SEwan Crawford   // Calculate stride between rows as there may be padding at end of rows since
3333a0f08674SEwan Crawford   // allocated memory is 16-byte aligned
3334b9c1b51eSKate Stone   if (!alloc->stride.isValid()) {
3335a0f08674SEwan Crawford     if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
3336a0f08674SEwan Crawford       alloc->stride = 0;
3337b9c1b51eSKate Stone     else if (!JITAllocationStride(alloc, frame_ptr)) {
3338a0f08674SEwan Crawford       strm.Printf("Error: Couldn't calculate allocation row stride");
3339a0f08674SEwan Crawford       strm.EOL();
3340a0f08674SEwan Crawford       return false;
3341a0f08674SEwan Crawford     }
3342a0f08674SEwan Crawford   }
3343b3f7f69dSAidan Dodds   const uint32_t stride = *alloc->stride.get();
3344b3f7f69dSAidan Dodds   const uint32_t size = *alloc->size.get(); // Size of whole allocation
3345b9c1b51eSKate Stone   const uint32_t padding =
3346b9c1b51eSKate Stone       alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3347a0f08674SEwan Crawford   if (log)
3348b9c1b51eSKate Stone     log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32
3349b9c1b51eSKate Stone                 " bytes, padding %" PRIu32,
3350b3f7f69dSAidan Dodds                 __FUNCTION__, stride, size, padding);
3351a0f08674SEwan Crawford 
3352a0f08674SEwan Crawford   // Find dimensions used to index loops, so need to be non-zero
3353b3f7f69dSAidan Dodds   uint32_t dim_x = alloc->dimension.get()->dim_1;
3354a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 1 : dim_x;
3355a0f08674SEwan Crawford 
3356b3f7f69dSAidan Dodds   uint32_t dim_y = alloc->dimension.get()->dim_2;
3357a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 1 : dim_y;
3358a0f08674SEwan Crawford 
3359b3f7f69dSAidan Dodds   uint32_t dim_z = alloc->dimension.get()->dim_3;
3360a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 1 : dim_z;
3361a0f08674SEwan Crawford 
336255232f09SEwan Crawford   // Use data extractor to format output
336380af0b9eSLuke Drummond   const uint32_t target_ptr_size =
3364b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3365b9c1b51eSKate Stone   DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
336680af0b9eSLuke Drummond                            target_ptr_size);
336755232f09SEwan Crawford 
3368b3f7f69dSAidan Dodds   uint32_t offset = 0;   // Offset in buffer to next element to be printed
3369b3f7f69dSAidan Dodds   uint32_t prev_row = 0; // Offset to the start of the previous row
3370a0f08674SEwan Crawford 
3371a0f08674SEwan Crawford   // Iterate over allocation dimensions, printing results to user
3372a0f08674SEwan Crawford   strm.Printf("Data (X, Y, Z):");
3373b9c1b51eSKate Stone   for (uint32_t z = 0; z < dim_z; ++z) {
3374b9c1b51eSKate Stone     for (uint32_t y = 0; y < dim_y; ++y) {
3375a0f08674SEwan Crawford       // Use stride to index start of next row.
3376a0f08674SEwan Crawford       if (!(y == 0 && z == 0))
3377a0f08674SEwan Crawford         offset = prev_row + stride;
3378a0f08674SEwan Crawford       prev_row = offset;
3379a0f08674SEwan Crawford 
3380a0f08674SEwan Crawford       // Print each element in the row individually
3381b9c1b51eSKate Stone       for (uint32_t x = 0; x < dim_x; ++x) {
3382b3f7f69dSAidan Dodds         strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3383b9c1b51eSKate Stone         if ((type == Element::RS_TYPE_NONE) &&
3384b9c1b51eSKate Stone             (alloc->element.children.size() > 0) &&
3385b9c1b51eSKate Stone             (alloc->element.type_name != Element::GetFallbackStructName())) {
338605097246SAdrian Prantl           // Here we are dumping an Element of struct type. This is done using
338705097246SAdrian Prantl           // expression evaluation with the name of the struct type and pointer
338805097246SAdrian Prantl           // to element. Don't print the name of the resulting expression,
338905097246SAdrian Prantl           // since this will be '$[0-9]+'
33908b244e21SEwan Crawford           DumpValueObjectOptions expr_options;
33918b244e21SEwan Crawford           expr_options.SetHideName(true);
33928b244e21SEwan Crawford 
33934ebdee0aSBruce Mitchener           // Setup expression as dereferencing a pointer cast to element
339405097246SAdrian Prantl           // address.
3395ea0636b5SEwan Crawford           char expr_char_buffer[jit_max_expr_size];
339680af0b9eSLuke Drummond           int written =
3397b9c1b51eSKate Stone               snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3398b9c1b51eSKate Stone                        alloc->element.type_name.AsCString(),
3399b9c1b51eSKate Stone                        *alloc->data_ptr.get() + offset);
34008b244e21SEwan Crawford 
340180af0b9eSLuke Drummond           if (written < 0 || written >= jit_max_expr_size) {
34028b244e21SEwan Crawford             if (log)
3403b3f7f69dSAidan Dodds               log->Printf("%s - error in snprintf().", __FUNCTION__);
34048b244e21SEwan Crawford             continue;
34058b244e21SEwan Crawford           }
34068b244e21SEwan Crawford 
34078b244e21SEwan Crawford           // Evaluate expression
34088b244e21SEwan Crawford           ValueObjectSP expr_result;
3409b9c1b51eSKate Stone           GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3410b9c1b51eSKate Stone                                                        frame_ptr, expr_result);
34118b244e21SEwan Crawford 
34128b244e21SEwan Crawford           // Print the results to our stream.
34138b244e21SEwan Crawford           expr_result->Dump(strm, expr_options);
3414b9c1b51eSKate Stone         } else {
341529cb868aSZachary Turner           DumpDataExtractor(alloc_data, &strm, offset, format,
341629cb868aSZachary Turner                             data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0,
341729cb868aSZachary Turner                             0);
34188b244e21SEwan Crawford         }
34198b244e21SEwan Crawford         offset += data_size;
3420a0f08674SEwan Crawford       }
3421a0f08674SEwan Crawford     }
3422a0f08674SEwan Crawford   }
3423a0f08674SEwan Crawford   strm.EOL();
3424a0f08674SEwan Crawford 
3425a0f08674SEwan Crawford   return true;
3426a0f08674SEwan Crawford }
3427a0f08674SEwan Crawford 
342805097246SAdrian Prantl // Function recalculates all our cached information about allocations by
342905097246SAdrian Prantl // jitting the RS runtime regarding each allocation we know about. Returns true
343005097246SAdrian Prantl // if all allocations could be recomputed, false otherwise.
3431b9c1b51eSKate Stone bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3432b9c1b51eSKate Stone                                                   StackFrame *frame_ptr) {
34330d2bfcfbSEwan Crawford   bool success = true;
3434b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
34350d2bfcfbSEwan Crawford     // JIT current allocation information
3436b9c1b51eSKate Stone     if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3437b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3438b9c1b51eSKate Stone                   "\n",
3439b9c1b51eSKate Stone                   alloc->id);
34400d2bfcfbSEwan Crawford       success = false;
34410d2bfcfbSEwan Crawford     }
34420d2bfcfbSEwan Crawford   }
34430d2bfcfbSEwan Crawford 
34440d2bfcfbSEwan Crawford   if (success)
34450d2bfcfbSEwan Crawford     strm.Printf("All allocations successfully recomputed");
34460d2bfcfbSEwan Crawford   strm.EOL();
34470d2bfcfbSEwan Crawford 
34480d2bfcfbSEwan Crawford   return success;
34490d2bfcfbSEwan Crawford }
34500d2bfcfbSEwan Crawford 
345180af0b9eSLuke Drummond // Prints information regarding currently loaded allocations. These details are
345280af0b9eSLuke Drummond // gathered by jitting the runtime, which has as latency. Index parameter
345380af0b9eSLuke Drummond // specifies a single allocation ID to print, or a zero value to print them all
3454b9c1b51eSKate Stone void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3455b9c1b51eSKate Stone                                           const uint32_t index) {
345615f2bd95SEwan Crawford   strm.Printf("RenderScript Allocations:");
345715f2bd95SEwan Crawford   strm.EOL();
345815f2bd95SEwan Crawford   strm.IndentMore();
345915f2bd95SEwan Crawford 
3460b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
3461b649b005SEwan Crawford     // index will only be zero if we want to print all allocations
3462b649b005SEwan Crawford     if (index != 0 && index != alloc->id)
3463b649b005SEwan Crawford       continue;
346415f2bd95SEwan Crawford 
346515f2bd95SEwan Crawford     // JIT current allocation information
346680af0b9eSLuke Drummond     if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3467b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3468b9c1b51eSKate Stone                   alloc->id);
3469b3f7f69dSAidan Dodds       strm.EOL();
347015f2bd95SEwan Crawford       continue;
347115f2bd95SEwan Crawford     }
347215f2bd95SEwan Crawford 
3473b3f7f69dSAidan Dodds     strm.Printf("%" PRIu32 ":", alloc->id);
3474b3f7f69dSAidan Dodds     strm.EOL();
347515f2bd95SEwan Crawford     strm.IndentMore();
347615f2bd95SEwan Crawford 
347715f2bd95SEwan Crawford     strm.Indent("Context: ");
347815f2bd95SEwan Crawford     if (!alloc->context.isValid())
347915f2bd95SEwan Crawford       strm.Printf("unknown\n");
348015f2bd95SEwan Crawford     else
348115f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
348215f2bd95SEwan Crawford 
348315f2bd95SEwan Crawford     strm.Indent("Address: ");
348415f2bd95SEwan Crawford     if (!alloc->address.isValid())
348515f2bd95SEwan Crawford       strm.Printf("unknown\n");
348615f2bd95SEwan Crawford     else
348715f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
348815f2bd95SEwan Crawford 
348915f2bd95SEwan Crawford     strm.Indent("Data pointer: ");
349015f2bd95SEwan Crawford     if (!alloc->data_ptr.isValid())
349115f2bd95SEwan Crawford       strm.Printf("unknown\n");
349215f2bd95SEwan Crawford     else
349315f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
349415f2bd95SEwan Crawford 
349515f2bd95SEwan Crawford     strm.Indent("Dimensions: ");
349615f2bd95SEwan Crawford     if (!alloc->dimension.isValid())
349715f2bd95SEwan Crawford       strm.Printf("unknown\n");
349815f2bd95SEwan Crawford     else
3499b3f7f69dSAidan Dodds       strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3500b9c1b51eSKate Stone                   alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3501b9c1b51eSKate Stone                   alloc->dimension.get()->dim_3);
350215f2bd95SEwan Crawford 
350315f2bd95SEwan Crawford     strm.Indent("Data Type: ");
3504b9c1b51eSKate Stone     if (!alloc->element.type.isValid() ||
3505b9c1b51eSKate Stone         !alloc->element.type_vec_size.isValid())
350615f2bd95SEwan Crawford       strm.Printf("unknown\n");
3507b9c1b51eSKate Stone     else {
35088b244e21SEwan Crawford       const int vector_size = *alloc->element.type_vec_size.get();
35092e920715SEwan Crawford       Element::DataType type = *alloc->element.type.get();
351015f2bd95SEwan Crawford 
35118b244e21SEwan Crawford       if (!alloc->element.type_name.IsEmpty())
35128b244e21SEwan Crawford         strm.Printf("%s\n", alloc->element.type_name.AsCString());
3513b9c1b51eSKate Stone       else {
3514b9c1b51eSKate Stone         // Enum value isn't monotonous, so doesn't always index
3515b9c1b51eSKate Stone         // RsDataTypeToString array
35162e920715SEwan Crawford         if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3517b9c1b51eSKate Stone           type =
3518b9c1b51eSKate Stone               static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3519b3f7f69dSAidan Dodds                                              Element::RS_TYPE_MATRIX_2X2 + 1);
35202e920715SEwan Crawford 
3521b3f7f69dSAidan Dodds         if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3522b3f7f69dSAidan Dodds                      sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3523b3f7f69dSAidan Dodds             vector_size > 4 || vector_size < 1)
352415f2bd95SEwan Crawford           strm.Printf("invalid type\n");
352515f2bd95SEwan Crawford         else
3526b9c1b51eSKate Stone           strm.Printf(
3527b9c1b51eSKate Stone               "%s\n",
3528b9c1b51eSKate Stone               AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3529b3f7f69dSAidan Dodds                                                    [vector_size - 1]);
353015f2bd95SEwan Crawford       }
35312e920715SEwan Crawford     }
353215f2bd95SEwan Crawford 
353315f2bd95SEwan Crawford     strm.Indent("Data Kind: ");
35348b244e21SEwan Crawford     if (!alloc->element.type_kind.isValid())
353515f2bd95SEwan Crawford       strm.Printf("unknown\n");
3536b9c1b51eSKate Stone     else {
35378b244e21SEwan Crawford       const Element::DataKind kind = *alloc->element.type_kind.get();
35388b244e21SEwan Crawford       if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
353915f2bd95SEwan Crawford         strm.Printf("invalid kind\n");
354015f2bd95SEwan Crawford       else
3541b9c1b51eSKate Stone         strm.Printf(
3542b9c1b51eSKate Stone             "%s\n",
3543b9c1b51eSKate Stone             AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
354415f2bd95SEwan Crawford     }
354515f2bd95SEwan Crawford 
354615f2bd95SEwan Crawford     strm.EOL();
354715f2bd95SEwan Crawford     strm.IndentLess();
354815f2bd95SEwan Crawford   }
354915f2bd95SEwan Crawford   strm.IndentLess();
355015f2bd95SEwan Crawford }
355115f2bd95SEwan Crawford 
35527dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
3553b9c1b51eSKate Stone void RenderScriptRuntime::BreakOnModuleKernels(
3554b9c1b51eSKate Stone     const RSModuleDescriptorSP rsmodule_sp) {
3555b9c1b51eSKate Stone   for (const auto &kernel : rsmodule_sp->m_kernels) {
35567dc7771cSEwan Crawford     // Don't set breakpoint on 'root' kernel
35577dc7771cSEwan Crawford     if (strcmp(kernel.m_name.AsCString(), "root") == 0)
35587dc7771cSEwan Crawford       continue;
35597dc7771cSEwan Crawford 
35607dc7771cSEwan Crawford     CreateKernelBreakpoint(kernel.m_name);
35617dc7771cSEwan Crawford   }
35627dc7771cSEwan Crawford }
35637dc7771cSEwan Crawford 
356480af0b9eSLuke Drummond // Method is internally called by the 'kernel breakpoint all' command to enable
356580af0b9eSLuke Drummond // or disable breaking on all kernels. When do_break is true we want to enable
356680af0b9eSLuke Drummond // this functionality. When do_break is false we want to disable it.
3567b9c1b51eSKate Stone void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3568b9c1b51eSKate Stone   Log *log(
3569b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
35707dc7771cSEwan Crawford 
35717dc7771cSEwan Crawford   InitSearchFilter(target);
35727dc7771cSEwan Crawford 
35737dc7771cSEwan Crawford   // Set breakpoints on all the kernels
3574b9c1b51eSKate Stone   if (do_break && !m_breakAllKernels) {
35757dc7771cSEwan Crawford     m_breakAllKernels = true;
35767dc7771cSEwan Crawford 
35777dc7771cSEwan Crawford     for (const auto &module : m_rsmodules)
35787dc7771cSEwan Crawford       BreakOnModuleKernels(module);
35797dc7771cSEwan Crawford 
35807dc7771cSEwan Crawford     if (log)
3581b9c1b51eSKate Stone       log->Printf("%s(True) - breakpoints set on all currently loaded kernels.",
3582b9c1b51eSKate Stone                   __FUNCTION__);
3583b9c1b51eSKate Stone   } else if (!do_break &&
3584b9c1b51eSKate Stone              m_breakAllKernels) // Breakpoints won't be set on any new kernels.
35857dc7771cSEwan Crawford   {
35867dc7771cSEwan Crawford     m_breakAllKernels = false;
35877dc7771cSEwan Crawford 
35887dc7771cSEwan Crawford     if (log)
3589b9c1b51eSKate Stone       log->Printf("%s(False) - breakpoints no longer automatically set.",
3590b9c1b51eSKate Stone                   __FUNCTION__);
35917dc7771cSEwan Crawford   }
35927dc7771cSEwan Crawford }
35937dc7771cSEwan Crawford 
359405097246SAdrian Prantl // Given the name of a kernel this function creates a breakpoint using our own
359505097246SAdrian Prantl // breakpoint resolver, and returns the Breakpoint shared pointer.
35967dc7771cSEwan Crawford BreakpointSP
3597b9c1b51eSKate Stone RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) {
3598b9c1b51eSKate Stone   Log *log(
3599b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
36007dc7771cSEwan Crawford 
3601b9c1b51eSKate Stone   if (!m_filtersp) {
36027dc7771cSEwan Crawford     if (log)
3603b3f7f69dSAidan Dodds       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
36047dc7771cSEwan Crawford     return nullptr;
36057dc7771cSEwan Crawford   }
36067dc7771cSEwan Crawford 
36077dc7771cSEwan Crawford   BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3608b842f2ecSJim Ingham   Target &target = GetProcess()->GetTarget();
3609b842f2ecSJim Ingham   BreakpointSP bp = target.CreateBreakpoint(
3610b9c1b51eSKate Stone       m_filtersp, resolver_sp, false, false, false);
36117dc7771cSEwan Crawford 
3612b9c1b51eSKate Stone   // Give RS breakpoints a specific name, so the user can manipulate them as a
3613b9c1b51eSKate Stone   // group.
361497206d57SZachary Turner   Status err;
3615b842f2ecSJim Ingham   target.AddNameToBreakpoint(bp, "RenderScriptKernel", err);
3616b842f2ecSJim Ingham   if (err.Fail() && log)
3617b3bbcb12SLuke Drummond     if (log)
3618b3bbcb12SLuke Drummond       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3619b3bbcb12SLuke Drummond                   err.AsCString());
3620b3bbcb12SLuke Drummond 
3621b3bbcb12SLuke Drummond   return bp;
3622b3bbcb12SLuke Drummond }
3623b3bbcb12SLuke Drummond 
3624b3bbcb12SLuke Drummond BreakpointSP
3625b3bbcb12SLuke Drummond RenderScriptRuntime::CreateReductionBreakpoint(const ConstString &name,
3626b3bbcb12SLuke Drummond                                                int kernel_types) {
3627b3bbcb12SLuke Drummond   Log *log(
3628b3bbcb12SLuke Drummond       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3629b3bbcb12SLuke Drummond 
3630b3bbcb12SLuke Drummond   if (!m_filtersp) {
3631b3bbcb12SLuke Drummond     if (log)
3632b3bbcb12SLuke Drummond       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3633b3bbcb12SLuke Drummond     return nullptr;
3634b3bbcb12SLuke Drummond   }
3635b3bbcb12SLuke Drummond 
3636b3bbcb12SLuke Drummond   BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3637b3bbcb12SLuke Drummond       nullptr, name, &m_rsmodules, kernel_types));
3638b842f2ecSJim Ingham   Target &target = GetProcess()->GetTarget();
3639b842f2ecSJim Ingham   BreakpointSP bp = target.CreateBreakpoint(
3640b3bbcb12SLuke Drummond       m_filtersp, resolver_sp, false, false, false);
3641b3bbcb12SLuke Drummond 
3642b3bbcb12SLuke Drummond   // Give RS breakpoints a specific name, so the user can manipulate them as a
3643b3bbcb12SLuke Drummond   // group.
364497206d57SZachary Turner   Status err;
3645b842f2ecSJim Ingham   target.AddNameToBreakpoint(bp, "RenderScriptReduction", err);
3646b842f2ecSJim Ingham   if (err.Fail() && log)
3647b9c1b51eSKate Stone       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3648b9c1b51eSKate Stone                   err.AsCString());
364954782db7SEwan Crawford 
36507dc7771cSEwan Crawford   return bp;
36517dc7771cSEwan Crawford }
36527dc7771cSEwan Crawford 
3653b9c1b51eSKate Stone // Given an expression for a variable this function tries to calculate the
365480af0b9eSLuke Drummond // variable's value. If this is possible it returns true and sets the uint64_t
365580af0b9eSLuke Drummond // parameter to the variables unsigned value. Otherwise function returns false.
3656b9c1b51eSKate Stone bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3657b9c1b51eSKate Stone                                                 const char *var_name,
3658b9c1b51eSKate Stone                                                 uint64_t &val) {
3659018f5a7eSEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
366097206d57SZachary Turner   Status err;
3661018f5a7eSEwan Crawford   VariableSP var_sp;
3662018f5a7eSEwan Crawford 
3663018f5a7eSEwan Crawford   // Find variable in stack frame
3664b3f7f69dSAidan Dodds   ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3665b3f7f69dSAidan Dodds       var_name, eNoDynamicValues,
3666b9c1b51eSKate Stone       StackFrame::eExpressionPathOptionCheckPtrVsMember |
3667b9c1b51eSKate Stone           StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
366880af0b9eSLuke Drummond       var_sp, err));
366980af0b9eSLuke Drummond   if (!err.Success()) {
3670018f5a7eSEwan Crawford     if (log)
3671b9c1b51eSKate Stone       log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__,
3672b9c1b51eSKate Stone                   var_name);
3673018f5a7eSEwan Crawford     return false;
3674018f5a7eSEwan Crawford   }
3675018f5a7eSEwan Crawford 
3676b3f7f69dSAidan Dodds   // Find the uint32_t value for the variable
3677018f5a7eSEwan Crawford   bool success = false;
3678018f5a7eSEwan Crawford   val = value_sp->GetValueAsUnsigned(0, &success);
3679b9c1b51eSKate Stone   if (!success) {
3680018f5a7eSEwan Crawford     if (log)
3681b9c1b51eSKate Stone       log->Printf("%s - error, couldn't parse '%s' as an uint32_t.",
3682b9c1b51eSKate Stone                   __FUNCTION__, var_name);
3683018f5a7eSEwan Crawford     return false;
3684018f5a7eSEwan Crawford   }
3685018f5a7eSEwan Crawford 
3686018f5a7eSEwan Crawford   return true;
3687018f5a7eSEwan Crawford }
3688018f5a7eSEwan Crawford 
3689b9c1b51eSKate Stone // Function attempts to find the current coordinate of a kernel invocation by
369080af0b9eSLuke Drummond // investigating the values of frame variables in the .expand function. These
369180af0b9eSLuke Drummond // coordinates are returned via the coord array reference parameter. Returns
369280af0b9eSLuke Drummond // true if the coordinates could be found, and false otherwise.
3693b9c1b51eSKate Stone bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3694b9c1b51eSKate Stone                                               Thread *thread_ptr) {
369500f56eebSLuke Drummond   static const char *const x_expr = "rsIndex";
369600f56eebSLuke Drummond   static const char *const y_expr = "p->current.y";
369700f56eebSLuke Drummond   static const char *const z_expr = "p->current.z";
36981e05c3bcSGreg Clayton 
36994f8817c2SEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
37004f8817c2SEwan Crawford 
3701b9c1b51eSKate Stone   if (!thread_ptr) {
37024f8817c2SEwan Crawford     if (log)
37034f8817c2SEwan Crawford       log->Printf("%s - Error, No thread pointer", __FUNCTION__);
37044f8817c2SEwan Crawford 
37054f8817c2SEwan Crawford     return false;
37064f8817c2SEwan Crawford   }
37074f8817c2SEwan Crawford 
3708b9c1b51eSKate Stone   // Walk the call stack looking for a function whose name has the suffix
370980af0b9eSLuke Drummond   // '.expand' and contains the variables we're looking for.
3710b9c1b51eSKate Stone   for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
37114f8817c2SEwan Crawford     if (!thread_ptr->SetSelectedFrameByIndex(i))
37124f8817c2SEwan Crawford       continue;
37134f8817c2SEwan Crawford 
37144f8817c2SEwan Crawford     StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
37154f8817c2SEwan Crawford     if (!frame_sp)
37164f8817c2SEwan Crawford       continue;
37174f8817c2SEwan Crawford 
37184f8817c2SEwan Crawford     // Find the function name
3719991e4453SZachary Turner     const SymbolContext sym_ctx =
3720991e4453SZachary Turner         frame_sp->GetSymbolContext(eSymbolContextFunction);
372100f56eebSLuke Drummond     const ConstString func_name = sym_ctx.GetFunctionName();
372200f56eebSLuke Drummond     if (!func_name)
37234f8817c2SEwan Crawford       continue;
37244f8817c2SEwan Crawford 
37254f8817c2SEwan Crawford     if (log)
3726b9c1b51eSKate Stone       log->Printf("%s - Inspecting function '%s'", __FUNCTION__,
372700f56eebSLuke Drummond                   func_name.GetCString());
37284f8817c2SEwan Crawford 
37294f8817c2SEwan Crawford     // Check if function name has .expand suffix
373000f56eebSLuke Drummond     if (!func_name.GetStringRef().endswith(".expand"))
37314f8817c2SEwan Crawford       continue;
37324f8817c2SEwan Crawford 
37334f8817c2SEwan Crawford     if (log)
3734b9c1b51eSKate Stone       log->Printf("%s - Found .expand function '%s'", __FUNCTION__,
373500f56eebSLuke Drummond                   func_name.GetCString());
37364f8817c2SEwan Crawford 
373705097246SAdrian Prantl     // Get values for variables in .expand frame that tell us the current
373805097246SAdrian Prantl     // kernel invocation
373900f56eebSLuke Drummond     uint64_t x, y, z;
374000f56eebSLuke Drummond     bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
374100f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
374200f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, z_expr, z);
37434f8817c2SEwan Crawford 
374400f56eebSLuke Drummond     if (found) {
374500f56eebSLuke Drummond       // The RenderScript runtime uses uint32_t for these vars. If they're not
374600f56eebSLuke Drummond       // within bounds, our frame parsing is garbage
374700f56eebSLuke Drummond       assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
374800f56eebSLuke Drummond       coord.x = (uint32_t)x;
374900f56eebSLuke Drummond       coord.y = (uint32_t)y;
375000f56eebSLuke Drummond       coord.z = (uint32_t)z;
37514f8817c2SEwan Crawford       return true;
37524f8817c2SEwan Crawford     }
375300f56eebSLuke Drummond   }
37544f8817c2SEwan Crawford   return false;
37554f8817c2SEwan Crawford }
37564f8817c2SEwan Crawford 
3757b9c1b51eSKate Stone // Callback when a kernel breakpoint hits and we're looking for a specific
375880af0b9eSLuke Drummond // coordinate. Baton parameter contains a pointer to the target coordinate we
375905097246SAdrian Prantl // want to break on. Function then checks the .expand frame for the current
376005097246SAdrian Prantl // coordinate and breaks to user if it matches. Parameter 'break_id' is the id
376105097246SAdrian Prantl // of the Breakpoint which made the callback. Parameter 'break_loc_id' is the
376205097246SAdrian Prantl // id for the BreakpointLocation which was hit, a single logical breakpoint can
376305097246SAdrian Prantl // have multiple addresses.
3764b9c1b51eSKate Stone bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3765b9c1b51eSKate Stone                                               StoppointCallbackContext *ctx,
3766b9c1b51eSKate Stone                                               user_id_t break_id,
3767b9c1b51eSKate Stone                                               user_id_t break_loc_id) {
3768b9c1b51eSKate Stone   Log *log(
3769b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3770018f5a7eSEwan Crawford 
3771b9c1b51eSKate Stone   assert(baton &&
3772b9c1b51eSKate Stone          "Error: null baton in conditional kernel breakpoint callback");
3773018f5a7eSEwan Crawford 
3774018f5a7eSEwan Crawford   // Coordinate we want to stop on
377500f56eebSLuke Drummond   RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3776018f5a7eSEwan Crawford 
3777018f5a7eSEwan Crawford   if (log)
377800f56eebSLuke Drummond     log->Printf("%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__, break_id,
377900f56eebSLuke Drummond                 target_coord.x, target_coord.y, target_coord.z);
3780018f5a7eSEwan Crawford 
37814f8817c2SEwan Crawford   // Select current thread
3782018f5a7eSEwan Crawford   ExecutionContext context(ctx->exe_ctx_ref);
37834f8817c2SEwan Crawford   Thread *thread_ptr = context.GetThreadPtr();
37844f8817c2SEwan Crawford   assert(thread_ptr && "Null thread pointer");
37854f8817c2SEwan Crawford 
37864f8817c2SEwan Crawford   // Find current kernel invocation from .expand frame variables
378700f56eebSLuke Drummond   RSCoordinate current_coord{};
3788b9c1b51eSKate Stone   if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3789018f5a7eSEwan Crawford     if (log)
3790b9c1b51eSKate Stone       log->Printf("%s - Error, couldn't select .expand stack frame",
3791b9c1b51eSKate Stone                   __FUNCTION__);
3792018f5a7eSEwan Crawford     return false;
3793018f5a7eSEwan Crawford   }
3794018f5a7eSEwan Crawford 
3795018f5a7eSEwan Crawford   if (log)
379600f56eebSLuke Drummond     log->Printf("%s - " FMT_COORD, __FUNCTION__, current_coord.x,
379700f56eebSLuke Drummond                 current_coord.y, current_coord.z);
3798018f5a7eSEwan Crawford 
3799b9c1b51eSKate Stone   // Check if the current kernel invocation coordinate matches our target
3800b9c1b51eSKate Stone   // coordinate
380100f56eebSLuke Drummond   if (target_coord == current_coord) {
3802018f5a7eSEwan Crawford     if (log)
380300f56eebSLuke Drummond       log->Printf("%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
380400f56eebSLuke Drummond                   current_coord.y, current_coord.z);
3805018f5a7eSEwan Crawford 
3806b9c1b51eSKate Stone     BreakpointSP breakpoint_sp =
3807b9c1b51eSKate Stone         context.GetTargetPtr()->GetBreakpointByID(break_id);
3808b9c1b51eSKate Stone     assert(breakpoint_sp != nullptr &&
3809b9c1b51eSKate Stone            "Error: Couldn't find breakpoint matching break id for callback");
3810b9c1b51eSKate Stone     breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3811b9c1b51eSKate Stone                                       // should only be hit once.
3812018f5a7eSEwan Crawford     return true;
3813018f5a7eSEwan Crawford   }
3814018f5a7eSEwan Crawford 
3815018f5a7eSEwan Crawford   // No match on coordinate
3816018f5a7eSEwan Crawford   return false;
3817018f5a7eSEwan Crawford }
3818018f5a7eSEwan Crawford 
381900f56eebSLuke Drummond void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
382000f56eebSLuke Drummond                                          const RSCoordinate &coord) {
382100f56eebSLuke Drummond   messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
382200f56eebSLuke Drummond                   coord.x, coord.y, coord.z);
382300f56eebSLuke Drummond   messages.EOL();
382400f56eebSLuke Drummond 
382500f56eebSLuke Drummond   // Allocate memory for the baton, and copy over coordinate
382600f56eebSLuke Drummond   RSCoordinate *baton = new RSCoordinate(coord);
382700f56eebSLuke Drummond 
382800f56eebSLuke Drummond   // Create a callback that will be invoked every time the breakpoint is hit.
382900f56eebSLuke Drummond   // The baton object passed to the handler is the target coordinate we want to
383000f56eebSLuke Drummond   // break on.
383100f56eebSLuke Drummond   bp->SetCallback(KernelBreakpointHit, baton, true);
383200f56eebSLuke Drummond 
383300f56eebSLuke Drummond   // Store a shared pointer to the baton, so the memory will eventually be
383400f56eebSLuke Drummond   // cleaned up after destruction
383500f56eebSLuke Drummond   m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
383600f56eebSLuke Drummond }
383700f56eebSLuke Drummond 
383805097246SAdrian Prantl // Tries to set a breakpoint on the start of a kernel, resolved using the
383905097246SAdrian Prantl // kernel name. Argument 'coords', represents a three dimensional coordinate
384005097246SAdrian Prantl // which can be used to specify a single kernel instance to break on. If this
384105097246SAdrian Prantl // is set then we add a callback to the breakpoint.
384200f56eebSLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
384300f56eebSLuke Drummond                                                   Stream &messages,
384400f56eebSLuke Drummond                                                   const char *name,
384500f56eebSLuke Drummond                                                   const RSCoordinate *coord) {
384600f56eebSLuke Drummond   if (!name)
384700f56eebSLuke Drummond     return false;
38484640cde1SColin Riley 
38497dc7771cSEwan Crawford   InitSearchFilter(target);
385098156583SEwan Crawford 
38514640cde1SColin Riley   ConstString kernel_name(name);
38527dc7771cSEwan Crawford   BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
385300f56eebSLuke Drummond   if (!bp)
385400f56eebSLuke Drummond     return false;
3855018f5a7eSEwan Crawford 
3856018f5a7eSEwan Crawford   // We have a conditional breakpoint on a specific coordinate
385700f56eebSLuke Drummond   if (coord)
385800f56eebSLuke Drummond     SetConditional(bp, messages, *coord);
3859018f5a7eSEwan Crawford 
386000f56eebSLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3861018f5a7eSEwan Crawford 
386200f56eebSLuke Drummond   return true;
38634640cde1SColin Riley }
38644640cde1SColin Riley 
386521fed052SAidan Dodds BreakpointSP
386621fed052SAidan Dodds RenderScriptRuntime::CreateScriptGroupBreakpoint(const ConstString &name,
386721fed052SAidan Dodds                                                  bool stop_on_all) {
386821fed052SAidan Dodds   Log *log(
386921fed052SAidan Dodds       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
387021fed052SAidan Dodds 
387121fed052SAidan Dodds   if (!m_filtersp) {
387221fed052SAidan Dodds     if (log)
387321fed052SAidan Dodds       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
387421fed052SAidan Dodds     return nullptr;
387521fed052SAidan Dodds   }
387621fed052SAidan Dodds 
387721fed052SAidan Dodds   BreakpointResolverSP resolver_sp(new RSScriptGroupBreakpointResolver(
387821fed052SAidan Dodds       nullptr, name, m_scriptGroups, stop_on_all));
3879b842f2ecSJim Ingham   Target &target = GetProcess()->GetTarget();
3880b842f2ecSJim Ingham   BreakpointSP bp = target.CreateBreakpoint(
388121fed052SAidan Dodds       m_filtersp, resolver_sp, false, false, false);
388221fed052SAidan Dodds   // Give RS breakpoints a specific name, so the user can manipulate them as a
388321fed052SAidan Dodds   // group.
388497206d57SZachary Turner   Status err;
3885b842f2ecSJim Ingham   target.AddNameToBreakpoint(bp, name.GetCString(), err);
3886b842f2ecSJim Ingham   if (err.Fail() && log)
388721fed052SAidan Dodds     log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
388821fed052SAidan Dodds                 err.AsCString());
388921fed052SAidan Dodds   // ask the breakpoint to resolve itself
389021fed052SAidan Dodds   bp->ResolveBreakpoint();
389121fed052SAidan Dodds   return bp;
389221fed052SAidan Dodds }
389321fed052SAidan Dodds 
389421fed052SAidan Dodds bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target,
389521fed052SAidan Dodds                                                        Stream &strm,
389621fed052SAidan Dodds                                                        const ConstString &name,
389721fed052SAidan Dodds                                                        bool multi) {
389821fed052SAidan Dodds   InitSearchFilter(target);
389921fed052SAidan Dodds   BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi);
390021fed052SAidan Dodds   if (bp)
390121fed052SAidan Dodds     bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
390221fed052SAidan Dodds   return bool(bp);
390321fed052SAidan Dodds }
390421fed052SAidan Dodds 
3905b3bbcb12SLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3906b3bbcb12SLuke Drummond                                                      Stream &messages,
3907b3bbcb12SLuke Drummond                                                      const char *reduce_name,
3908b3bbcb12SLuke Drummond                                                      const RSCoordinate *coord,
3909b3bbcb12SLuke Drummond                                                      int kernel_types) {
3910b3bbcb12SLuke Drummond   if (!reduce_name)
3911b3bbcb12SLuke Drummond     return false;
3912b3bbcb12SLuke Drummond 
3913b3bbcb12SLuke Drummond   InitSearchFilter(target);
3914b3bbcb12SLuke Drummond   BreakpointSP bp =
3915b3bbcb12SLuke Drummond       CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3916b3bbcb12SLuke Drummond   if (!bp)
3917b3bbcb12SLuke Drummond     return false;
3918b3bbcb12SLuke Drummond 
3919b3bbcb12SLuke Drummond   if (coord)
3920b3bbcb12SLuke Drummond     SetConditional(bp, messages, *coord);
3921b3bbcb12SLuke Drummond 
3922b3bbcb12SLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3923b3bbcb12SLuke Drummond 
3924b3bbcb12SLuke Drummond   return true;
3925b3bbcb12SLuke Drummond }
3926b3bbcb12SLuke Drummond 
3927b9c1b51eSKate Stone void RenderScriptRuntime::DumpModules(Stream &strm) const {
39285ec532a9SColin Riley   strm.Printf("RenderScript Modules:");
39295ec532a9SColin Riley   strm.EOL();
39305ec532a9SColin Riley   strm.IndentMore();
3931b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
39324640cde1SColin Riley     module->Dump(strm);
39335ec532a9SColin Riley   }
39345ec532a9SColin Riley   strm.IndentLess();
39355ec532a9SColin Riley }
39365ec532a9SColin Riley 
393778f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails *
3938b9c1b51eSKate Stone RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3939b9c1b51eSKate Stone   for (const auto &s : m_scripts) {
394078f339d1SEwan Crawford     if (s->script.isValid())
394178f339d1SEwan Crawford       if (*s->script == address)
394278f339d1SEwan Crawford         return s.get();
394378f339d1SEwan Crawford   }
3944b9c1b51eSKate Stone   if (create) {
394578f339d1SEwan Crawford     std::unique_ptr<ScriptDetails> s(new ScriptDetails);
394678f339d1SEwan Crawford     s->script = address;
394778f339d1SEwan Crawford     m_scripts.push_back(std::move(s));
3948d10ca9deSEwan Crawford     return m_scripts.back().get();
394978f339d1SEwan Crawford   }
395078f339d1SEwan Crawford   return nullptr;
395178f339d1SEwan Crawford }
395278f339d1SEwan Crawford 
395378f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails *
3954b9c1b51eSKate Stone RenderScriptRuntime::LookUpAllocation(addr_t address) {
3955b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
395678f339d1SEwan Crawford     if (a->address.isValid())
395778f339d1SEwan Crawford       if (*a->address == address)
395878f339d1SEwan Crawford         return a.get();
395978f339d1SEwan Crawford   }
39605d057637SLuke Drummond   return nullptr;
39615d057637SLuke Drummond }
39625d057637SLuke Drummond 
39635d057637SLuke Drummond RenderScriptRuntime::AllocationDetails *
3964b9c1b51eSKate Stone RenderScriptRuntime::CreateAllocation(addr_t address) {
39655d057637SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
39665d057637SLuke Drummond 
39675d057637SLuke Drummond   // Remove any previous allocation which contains the same address
39685d057637SLuke Drummond   auto it = m_allocations.begin();
3969b9c1b51eSKate Stone   while (it != m_allocations.end()) {
3970b9c1b51eSKate Stone     if (*((*it)->address) == address) {
39715d057637SLuke Drummond       if (log)
3972b9c1b51eSKate Stone         log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64,
3973b9c1b51eSKate Stone                     __FUNCTION__, (*it)->id, address);
39745d057637SLuke Drummond 
39755d057637SLuke Drummond       it = m_allocations.erase(it);
3976b9c1b51eSKate Stone     } else {
39775d057637SLuke Drummond       it++;
39785d057637SLuke Drummond     }
39795d057637SLuke Drummond   }
39805d057637SLuke Drummond 
398178f339d1SEwan Crawford   std::unique_ptr<AllocationDetails> a(new AllocationDetails);
398278f339d1SEwan Crawford   a->address = address;
398378f339d1SEwan Crawford   m_allocations.push_back(std::move(a));
3984d10ca9deSEwan Crawford   return m_allocations.back().get();
398578f339d1SEwan Crawford }
398678f339d1SEwan Crawford 
398721fed052SAidan Dodds bool RenderScriptRuntime::ResolveKernelName(lldb::addr_t kernel_addr,
398821fed052SAidan Dodds                                             ConstString &name) {
398921fed052SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
399021fed052SAidan Dodds 
399121fed052SAidan Dodds   Target &target = GetProcess()->GetTarget();
399221fed052SAidan Dodds   Address resolved;
399321fed052SAidan Dodds   // RenderScript module
399421fed052SAidan Dodds   if (!target.GetSectionLoadList().ResolveLoadAddress(kernel_addr, resolved)) {
399521fed052SAidan Dodds     if (log)
399621fed052SAidan Dodds       log->Printf("%s: unable to resolve 0x%" PRIx64 " to a loaded symbol",
399721fed052SAidan Dodds                   __FUNCTION__, kernel_addr);
399821fed052SAidan Dodds     return false;
399921fed052SAidan Dodds   }
400021fed052SAidan Dodds 
400121fed052SAidan Dodds   Symbol *sym = resolved.CalculateSymbolContextSymbol();
400221fed052SAidan Dodds   if (!sym)
400321fed052SAidan Dodds     return false;
400421fed052SAidan Dodds 
400521fed052SAidan Dodds   name = sym->GetName();
400621fed052SAidan Dodds   assert(IsRenderScriptModule(resolved.CalculateSymbolContextModule()));
400721fed052SAidan Dodds   if (log)
400821fed052SAidan Dodds     log->Printf("%s: 0x%" PRIx64 " resolved to the symbol '%s'", __FUNCTION__,
400921fed052SAidan Dodds                 kernel_addr, name.GetCString());
401021fed052SAidan Dodds   return true;
401121fed052SAidan Dodds }
401221fed052SAidan Dodds 
4013b9c1b51eSKate Stone void RSModuleDescriptor::Dump(Stream &strm) const {
40147f193d69SLuke Drummond   int indent = strm.GetIndentLevel();
40157f193d69SLuke Drummond 
40165ec532a9SColin Riley   strm.Indent();
40175ec532a9SColin Riley   m_module->GetFileSpec().Dump(&strm);
40187f193d69SLuke Drummond   strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
40197f193d69SLuke Drummond                                              : "Debug info does not exist.");
40205ec532a9SColin Riley   strm.EOL();
40215ec532a9SColin Riley   strm.IndentMore();
40227f193d69SLuke Drummond 
40235ec532a9SColin Riley   strm.Indent();
4024189598edSColin Riley   strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
40255ec532a9SColin Riley   strm.EOL();
40265ec532a9SColin Riley   strm.IndentMore();
4027b9c1b51eSKate Stone   for (const auto &global : m_globals) {
40285ec532a9SColin Riley     global.Dump(strm);
40295ec532a9SColin Riley   }
40305ec532a9SColin Riley   strm.IndentLess();
40317f193d69SLuke Drummond 
40325ec532a9SColin Riley   strm.Indent();
4033189598edSColin Riley   strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
40345ec532a9SColin Riley   strm.EOL();
40355ec532a9SColin Riley   strm.IndentMore();
4036b9c1b51eSKate Stone   for (const auto &kernel : m_kernels) {
40375ec532a9SColin Riley     kernel.Dump(strm);
40385ec532a9SColin Riley   }
40397f193d69SLuke Drummond   strm.IndentLess();
40407f193d69SLuke Drummond 
40417f193d69SLuke Drummond   strm.Indent();
40424640cde1SColin Riley   strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
40434640cde1SColin Riley   strm.EOL();
40444640cde1SColin Riley   strm.IndentMore();
4045b9c1b51eSKate Stone   for (const auto &key_val : m_pragmas) {
40467f193d69SLuke Drummond     strm.Indent();
40474640cde1SColin Riley     strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
40484640cde1SColin Riley     strm.EOL();
40494640cde1SColin Riley   }
40507f193d69SLuke Drummond   strm.IndentLess();
40517f193d69SLuke Drummond 
40527f193d69SLuke Drummond   strm.Indent();
40537f193d69SLuke Drummond   strm.Printf("Reductions: %" PRIu64,
40547f193d69SLuke Drummond               static_cast<uint64_t>(m_reductions.size()));
40557f193d69SLuke Drummond   strm.EOL();
40567f193d69SLuke Drummond   strm.IndentMore();
40577f193d69SLuke Drummond   for (const auto &reduction : m_reductions) {
40587f193d69SLuke Drummond     reduction.Dump(strm);
40597f193d69SLuke Drummond   }
40607f193d69SLuke Drummond 
40617f193d69SLuke Drummond   strm.SetIndentLevel(indent);
40625ec532a9SColin Riley }
40635ec532a9SColin Riley 
4064b9c1b51eSKate Stone void RSGlobalDescriptor::Dump(Stream &strm) const {
40655ec532a9SColin Riley   strm.Indent(m_name.AsCString());
40664640cde1SColin Riley   VariableList var_list;
406734cda14bSPavel Labath   m_module->m_module->FindGlobalVariables(m_name, nullptr, 1U, var_list);
4068b9c1b51eSKate Stone   if (var_list.GetSize() == 1) {
40694640cde1SColin Riley     auto var = var_list.GetVariableAtIndex(0);
40704640cde1SColin Riley     auto type = var->GetType();
4071b9c1b51eSKate Stone     if (type) {
40724640cde1SColin Riley       strm.Printf(" - ");
40734640cde1SColin Riley       type->DumpTypeName(&strm);
4074b9c1b51eSKate Stone     } else {
40754640cde1SColin Riley       strm.Printf(" - Unknown Type");
40764640cde1SColin Riley     }
4077b9c1b51eSKate Stone   } else {
40784640cde1SColin Riley     strm.Printf(" - variable identified, but not found in binary");
4079b9c1b51eSKate Stone     const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
4080b9c1b51eSKate Stone         m_name, eSymbolTypeData);
4081b9c1b51eSKate Stone     if (s) {
40824640cde1SColin Riley       strm.Printf(" (symbol exists) ");
40834640cde1SColin Riley     }
40844640cde1SColin Riley   }
40854640cde1SColin Riley 
40865ec532a9SColin Riley   strm.EOL();
40875ec532a9SColin Riley }
40885ec532a9SColin Riley 
4089b9c1b51eSKate Stone void RSKernelDescriptor::Dump(Stream &strm) const {
40905ec532a9SColin Riley   strm.Indent(m_name.AsCString());
40915ec532a9SColin Riley   strm.EOL();
40925ec532a9SColin Riley }
40935ec532a9SColin Riley 
40947f193d69SLuke Drummond void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
40957f193d69SLuke Drummond   stream.Indent(m_reduce_name.AsCString());
40967f193d69SLuke Drummond   stream.IndentMore();
40977f193d69SLuke Drummond   stream.EOL();
40987f193d69SLuke Drummond   stream.Indent();
40997f193d69SLuke Drummond   stream.Printf("accumulator: %s", m_accum_name.AsCString());
41007f193d69SLuke Drummond   stream.EOL();
41017f193d69SLuke Drummond   stream.Indent();
41027f193d69SLuke Drummond   stream.Printf("initializer: %s", m_init_name.AsCString());
41037f193d69SLuke Drummond   stream.EOL();
41047f193d69SLuke Drummond   stream.Indent();
41057f193d69SLuke Drummond   stream.Printf("combiner: %s", m_comb_name.AsCString());
41067f193d69SLuke Drummond   stream.EOL();
41077f193d69SLuke Drummond   stream.Indent();
41087f193d69SLuke Drummond   stream.Printf("outconverter: %s", m_outc_name.AsCString());
41097f193d69SLuke Drummond   stream.EOL();
41107f193d69SLuke Drummond   // XXX This is currently unspecified by RenderScript, and unused
41117f193d69SLuke Drummond   // stream.Indent();
41127f193d69SLuke Drummond   // stream.Printf("halter: '%s'", m_init_name.AsCString());
41137f193d69SLuke Drummond   // stream.EOL();
41147f193d69SLuke Drummond   stream.IndentLess();
41157f193d69SLuke Drummond }
41167f193d69SLuke Drummond 
4117b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
41185ec532a9SColin Riley public:
41195ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
4120b9c1b51eSKate Stone       : CommandObjectParsed(
4121b9c1b51eSKate Stone             interpreter, "renderscript module dump",
4122b9c1b51eSKate Stone             "Dumps renderscript specific information for all modules.",
4123b9c1b51eSKate Stone             "renderscript module dump",
4124b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
41255ec532a9SColin Riley 
4126222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
41275ec532a9SColin Riley 
4128b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
41295ec532a9SColin Riley     RenderScriptRuntime *runtime =
4130b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4131b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
41325ec532a9SColin Riley     runtime->DumpModules(result.GetOutputStream());
41335ec532a9SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
41345ec532a9SColin Riley     return true;
41355ec532a9SColin Riley   }
41365ec532a9SColin Riley };
41375ec532a9SColin Riley 
4138b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
41395ec532a9SColin Riley public:
41405ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
4141b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript module",
4142b9c1b51eSKate Stone                                "Commands that deal with RenderScript modules.",
4143b9c1b51eSKate Stone                                nullptr) {
4144b9c1b51eSKate Stone     LoadSubCommand(
4145b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
4146b9c1b51eSKate Stone                     interpreter)));
41475ec532a9SColin Riley   }
41485ec532a9SColin Riley 
4149222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModule() override = default;
41505ec532a9SColin Riley };
41515ec532a9SColin Riley 
4152b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
41534640cde1SColin Riley public:
41544640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
4155b9c1b51eSKate Stone       : CommandObjectParsed(
4156b9c1b51eSKate Stone             interpreter, "renderscript kernel list",
4157b3f7f69dSAidan Dodds             "Lists renderscript kernel names and associated script resources.",
4158b9c1b51eSKate Stone             "renderscript kernel list",
4159b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
41604640cde1SColin Riley 
4161222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelList() override = default;
41624640cde1SColin Riley 
4163b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
41644640cde1SColin Riley     RenderScriptRuntime *runtime =
4165b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4166b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
41674640cde1SColin Riley     runtime->DumpKernels(result.GetOutputStream());
41684640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
41694640cde1SColin Riley     return true;
41704640cde1SColin Riley   }
41714640cde1SColin Riley };
41724640cde1SColin Riley 
41738fe53c49STatyana Krasnukha static constexpr OptionDefinition g_renderscript_reduction_bp_set_options[] = {
4174b3bbcb12SLuke Drummond     {LLDB_OPT_SET_1, false, "function-role", 't',
41758fe53c49STatyana Krasnukha      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOneLiner,
4176b3bbcb12SLuke Drummond      "Break on a comma separated set of reduction kernel types "
4177b3bbcb12SLuke Drummond      "(accumulator,outcoverter,combiner,initializer"},
4178b3bbcb12SLuke Drummond     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
41798fe53c49STatyana Krasnukha      nullptr, {}, 0, eArgTypeValue,
4180b3bbcb12SLuke Drummond      "Set a breakpoint on a single invocation of the kernel with specified "
4181b3bbcb12SLuke Drummond      "coordinate.\n"
4182b3bbcb12SLuke Drummond      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4183b3bbcb12SLuke Drummond      "integers representing kernel dimensions. "
4184b3bbcb12SLuke Drummond      "Any unset dimensions will be defaulted to zero."}};
4185b3bbcb12SLuke Drummond 
4186b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReductionBreakpointSet
4187b3bbcb12SLuke Drummond     : public CommandObjectParsed {
4188b3bbcb12SLuke Drummond public:
4189b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4190b3bbcb12SLuke Drummond       CommandInterpreter &interpreter)
4191b3bbcb12SLuke Drummond       : CommandObjectParsed(
4192b3bbcb12SLuke Drummond             interpreter, "renderscript reduction breakpoint set",
4193b3bbcb12SLuke Drummond             "Set a breakpoint on named RenderScript general reductions",
4194b3bbcb12SLuke Drummond             "renderscript reduction breakpoint set  <kernel_name> [-t "
4195b3bbcb12SLuke Drummond             "<reduction_kernel_type,...>]",
4196b3bbcb12SLuke Drummond             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4197b3bbcb12SLuke Drummond                 eCommandProcessMustBePaused),
4198b3bbcb12SLuke Drummond         m_options(){};
4199b3bbcb12SLuke Drummond 
4200b3bbcb12SLuke Drummond   class CommandOptions : public Options {
4201b3bbcb12SLuke Drummond   public:
4202b3bbcb12SLuke Drummond     CommandOptions()
4203b3bbcb12SLuke Drummond         : Options(),
4204b3bbcb12SLuke Drummond           m_kernel_types(RSReduceBreakpointResolver::eKernelTypeAll) {}
4205b3bbcb12SLuke Drummond 
4206b3bbcb12SLuke Drummond     ~CommandOptions() override = default;
4207b3bbcb12SLuke Drummond 
420897206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4209b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
421097206d57SZachary Turner       Status err;
4211b3bbcb12SLuke Drummond       StreamString err_str;
4212b3bbcb12SLuke Drummond       const int short_option = m_getopt_table[option_idx].val;
4213b3bbcb12SLuke Drummond       switch (short_option) {
4214b3bbcb12SLuke Drummond       case 't':
4215fe11483bSZachary Turner         if (!ParseReductionTypes(option_arg, err_str))
4216b3bbcb12SLuke Drummond           err.SetErrorStringWithFormat(
4217fe11483bSZachary Turner               "Unable to deduce reduction types for %s: %s",
4218fe11483bSZachary Turner               option_arg.str().c_str(), err_str.GetData());
4219b3bbcb12SLuke Drummond         break;
4220b3bbcb12SLuke Drummond       case 'c': {
4221b3bbcb12SLuke Drummond         auto coord = RSCoordinate{};
4222fe11483bSZachary Turner         if (!ParseCoordinate(option_arg, coord))
4223b3bbcb12SLuke Drummond           err.SetErrorStringWithFormat("unable to parse coordinate for %s",
4224fe11483bSZachary Turner                                        option_arg.str().c_str());
4225b3bbcb12SLuke Drummond         else {
4226b3bbcb12SLuke Drummond           m_have_coord = true;
4227b3bbcb12SLuke Drummond           m_coord = coord;
4228b3bbcb12SLuke Drummond         }
4229b3bbcb12SLuke Drummond         break;
4230b3bbcb12SLuke Drummond       }
4231b3bbcb12SLuke Drummond       default:
4232b3bbcb12SLuke Drummond         err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
4233b3bbcb12SLuke Drummond       }
4234b3bbcb12SLuke Drummond       return err;
4235b3bbcb12SLuke Drummond     }
4236b3bbcb12SLuke Drummond 
4237b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4238b3bbcb12SLuke Drummond       m_have_coord = false;
4239b3bbcb12SLuke Drummond     }
4240b3bbcb12SLuke Drummond 
4241b3bbcb12SLuke Drummond     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4242b3bbcb12SLuke Drummond       return llvm::makeArrayRef(g_renderscript_reduction_bp_set_options);
4243b3bbcb12SLuke Drummond     }
4244b3bbcb12SLuke Drummond 
4245fe11483bSZachary Turner     bool ParseReductionTypes(llvm::StringRef option_val,
4246fe11483bSZachary Turner                              StreamString &err_str) {
4247b3bbcb12SLuke Drummond       m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
4248b3bbcb12SLuke Drummond       const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
4249b3bbcb12SLuke Drummond         return llvm::StringSwitch<int>(name)
4250b3bbcb12SLuke Drummond             .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
4251b3bbcb12SLuke Drummond             .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
4252b3bbcb12SLuke Drummond             .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
4253b3bbcb12SLuke Drummond             .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
4254b3bbcb12SLuke Drummond             .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
4255b3bbcb12SLuke Drummond             // Currently not exposed by the runtime
4256b3bbcb12SLuke Drummond             // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
4257b3bbcb12SLuke Drummond             .Default(0);
4258b3bbcb12SLuke Drummond       };
4259b3bbcb12SLuke Drummond 
4260b3bbcb12SLuke Drummond       // Matching a comma separated list of known words is fairly
426105097246SAdrian Prantl       // straightforward with PCRE, but we're using ERE, so we end up with a
426205097246SAdrian Prantl       // little ugliness...
4263b3bbcb12SLuke Drummond       RegularExpression::Match match(/* max_matches */ 5);
4264b3bbcb12SLuke Drummond       RegularExpression match_type_list(
4265b3bbcb12SLuke Drummond           llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
4266b3bbcb12SLuke Drummond 
4267b3bbcb12SLuke Drummond       assert(match_type_list.IsValid());
4268b3bbcb12SLuke Drummond 
4269fe11483bSZachary Turner       if (!match_type_list.Execute(option_val, &match)) {
4270b3bbcb12SLuke Drummond         err_str.PutCString(
4271b3bbcb12SLuke Drummond             "a comma-separated list of kernel types is required");
4272b3bbcb12SLuke Drummond         return false;
4273b3bbcb12SLuke Drummond       }
4274b3bbcb12SLuke Drummond 
4275b3bbcb12SLuke Drummond       // splitting on commas is much easier with llvm::StringRef than regex
4276b3bbcb12SLuke Drummond       llvm::SmallVector<llvm::StringRef, 5> type_names;
4277b3bbcb12SLuke Drummond       llvm::StringRef(option_val).split(type_names, ',');
4278b3bbcb12SLuke Drummond 
4279b3bbcb12SLuke Drummond       for (const auto &name : type_names) {
4280b3bbcb12SLuke Drummond         const int type = reduce_name_to_type(name);
4281b3bbcb12SLuke Drummond         if (!type) {
4282b3bbcb12SLuke Drummond           err_str.Printf("unknown kernel type name %s", name.str().c_str());
4283b3bbcb12SLuke Drummond           return false;
4284b3bbcb12SLuke Drummond         }
4285b3bbcb12SLuke Drummond         m_kernel_types |= type;
4286b3bbcb12SLuke Drummond       }
4287b3bbcb12SLuke Drummond 
4288b3bbcb12SLuke Drummond       return true;
4289b3bbcb12SLuke Drummond     }
4290b3bbcb12SLuke Drummond 
4291b3bbcb12SLuke Drummond     int m_kernel_types;
4292b3bbcb12SLuke Drummond     llvm::StringRef m_reduce_name;
4293b3bbcb12SLuke Drummond     RSCoordinate m_coord;
4294b3bbcb12SLuke Drummond     bool m_have_coord;
4295b3bbcb12SLuke Drummond   };
4296b3bbcb12SLuke Drummond 
4297b3bbcb12SLuke Drummond   Options *GetOptions() override { return &m_options; }
4298b3bbcb12SLuke Drummond 
4299b3bbcb12SLuke Drummond   bool DoExecute(Args &command, CommandReturnObject &result) override {
4300b3bbcb12SLuke Drummond     const size_t argc = command.GetArgumentCount();
4301b3bbcb12SLuke Drummond     if (argc < 1) {
4302b3bbcb12SLuke Drummond       result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
4303b3bbcb12SLuke Drummond                                    "and an optional kernel type list",
4304b3bbcb12SLuke Drummond                                    m_cmd_name.c_str());
4305b3bbcb12SLuke Drummond       result.SetStatus(eReturnStatusFailed);
4306b3bbcb12SLuke Drummond       return false;
4307b3bbcb12SLuke Drummond     }
4308b3bbcb12SLuke Drummond 
4309b3bbcb12SLuke Drummond     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4310b3bbcb12SLuke Drummond         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4311b3bbcb12SLuke Drummond             eLanguageTypeExtRenderScript));
4312b3bbcb12SLuke Drummond 
4313b3bbcb12SLuke Drummond     auto &outstream = result.GetOutputStream();
4314b3bbcb12SLuke Drummond     auto name = command.GetArgumentAtIndex(0);
4315b3bbcb12SLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
4316b3bbcb12SLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4317b3bbcb12SLuke Drummond     if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
4318b3bbcb12SLuke Drummond                                              m_options.m_kernel_types)) {
4319b3bbcb12SLuke Drummond       result.SetStatus(eReturnStatusFailed);
4320b3bbcb12SLuke Drummond       result.AppendError("Error: unable to place breakpoint on reduction");
4321b3bbcb12SLuke Drummond       return false;
4322b3bbcb12SLuke Drummond     }
4323b3bbcb12SLuke Drummond     result.AppendMessage("Breakpoint(s) created");
4324b3bbcb12SLuke Drummond     result.SetStatus(eReturnStatusSuccessFinishResult);
4325b3bbcb12SLuke Drummond     return true;
4326b3bbcb12SLuke Drummond   }
4327b3bbcb12SLuke Drummond 
4328b3bbcb12SLuke Drummond private:
4329b3bbcb12SLuke Drummond   CommandOptions m_options;
4330b3bbcb12SLuke Drummond };
4331b3bbcb12SLuke Drummond 
43328fe53c49STatyana Krasnukha static constexpr OptionDefinition g_renderscript_kernel_bp_set_options[] = {
43331f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
43348fe53c49STatyana Krasnukha      nullptr, {}, 0, eArgTypeValue,
43351f0f5b5bSZachary Turner      "Set a breakpoint on a single invocation of the kernel with specified "
43361f0f5b5bSZachary Turner      "coordinate.\n"
43371f0f5b5bSZachary Turner      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
43381f0f5b5bSZachary Turner      "integers representing kernel dimensions. "
43391f0f5b5bSZachary Turner      "Any unset dimensions will be defaulted to zero."}};
43401f0f5b5bSZachary Turner 
4341b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointSet
4342b9c1b51eSKate Stone     : public CommandObjectParsed {
43434640cde1SColin Riley public:
4344b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4345b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4346b9c1b51eSKate Stone       : CommandObjectParsed(
4347b9c1b51eSKate Stone             interpreter, "renderscript kernel breakpoint set",
4348b3f7f69dSAidan Dodds             "Sets a breakpoint on a renderscript kernel.",
4349b3f7f69dSAidan Dodds             "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
4350b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4351b9c1b51eSKate Stone                 eCommandProcessMustBePaused),
4352b9c1b51eSKate Stone         m_options() {}
43534640cde1SColin Riley 
4354222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
4355222b937cSEugene Zelenko 
4356b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
4357018f5a7eSEwan Crawford 
4358b9c1b51eSKate Stone   class CommandOptions : public Options {
4359018f5a7eSEwan Crawford   public:
4360e1cfbc79STodd Fiala     CommandOptions() : Options() {}
4361018f5a7eSEwan Crawford 
4362222b937cSEugene Zelenko     ~CommandOptions() override = default;
4363018f5a7eSEwan Crawford 
436497206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4365b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
436697206d57SZachary Turner       Status err;
4367018f5a7eSEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
4368018f5a7eSEwan Crawford 
4369b9c1b51eSKate Stone       switch (short_option) {
437000f56eebSLuke Drummond       case 'c': {
437100f56eebSLuke Drummond         auto coord = RSCoordinate{};
437200f56eebSLuke Drummond         if (!ParseCoordinate(option_arg, coord))
437380af0b9eSLuke Drummond           err.SetErrorStringWithFormat(
4374b9c1b51eSKate Stone               "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
4375fe11483bSZachary Turner               option_arg.str().c_str());
437600f56eebSLuke Drummond         else {
437700f56eebSLuke Drummond           m_have_coord = true;
437800f56eebSLuke Drummond           m_coord = coord;
437900f56eebSLuke Drummond         }
4380018f5a7eSEwan Crawford         break;
438100f56eebSLuke Drummond       }
4382018f5a7eSEwan Crawford       default:
438380af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4384018f5a7eSEwan Crawford         break;
4385018f5a7eSEwan Crawford       }
438680af0b9eSLuke Drummond       return err;
4387018f5a7eSEwan Crawford     }
4388018f5a7eSEwan Crawford 
4389b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
439000f56eebSLuke Drummond       m_have_coord = false;
4391018f5a7eSEwan Crawford     }
4392018f5a7eSEwan Crawford 
43931f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
439470602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
43951f0f5b5bSZachary Turner     }
4396018f5a7eSEwan Crawford 
439700f56eebSLuke Drummond     RSCoordinate m_coord;
439800f56eebSLuke Drummond     bool m_have_coord;
4399018f5a7eSEwan Crawford   };
4400018f5a7eSEwan Crawford 
4401b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
44024640cde1SColin Riley     const size_t argc = command.GetArgumentCount();
4403b9c1b51eSKate Stone     if (argc < 1) {
4404b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4405b9c1b51eSKate Stone           "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4406b3f7f69dSAidan Dodds           m_cmd_name.c_str());
4407018f5a7eSEwan Crawford       result.SetStatus(eReturnStatusFailed);
4408018f5a7eSEwan Crawford       return false;
4409018f5a7eSEwan Crawford     }
4410018f5a7eSEwan Crawford 
44114640cde1SColin Riley     RenderScriptRuntime *runtime =
4412b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4413b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
44144640cde1SColin Riley 
441500f56eebSLuke Drummond     auto &outstream = result.GetOutputStream();
441600f56eebSLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
441700f56eebSLuke Drummond     auto name = command.GetArgumentAtIndex(0);
441800f56eebSLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
441900f56eebSLuke Drummond     if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
442000f56eebSLuke Drummond       result.SetStatus(eReturnStatusFailed);
442100f56eebSLuke Drummond       result.AppendErrorWithFormat(
442200f56eebSLuke Drummond           "Error: unable to set breakpoint on kernel '%s'", name);
442300f56eebSLuke Drummond       return false;
442400f56eebSLuke Drummond     }
44254640cde1SColin Riley 
44264640cde1SColin Riley     result.AppendMessage("Breakpoint(s) created");
44274640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
44284640cde1SColin Riley     return true;
44294640cde1SColin Riley   }
44304640cde1SColin Riley 
4431018f5a7eSEwan Crawford private:
4432018f5a7eSEwan Crawford   CommandOptions m_options;
44334640cde1SColin Riley };
44344640cde1SColin Riley 
4435b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4436b9c1b51eSKate Stone     : public CommandObjectParsed {
44377dc7771cSEwan Crawford public:
4438b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4439b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4440b3f7f69dSAidan Dodds       : CommandObjectParsed(
4441b3f7f69dSAidan Dodds             interpreter, "renderscript kernel breakpoint all",
4442b9c1b51eSKate Stone             "Automatically sets a breakpoint on all renderscript kernels that "
4443b9c1b51eSKate Stone             "are or will be loaded.\n"
4444b9c1b51eSKate Stone             "Disabling option means breakpoints will no longer be set on any "
4445b9c1b51eSKate Stone             "kernels loaded in the future, "
44467dc7771cSEwan Crawford             "but does not remove currently set breakpoints.",
44477dc7771cSEwan Crawford             "renderscript kernel breakpoint all <enable/disable>",
4448b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4449b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
44507dc7771cSEwan Crawford 
4451222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
44527dc7771cSEwan Crawford 
4453b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
44547dc7771cSEwan Crawford     const size_t argc = command.GetArgumentCount();
4455b9c1b51eSKate Stone     if (argc != 1) {
4456b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4457b9c1b51eSKate Stone           "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
44587dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
44597dc7771cSEwan Crawford       return false;
44607dc7771cSEwan Crawford     }
44617dc7771cSEwan Crawford 
4462b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4463b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4464b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
44657dc7771cSEwan Crawford 
44667dc7771cSEwan Crawford     bool do_break = false;
44677dc7771cSEwan Crawford     const char *argument = command.GetArgumentAtIndex(0);
4468b9c1b51eSKate Stone     if (strcmp(argument, "enable") == 0) {
44697dc7771cSEwan Crawford       do_break = true;
44707dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will be set on all kernels.");
4471b9c1b51eSKate Stone     } else if (strcmp(argument, "disable") == 0) {
44727dc7771cSEwan Crawford       do_break = false;
44737dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will not be set on any new kernels.");
4474b9c1b51eSKate Stone     } else {
4475b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4476b9c1b51eSKate Stone           "Argument must be either 'enable' or 'disable'");
44777dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
44787dc7771cSEwan Crawford       return false;
44797dc7771cSEwan Crawford     }
44807dc7771cSEwan Crawford 
44817dc7771cSEwan Crawford     runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
44827dc7771cSEwan Crawford 
44837dc7771cSEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
44847dc7771cSEwan Crawford     return true;
44857dc7771cSEwan Crawford   }
44867dc7771cSEwan Crawford };
44877dc7771cSEwan Crawford 
4488b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReductionBreakpoint
4489b3bbcb12SLuke Drummond     : public CommandObjectMultiword {
4490b3bbcb12SLuke Drummond public:
4491b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReductionBreakpoint(
4492b3bbcb12SLuke Drummond       CommandInterpreter &interpreter)
4493b3bbcb12SLuke Drummond       : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4494b3bbcb12SLuke Drummond                                "Commands that manipulate breakpoints on "
4495b3bbcb12SLuke Drummond                                "renderscript general reductions.",
4496b3bbcb12SLuke Drummond                                nullptr) {
4497b3bbcb12SLuke Drummond     LoadSubCommand(
4498b3bbcb12SLuke Drummond         "set", CommandObjectSP(
4499b3bbcb12SLuke Drummond                    new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4500b3bbcb12SLuke Drummond                        interpreter)));
4501b3bbcb12SLuke Drummond   }
4502b3bbcb12SLuke Drummond 
4503b3bbcb12SLuke Drummond   ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4504b3bbcb12SLuke Drummond };
4505b3bbcb12SLuke Drummond 
4506b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelCoordinate
4507b9c1b51eSKate Stone     : public CommandObjectParsed {
45084f8817c2SEwan Crawford public:
4509b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelCoordinate(
4510b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4511b9c1b51eSKate Stone       : CommandObjectParsed(
4512b9c1b51eSKate Stone             interpreter, "renderscript kernel coordinate",
45134f8817c2SEwan Crawford             "Shows the (x,y,z) coordinate of the current kernel invocation.",
45144f8817c2SEwan Crawford             "renderscript kernel coordinate",
4515b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4516b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
45174f8817c2SEwan Crawford 
45184f8817c2SEwan Crawford   ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
45194f8817c2SEwan Crawford 
4520b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
452100f56eebSLuke Drummond     RSCoordinate coord{};
4522b9c1b51eSKate Stone     bool success = RenderScriptRuntime::GetKernelCoordinate(
4523b9c1b51eSKate Stone         coord, m_exe_ctx.GetThreadPtr());
45244f8817c2SEwan Crawford     Stream &stream = result.GetOutputStream();
45254f8817c2SEwan Crawford 
4526b9c1b51eSKate Stone     if (success) {
452700f56eebSLuke Drummond       stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
45284f8817c2SEwan Crawford       stream.EOL();
45294f8817c2SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4530b9c1b51eSKate Stone     } else {
45314f8817c2SEwan Crawford       stream.Printf("Error: Coordinate could not be found.");
45324f8817c2SEwan Crawford       stream.EOL();
45334f8817c2SEwan Crawford       result.SetStatus(eReturnStatusFailed);
45344f8817c2SEwan Crawford     }
45354f8817c2SEwan Crawford     return true;
45364f8817c2SEwan Crawford   }
45374f8817c2SEwan Crawford };
45384f8817c2SEwan Crawford 
4539b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpoint
4540b9c1b51eSKate Stone     : public CommandObjectMultiword {
45417dc7771cSEwan Crawford public:
4542b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpoint(
4543b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4544b9c1b51eSKate Stone       : CommandObjectMultiword(
4545b9c1b51eSKate Stone             interpreter, "renderscript kernel",
4546b9c1b51eSKate Stone             "Commands that generate breakpoints on renderscript kernels.",
4547b9c1b51eSKate Stone             nullptr) {
4548b9c1b51eSKate Stone     LoadSubCommand(
4549b9c1b51eSKate Stone         "set",
4550b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4551b9c1b51eSKate Stone             interpreter)));
4552b9c1b51eSKate Stone     LoadSubCommand(
4553b9c1b51eSKate Stone         "all",
4554b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4555b9c1b51eSKate Stone             interpreter)));
45567dc7771cSEwan Crawford   }
45577dc7771cSEwan Crawford 
4558222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
45597dc7771cSEwan Crawford };
45607dc7771cSEwan Crawford 
4561b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
45624640cde1SColin Riley public:
45634640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4564b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript kernel",
4565b9c1b51eSKate Stone                                "Commands that deal with RenderScript kernels.",
4566b9c1b51eSKate Stone                                nullptr) {
4567b9c1b51eSKate Stone     LoadSubCommand(
4568b9c1b51eSKate Stone         "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4569b9c1b51eSKate Stone                     interpreter)));
4570b9c1b51eSKate Stone     LoadSubCommand(
4571b9c1b51eSKate Stone         "coordinate",
4572b9c1b51eSKate Stone         CommandObjectSP(
4573b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4574b9c1b51eSKate Stone     LoadSubCommand(
4575b9c1b51eSKate Stone         "breakpoint",
4576b9c1b51eSKate Stone         CommandObjectSP(
4577b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
45784640cde1SColin Riley   }
45794640cde1SColin Riley 
4580222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernel() override = default;
45814640cde1SColin Riley };
45824640cde1SColin Riley 
4583b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
45844640cde1SColin Riley public:
45854640cde1SColin Riley   CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4586b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript context dump",
4587b9c1b51eSKate Stone                             "Dumps renderscript context information.",
4588b9c1b51eSKate Stone                             "renderscript context dump",
4589b9c1b51eSKate Stone                             eCommandRequiresProcess |
4590b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
45914640cde1SColin Riley 
4592222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContextDump() override = default;
45934640cde1SColin Riley 
4594b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
45954640cde1SColin Riley     RenderScriptRuntime *runtime =
4596b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4597b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
45984640cde1SColin Riley     runtime->DumpContexts(result.GetOutputStream());
45994640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
46004640cde1SColin Riley     return true;
46014640cde1SColin Riley   }
46024640cde1SColin Riley };
46034640cde1SColin Riley 
46048fe53c49STatyana Krasnukha static constexpr OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
46051f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
46068fe53c49STatyana Krasnukha      nullptr, {}, 0, eArgTypeFilename,
46071f0f5b5bSZachary Turner      "Print results to specified file instead of command line."}};
46081f0f5b5bSZachary Turner 
4609b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
46104640cde1SColin Riley public:
46114640cde1SColin Riley   CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4612b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript context",
4613b9c1b51eSKate Stone                                "Commands that deal with RenderScript contexts.",
4614b9c1b51eSKate Stone                                nullptr) {
4615b9c1b51eSKate Stone     LoadSubCommand(
4616b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4617b9c1b51eSKate Stone                     interpreter)));
46184640cde1SColin Riley   }
46194640cde1SColin Riley 
4620222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContext() override = default;
46214640cde1SColin Riley };
46224640cde1SColin Riley 
4623b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationDump
4624b9c1b51eSKate Stone     : public CommandObjectParsed {
4625a0f08674SEwan Crawford public:
4626b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationDump(
4627b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4628a0f08674SEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation dump",
4629b9c1b51eSKate Stone                             "Displays the contents of a particular allocation",
4630b9c1b51eSKate Stone                             "renderscript allocation dump <ID>",
4631b9c1b51eSKate Stone                             eCommandRequiresProcess |
4632b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched),
4633b9c1b51eSKate Stone         m_options() {}
4634a0f08674SEwan Crawford 
4635222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4636222b937cSEugene Zelenko 
4637b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
4638a0f08674SEwan Crawford 
4639b9c1b51eSKate Stone   class CommandOptions : public Options {
4640a0f08674SEwan Crawford   public:
4641e1cfbc79STodd Fiala     CommandOptions() : Options() {}
4642a0f08674SEwan Crawford 
4643222b937cSEugene Zelenko     ~CommandOptions() override = default;
4644a0f08674SEwan Crawford 
464597206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4646b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
464797206d57SZachary Turner       Status err;
4648a0f08674SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
4649a0f08674SEwan Crawford 
4650b9c1b51eSKate Stone       switch (short_option) {
4651a0f08674SEwan Crawford       case 'f':
46528f3be7a3SJonas Devlieghere         m_outfile.SetFile(option_arg, FileSpec::Style::native);
46538f3be7a3SJonas Devlieghere         FileSystem::Instance().Resolve(m_outfile);
4654dbd7fabaSJonas Devlieghere         if (FileSystem::Instance().Exists(m_outfile)) {
4655a0f08674SEwan Crawford           m_outfile.Clear();
4656fe11483bSZachary Turner           err.SetErrorStringWithFormat("file already exists: '%s'",
4657fe11483bSZachary Turner                                        option_arg.str().c_str());
4658a0f08674SEwan Crawford         }
4659a0f08674SEwan Crawford         break;
4660a0f08674SEwan Crawford       default:
466180af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4662a0f08674SEwan Crawford         break;
4663a0f08674SEwan Crawford       }
466480af0b9eSLuke Drummond       return err;
4665a0f08674SEwan Crawford     }
4666a0f08674SEwan Crawford 
4667b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4668a0f08674SEwan Crawford       m_outfile.Clear();
4669a0f08674SEwan Crawford     }
4670a0f08674SEwan Crawford 
46711f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
467270602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
46731f0f5b5bSZachary Turner     }
4674a0f08674SEwan Crawford 
4675a0f08674SEwan Crawford     FileSpec m_outfile;
4676a0f08674SEwan Crawford   };
4677a0f08674SEwan Crawford 
4678b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4679a0f08674SEwan Crawford     const size_t argc = command.GetArgumentCount();
4680b9c1b51eSKate Stone     if (argc < 1) {
4681b9c1b51eSKate Stone       result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4682b9c1b51eSKate Stone                                    "As well as an optional -f argument",
4683a0f08674SEwan Crawford                                    m_cmd_name.c_str());
4684a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4685a0f08674SEwan Crawford       return false;
4686a0f08674SEwan Crawford     }
4687a0f08674SEwan Crawford 
4688b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4689b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4690b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4691a0f08674SEwan Crawford 
4692a0f08674SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
469380af0b9eSLuke Drummond     bool success = false;
4694b9c1b51eSKate Stone     const uint32_t id =
469580af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
469680af0b9eSLuke Drummond     if (!success) {
4697b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4698b9c1b51eSKate Stone                                    id_cstr);
4699a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4700a0f08674SEwan Crawford       return false;
4701a0f08674SEwan Crawford     }
4702a0f08674SEwan Crawford 
4703a0f08674SEwan Crawford     Stream *output_strm = nullptr;
4704a0f08674SEwan Crawford     StreamFile outfile_stream;
4705b9c1b51eSKate Stone     const FileSpec &outfile_spec =
4706b9c1b51eSKate Stone         m_options.m_outfile; // Dump allocation to file instead
4707b9c1b51eSKate Stone     if (outfile_spec) {
4708a0f08674SEwan Crawford       // Open output file
470950bc1ed2SJonas Devlieghere       std::string path = outfile_spec.GetPath();
471050bc1ed2SJonas Devlieghere       auto error = FileSystem::Instance().Open(
471150bc1ed2SJonas Devlieghere           outfile_stream.GetFile(), outfile_spec,
471250bc1ed2SJonas Devlieghere           File::eOpenOptionWrite | File::eOpenOptionCanCreate);
471350bc1ed2SJonas Devlieghere       if (error.Success()) {
4714a0f08674SEwan Crawford         output_strm = &outfile_stream;
471550bc1ed2SJonas Devlieghere         result.GetOutputStream().Printf("Results written to '%s'",
471650bc1ed2SJonas Devlieghere                                         path.c_str());
4717a0f08674SEwan Crawford         result.GetOutputStream().EOL();
4718b9c1b51eSKate Stone       } else {
471950bc1ed2SJonas Devlieghere         result.AppendErrorWithFormat("Couldn't open file '%s'", path.c_str());
4720a0f08674SEwan Crawford         result.SetStatus(eReturnStatusFailed);
4721a0f08674SEwan Crawford         return false;
4722a0f08674SEwan Crawford       }
4723b9c1b51eSKate Stone     } else
4724a0f08674SEwan Crawford       output_strm = &result.GetOutputStream();
4725a0f08674SEwan Crawford 
4726a0f08674SEwan Crawford     assert(output_strm != nullptr);
472780af0b9eSLuke Drummond     bool dumped =
4728b9c1b51eSKate Stone         runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4729a0f08674SEwan Crawford 
473080af0b9eSLuke Drummond     if (dumped)
4731a0f08674SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4732a0f08674SEwan Crawford     else
4733a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4734a0f08674SEwan Crawford 
4735a0f08674SEwan Crawford     return true;
4736a0f08674SEwan Crawford   }
4737a0f08674SEwan Crawford 
4738a0f08674SEwan Crawford private:
4739a0f08674SEwan Crawford   CommandOptions m_options;
4740a0f08674SEwan Crawford };
4741a0f08674SEwan Crawford 
47428fe53c49STatyana Krasnukha static constexpr OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
47431f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
47448fe53c49STatyana Krasnukha      {}, 0, eArgTypeIndex,
47451f0f5b5bSZachary Turner      "Only show details of a single allocation with specified id."}};
4746a0f08674SEwan Crawford 
4747b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationList
4748b9c1b51eSKate Stone     : public CommandObjectParsed {
474915f2bd95SEwan Crawford public:
4750b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationList(
4751b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4752b9c1b51eSKate Stone       : CommandObjectParsed(
4753b9c1b51eSKate Stone             interpreter, "renderscript allocation list",
4754b9c1b51eSKate Stone             "List renderscript allocations and their information.",
4755b9c1b51eSKate Stone             "renderscript allocation list",
4756b3f7f69dSAidan Dodds             eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4757b9c1b51eSKate Stone         m_options() {}
475815f2bd95SEwan Crawford 
4759222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4760222b937cSEugene Zelenko 
4761b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
476215f2bd95SEwan Crawford 
4763b9c1b51eSKate Stone   class CommandOptions : public Options {
476415f2bd95SEwan Crawford   public:
4765e1cfbc79STodd Fiala     CommandOptions() : Options(), m_id(0) {}
476615f2bd95SEwan Crawford 
4767222b937cSEugene Zelenko     ~CommandOptions() override = default;
476815f2bd95SEwan Crawford 
476997206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4770b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
477197206d57SZachary Turner       Status err;
477215f2bd95SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
477315f2bd95SEwan Crawford 
4774b9c1b51eSKate Stone       switch (short_option) {
4775b649b005SEwan Crawford       case 'i':
4776fe11483bSZachary Turner         if (option_arg.getAsInteger(0, m_id))
477780af0b9eSLuke Drummond           err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4778b9c1b51eSKate Stone                                        short_option);
477915f2bd95SEwan Crawford         break;
478080af0b9eSLuke Drummond       default:
478180af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
478280af0b9eSLuke Drummond         break;
478315f2bd95SEwan Crawford       }
478480af0b9eSLuke Drummond       return err;
478515f2bd95SEwan Crawford     }
478615f2bd95SEwan Crawford 
4787b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
478815f2bd95SEwan Crawford 
47891f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
479070602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
47911f0f5b5bSZachary Turner     }
479215f2bd95SEwan Crawford 
4793b649b005SEwan Crawford     uint32_t m_id;
479415f2bd95SEwan Crawford   };
479515f2bd95SEwan Crawford 
4796b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4797b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4798b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4799b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4800b9c1b51eSKate Stone     runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4801b9c1b51eSKate Stone                              m_options.m_id);
480215f2bd95SEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
480315f2bd95SEwan Crawford     return true;
480415f2bd95SEwan Crawford   }
480515f2bd95SEwan Crawford 
480615f2bd95SEwan Crawford private:
480715f2bd95SEwan Crawford   CommandOptions m_options;
480815f2bd95SEwan Crawford };
480915f2bd95SEwan Crawford 
4810b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationLoad
4811b9c1b51eSKate Stone     : public CommandObjectParsed {
481255232f09SEwan Crawford public:
4813b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationLoad(
4814b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4815b3f7f69dSAidan Dodds       : CommandObjectParsed(
4816b9c1b51eSKate Stone             interpreter, "renderscript allocation load",
4817b9c1b51eSKate Stone             "Loads renderscript allocation contents from a file.",
4818b9c1b51eSKate Stone             "renderscript allocation load <ID> <filename>",
4819b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
482055232f09SEwan Crawford 
4821222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
482255232f09SEwan Crawford 
4823b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
482455232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4825b9c1b51eSKate Stone     if (argc != 2) {
4826b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4827b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4828b3f7f69dSAidan Dodds           m_cmd_name.c_str());
482955232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
483055232f09SEwan Crawford       return false;
483155232f09SEwan Crawford     }
483255232f09SEwan Crawford 
4833b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4834b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4835b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
483655232f09SEwan Crawford 
483755232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
483880af0b9eSLuke Drummond     bool success = false;
4839b9c1b51eSKate Stone     const uint32_t id =
484080af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
484180af0b9eSLuke Drummond     if (!success) {
4842b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4843b9c1b51eSKate Stone                                    id_cstr);
484455232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
484555232f09SEwan Crawford       return false;
484655232f09SEwan Crawford     }
484755232f09SEwan Crawford 
484880af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
484980af0b9eSLuke Drummond     bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
485080af0b9eSLuke Drummond                                           m_exe_ctx.GetFramePtr());
485155232f09SEwan Crawford 
485280af0b9eSLuke Drummond     if (loaded)
485355232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
485455232f09SEwan Crawford     else
485555232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
485655232f09SEwan Crawford 
485755232f09SEwan Crawford     return true;
485855232f09SEwan Crawford   }
485955232f09SEwan Crawford };
486055232f09SEwan Crawford 
4861b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationSave
4862b9c1b51eSKate Stone     : public CommandObjectParsed {
486355232f09SEwan Crawford public:
4864b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationSave(
4865b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4866b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript allocation save",
4867b9c1b51eSKate Stone                             "Write renderscript allocation contents to a file.",
4868b9c1b51eSKate Stone                             "renderscript allocation save <ID> <filename>",
4869b9c1b51eSKate Stone                             eCommandRequiresProcess |
4870b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
487155232f09SEwan Crawford 
4872222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
487355232f09SEwan Crawford 
4874b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
487555232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4876b9c1b51eSKate Stone     if (argc != 2) {
4877b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4878b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4879b3f7f69dSAidan Dodds           m_cmd_name.c_str());
488055232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
488155232f09SEwan Crawford       return false;
488255232f09SEwan Crawford     }
488355232f09SEwan Crawford 
4884b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4885b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4886b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
488755232f09SEwan Crawford 
488855232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
488980af0b9eSLuke Drummond     bool success = false;
4890b9c1b51eSKate Stone     const uint32_t id =
489180af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
489280af0b9eSLuke Drummond     if (!success) {
4893b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4894b9c1b51eSKate Stone                                    id_cstr);
489555232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
489655232f09SEwan Crawford       return false;
489755232f09SEwan Crawford     }
489855232f09SEwan Crawford 
489980af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
490080af0b9eSLuke Drummond     bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
490180af0b9eSLuke Drummond                                          m_exe_ctx.GetFramePtr());
490255232f09SEwan Crawford 
490380af0b9eSLuke Drummond     if (saved)
490455232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
490555232f09SEwan Crawford     else
490655232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
490755232f09SEwan Crawford 
490855232f09SEwan Crawford     return true;
490955232f09SEwan Crawford   }
491055232f09SEwan Crawford };
491155232f09SEwan Crawford 
4912b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationRefresh
4913b9c1b51eSKate Stone     : public CommandObjectParsed {
49140d2bfcfbSEwan Crawford public:
4915b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationRefresh(
4916b9c1b51eSKate Stone       CommandInterpreter &interpreter)
49170d2bfcfbSEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4918b9c1b51eSKate Stone                             "Recomputes the details of all allocations.",
4919b9c1b51eSKate Stone                             "renderscript allocation refresh",
4920b9c1b51eSKate Stone                             eCommandRequiresProcess |
4921b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
49220d2bfcfbSEwan Crawford 
49230d2bfcfbSEwan Crawford   ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
49240d2bfcfbSEwan Crawford 
4925b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
49260d2bfcfbSEwan Crawford     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4927b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4928b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
49290d2bfcfbSEwan Crawford 
4930b9c1b51eSKate Stone     bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4931b9c1b51eSKate Stone                                                     m_exe_ctx.GetFramePtr());
49320d2bfcfbSEwan Crawford 
4933b9c1b51eSKate Stone     if (success) {
49340d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
49350d2bfcfbSEwan Crawford       return true;
4936b9c1b51eSKate Stone     } else {
49370d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusFailed);
49380d2bfcfbSEwan Crawford       return false;
49390d2bfcfbSEwan Crawford     }
49400d2bfcfbSEwan Crawford   }
49410d2bfcfbSEwan Crawford };
49420d2bfcfbSEwan Crawford 
4943b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocation
4944b9c1b51eSKate Stone     : public CommandObjectMultiword {
494515f2bd95SEwan Crawford public:
494615f2bd95SEwan Crawford   CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4947b9c1b51eSKate Stone       : CommandObjectMultiword(
4948b9c1b51eSKate Stone             interpreter, "renderscript allocation",
4949b9c1b51eSKate Stone             "Commands that deal with RenderScript allocations.", nullptr) {
4950b9c1b51eSKate Stone     LoadSubCommand(
4951b9c1b51eSKate Stone         "list",
4952b9c1b51eSKate Stone         CommandObjectSP(
4953b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4954b9c1b51eSKate Stone     LoadSubCommand(
4955b9c1b51eSKate Stone         "dump",
4956b9c1b51eSKate Stone         CommandObjectSP(
4957b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4958b9c1b51eSKate Stone     LoadSubCommand(
4959b9c1b51eSKate Stone         "save",
4960b9c1b51eSKate Stone         CommandObjectSP(
4961b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4962b9c1b51eSKate Stone     LoadSubCommand(
4963b9c1b51eSKate Stone         "load",
4964b9c1b51eSKate Stone         CommandObjectSP(
4965b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4966b9c1b51eSKate Stone     LoadSubCommand(
4967b9c1b51eSKate Stone         "refresh",
4968b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4969b9c1b51eSKate Stone             interpreter)));
497015f2bd95SEwan Crawford   }
497115f2bd95SEwan Crawford 
4972222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocation() override = default;
497315f2bd95SEwan Crawford };
497415f2bd95SEwan Crawford 
4975b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
49764640cde1SColin Riley public:
49774640cde1SColin Riley   CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4978b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript status",
4979b9c1b51eSKate Stone                             "Displays current RenderScript runtime status.",
4980b9c1b51eSKate Stone                             "renderscript status",
4981b9c1b51eSKate Stone                             eCommandRequiresProcess |
4982b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
49834640cde1SColin Riley 
4984222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeStatus() override = default;
49854640cde1SColin Riley 
4986b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
49874640cde1SColin Riley     RenderScriptRuntime *runtime =
4988b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4989b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
499097206d57SZachary Turner     runtime->DumpStatus(result.GetOutputStream());
49914640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
49924640cde1SColin Riley     return true;
49934640cde1SColin Riley   }
49944640cde1SColin Riley };
49954640cde1SColin Riley 
4996b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReduction
4997b3bbcb12SLuke Drummond     : public CommandObjectMultiword {
4998b3bbcb12SLuke Drummond public:
4999b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
5000b3bbcb12SLuke Drummond       : CommandObjectMultiword(interpreter, "renderscript reduction",
5001b3bbcb12SLuke Drummond                                "Commands that handle general reduction kernels",
5002b3bbcb12SLuke Drummond                                nullptr) {
5003b3bbcb12SLuke Drummond     LoadSubCommand(
5004b3bbcb12SLuke Drummond         "breakpoint",
5005b3bbcb12SLuke Drummond         CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
5006b3bbcb12SLuke Drummond             interpreter)));
5007b3bbcb12SLuke Drummond   }
5008b3bbcb12SLuke Drummond   ~CommandObjectRenderScriptRuntimeReduction() override = default;
5009b3bbcb12SLuke Drummond };
5010b3bbcb12SLuke Drummond 
5011b9c1b51eSKate Stone class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
50125ec532a9SColin Riley public:
50135ec532a9SColin Riley   CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
5014b9c1b51eSKate Stone       : CommandObjectMultiword(
5015b9c1b51eSKate Stone             interpreter, "renderscript",
5016b9c1b51eSKate Stone             "Commands for operating on the RenderScript runtime.",
5017b9c1b51eSKate Stone             "renderscript <subcommand> [<subcommand-options>]") {
5018b9c1b51eSKate Stone     LoadSubCommand(
5019b9c1b51eSKate Stone         "module", CommandObjectSP(
5020b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeModule(interpreter)));
5021b9c1b51eSKate Stone     LoadSubCommand(
5022b9c1b51eSKate Stone         "status", CommandObjectSP(
5023b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeStatus(interpreter)));
5024b9c1b51eSKate Stone     LoadSubCommand(
5025b9c1b51eSKate Stone         "kernel", CommandObjectSP(
5026b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeKernel(interpreter)));
5027b9c1b51eSKate Stone     LoadSubCommand("context",
5028b9c1b51eSKate Stone                    CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
5029b9c1b51eSKate Stone                        interpreter)));
5030b9c1b51eSKate Stone     LoadSubCommand(
5031b9c1b51eSKate Stone         "allocation",
5032b9c1b51eSKate Stone         CommandObjectSP(
5033b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
503421fed052SAidan Dodds     LoadSubCommand("scriptgroup",
503521fed052SAidan Dodds                    NewCommandObjectRenderScriptScriptGroup(interpreter));
5036b3bbcb12SLuke Drummond     LoadSubCommand(
5037b3bbcb12SLuke Drummond         "reduction",
5038b3bbcb12SLuke Drummond         CommandObjectSP(
5039b3bbcb12SLuke Drummond             new CommandObjectRenderScriptRuntimeReduction(interpreter)));
50405ec532a9SColin Riley   }
50415ec532a9SColin Riley 
5042222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntime() override = default;
50435ec532a9SColin Riley };
5044ef20b08fSColin Riley 
5045b9c1b51eSKate Stone void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
5046ef20b08fSColin Riley 
5047ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
5048b9c1b51eSKate Stone     : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
5049b9c1b51eSKate Stone       m_debuggerPresentFlagged(false), m_breakAllKernels(false),
5050b9c1b51eSKate Stone       m_ir_passes(nullptr) {
50514640cde1SColin Riley   ModulesDidLoad(process->GetTarget().GetImages());
5052ef20b08fSColin Riley }
50534640cde1SColin Riley 
5054b9c1b51eSKate Stone lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
5055b9c1b51eSKate Stone     lldb_private::CommandInterpreter &interpreter) {
50560a66e2f1SEnrico Granata   return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
50574640cde1SColin Riley }
50584640cde1SColin Riley 
505978f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
5060