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 
41796ac80bSJonas Devlieghere #include "llvm/ADT/StringSwitch.h"
42796ac80bSJonas Devlieghere 
43796ac80bSJonas Devlieghere #include <memory>
44796ac80bSJonas 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 
51056f6f18SAlex Langford char RenderScriptRuntime::ID = 0;
52056f6f18SAlex Langford 
53b9c1b51eSKate Stone namespace {
5478f339d1SEwan Crawford 
5578f339d1SEwan Crawford // The empirical_type adds a basic level of validation to arbitrary data
5680af0b9eSLuke Drummond // allowing us to track if data has been discovered and stored or not. An
5780af0b9eSLuke Drummond // empirical_type will be marked as valid only if it has been explicitly
58b9c1b51eSKate Stone // assigned to.
59b9c1b51eSKate Stone template <typename type_t> class empirical_type {
6078f339d1SEwan Crawford public:
6178f339d1SEwan Crawford   // Ctor. Contents is invalid when constructed.
62b3f7f69dSAidan Dodds   empirical_type() : valid(false) {}
6378f339d1SEwan Crawford 
6478f339d1SEwan Crawford   // Return true and copy contents to out if valid, else return false.
65b9c1b51eSKate Stone   bool get(type_t &out) const {
6678f339d1SEwan Crawford     if (valid)
6778f339d1SEwan Crawford       out = data;
6878f339d1SEwan Crawford     return valid;
6978f339d1SEwan Crawford   }
7078f339d1SEwan Crawford 
7178f339d1SEwan Crawford   // Return a pointer to the contents or nullptr if it was not valid.
72b9c1b51eSKate Stone   const type_t *get() const { return valid ? &data : nullptr; }
7378f339d1SEwan Crawford 
7478f339d1SEwan Crawford   // Assign data explicitly.
75b9c1b51eSKate Stone   void set(const type_t in) {
7678f339d1SEwan Crawford     data = in;
7778f339d1SEwan Crawford     valid = true;
7878f339d1SEwan Crawford   }
7978f339d1SEwan Crawford 
8078f339d1SEwan Crawford   // Mark contents as invalid.
81b9c1b51eSKate Stone   void invalidate() { valid = false; }
8278f339d1SEwan Crawford 
8378f339d1SEwan Crawford   // Returns true if this type contains valid data.
84b9c1b51eSKate Stone   bool isValid() const { return valid; }
8578f339d1SEwan Crawford 
8678f339d1SEwan Crawford   // Assignment operator.
87b9c1b51eSKate Stone   empirical_type<type_t> &operator=(const type_t in) {
8878f339d1SEwan Crawford     set(in);
8978f339d1SEwan Crawford     return *this;
9078f339d1SEwan Crawford   }
9178f339d1SEwan Crawford 
9278f339d1SEwan Crawford   // Dereference operator returns contents.
9378f339d1SEwan Crawford   // Warning: Will assert if not valid so use only when you know data is valid.
94b9c1b51eSKate Stone   const type_t &operator*() const {
9578f339d1SEwan Crawford     assert(valid);
9678f339d1SEwan Crawford     return data;
9778f339d1SEwan Crawford   }
9878f339d1SEwan Crawford 
9978f339d1SEwan Crawford protected:
10078f339d1SEwan Crawford   bool valid;
10178f339d1SEwan Crawford   type_t data;
10278f339d1SEwan Crawford };
10378f339d1SEwan Crawford 
104b9c1b51eSKate Stone // ArgItem is used by the GetArgs() function when reading function arguments
105b9c1b51eSKate Stone // from the target.
106b9c1b51eSKate Stone struct ArgItem {
107b9c1b51eSKate Stone   enum { ePointer, eInt32, eInt64, eLong, eBool } type;
108f4786785SAidan Dodds 
109f4786785SAidan Dodds   uint64_t value;
110f4786785SAidan Dodds 
111f4786785SAidan Dodds   explicit operator uint64_t() const { return value; }
112f4786785SAidan Dodds };
113f4786785SAidan Dodds 
114b9c1b51eSKate Stone // Context structure to be passed into GetArgsXXX(), argument reading functions
115b9c1b51eSKate Stone // below.
116b9c1b51eSKate Stone struct GetArgsCtx {
117f4786785SAidan Dodds   RegisterContext *reg_ctx;
118f4786785SAidan Dodds   Process *process;
119f4786785SAidan Dodds };
120f4786785SAidan Dodds 
121b9c1b51eSKate Stone bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
122f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
123f4786785SAidan Dodds 
12497206d57SZachary Turner   Status err;
12567dc3e15SAidan Dodds 
126f4786785SAidan Dodds   // get the current stack pointer
127f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
128f4786785SAidan Dodds 
129b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
130f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
131f4786785SAidan Dodds     // advance up the stack by one argument
132f4786785SAidan Dodds     sp += sizeof(uint32_t);
133f4786785SAidan Dodds     // get the argument type size
134f4786785SAidan Dodds     size_t arg_size = sizeof(uint32_t);
135f4786785SAidan Dodds     // read the argument from memory
136f4786785SAidan Dodds     arg.value = 0;
13797206d57SZachary Turner     Status err;
138b9c1b51eSKate Stone     size_t read =
13980af0b9eSLuke Drummond         ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
14080af0b9eSLuke Drummond     if (read != arg_size || !err.Success()) {
141*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 " '%s'",
14280af0b9eSLuke Drummond                 __FUNCTION__, uint64_t(i), err.AsCString());
143f4786785SAidan Dodds       return false;
144f4786785SAidan Dodds     }
145f4786785SAidan Dodds   }
146f4786785SAidan Dodds   return true;
147f4786785SAidan Dodds }
148f4786785SAidan Dodds 
149b9c1b51eSKate Stone bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
150f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
151f4786785SAidan Dodds 
152f4786785SAidan Dodds   // number of arguments passed in registers
15380af0b9eSLuke Drummond   static const uint32_t args_in_reg = 6;
154f4786785SAidan Dodds   // register passing order
15580af0b9eSLuke Drummond   static const std::array<const char *, args_in_reg> reg_names{
156b9c1b51eSKate Stone       {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
157f4786785SAidan Dodds   // argument type to size mapping
1581ee07253SSaleem Abdulrasool   static const std::array<size_t, 5> arg_size{{
159f4786785SAidan Dodds       8, // ePointer,
160f4786785SAidan Dodds       4, // eInt32,
161f4786785SAidan Dodds       8, // eInt64,
162f4786785SAidan Dodds       8, // eLong,
163f4786785SAidan Dodds       4, // eBool,
1641ee07253SSaleem Abdulrasool   }};
165f4786785SAidan Dodds 
16697206d57SZachary Turner   Status err;
16717e07c0aSAidan Dodds 
168f4786785SAidan Dodds   // get the current stack pointer
169f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
170f4786785SAidan Dodds   // step over the return address
171f4786785SAidan Dodds   sp += sizeof(uint64_t);
172f4786785SAidan Dodds 
173f4786785SAidan Dodds   // check the stack alignment was correct (16 byte aligned)
174b9c1b51eSKate Stone   if ((sp & 0xf) != 0x0) {
175*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%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) {
214*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
21580af0b9eSLuke Drummond                 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
216f4786785SAidan Dodds       return false;
217f4786785SAidan Dodds     }
218f4786785SAidan Dodds   }
219f4786785SAidan Dodds   return true;
220f4786785SAidan Dodds }
221f4786785SAidan Dodds 
222b9c1b51eSKate Stone bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
223f4786785SAidan Dodds   // number of arguments passed in registers
22480af0b9eSLuke Drummond   static const uint32_t args_in_reg = 4;
225f4786785SAidan Dodds 
226f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
227f4786785SAidan Dodds 
22897206d57SZachary Turner   Status err;
22917e07c0aSAidan Dodds 
230f4786785SAidan Dodds   // get the current stack pointer
231f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
232f4786785SAidan Dodds 
233b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
234f4786785SAidan Dodds     bool success = false;
235f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
236f4786785SAidan Dodds     // arguments passed in registers
23780af0b9eSLuke Drummond     if (i < args_in_reg) {
23880af0b9eSLuke Drummond       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
23980af0b9eSLuke Drummond       RegisterValue reg_val;
24080af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
24180af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt32(0, &success);
242f4786785SAidan Dodds     }
243f4786785SAidan Dodds     // arguments passed on the stack
244b9c1b51eSKate Stone     else {
245f4786785SAidan Dodds       // get the argument type size
246f4786785SAidan Dodds       const size_t arg_size = sizeof(uint32_t);
247f4786785SAidan Dodds       // clear all 64bits
248f4786785SAidan Dodds       arg.value = 0;
249f4786785SAidan Dodds       // read this argument from memory
250b9c1b51eSKate Stone       size_t bytes_read =
25180af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
25280af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
253f4786785SAidan Dodds       // advance the stack pointer
254f4786785SAidan Dodds       sp += sizeof(uint32_t);
255f4786785SAidan Dodds     }
256f4786785SAidan Dodds     // fail if we couldn't read this argument
257b9c1b51eSKate Stone     if (!success) {
258*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
25980af0b9eSLuke Drummond                 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
260f4786785SAidan Dodds       return false;
261f4786785SAidan Dodds     }
262f4786785SAidan Dodds   }
263f4786785SAidan Dodds   return true;
264f4786785SAidan Dodds }
265f4786785SAidan Dodds 
266b9c1b51eSKate Stone bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
267f4786785SAidan Dodds   // number of arguments passed in registers
26880af0b9eSLuke Drummond   static const uint32_t args_in_reg = 8;
269f4786785SAidan Dodds 
270f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
271f4786785SAidan Dodds 
272b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
273f4786785SAidan Dodds     bool success = false;
274f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
275f4786785SAidan Dodds     // arguments passed in registers
27680af0b9eSLuke Drummond     if (i < args_in_reg) {
27780af0b9eSLuke Drummond       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
27880af0b9eSLuke Drummond       RegisterValue reg_val;
27980af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
28080af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
281f4786785SAidan Dodds     }
282f4786785SAidan Dodds     // arguments passed on the stack
283b9c1b51eSKate Stone     else {
284*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - reading arguments spilled to stack not implemented",
285b9c1b51eSKate Stone                 __FUNCTION__);
286f4786785SAidan Dodds     }
287f4786785SAidan Dodds     // fail if we couldn't read this argument
288b9c1b51eSKate Stone     if (!success) {
289*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - error reading argument: %" PRIu64, __FUNCTION__,
290f4786785SAidan Dodds                 uint64_t(i));
291f4786785SAidan Dodds       return false;
292f4786785SAidan Dodds     }
293f4786785SAidan Dodds   }
294f4786785SAidan Dodds   return true;
295f4786785SAidan Dodds }
296f4786785SAidan Dodds 
297b9c1b51eSKate Stone bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
298f4786785SAidan Dodds   // number of arguments passed in registers
29980af0b9eSLuke Drummond   static const uint32_t args_in_reg = 4;
300f4786785SAidan Dodds   // register file offset to first argument
30180af0b9eSLuke Drummond   static const uint32_t reg_offset = 4;
302f4786785SAidan Dodds 
303f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
304f4786785SAidan Dodds 
30597206d57SZachary Turner   Status err;
30617e07c0aSAidan Dodds 
30705097246SAdrian Prantl   // find offset to arguments on the stack (+16 to skip over a0-a3 shadow
30805097246SAdrian Prantl   // space)
30917e07c0aSAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP() + 16;
31017e07c0aSAidan Dodds 
311b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
312f4786785SAidan Dodds     bool success = false;
313f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
314f4786785SAidan Dodds     // arguments passed in registers
31580af0b9eSLuke Drummond     if (i < args_in_reg) {
31680af0b9eSLuke Drummond       const RegisterInfo *reg =
31780af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
31880af0b9eSLuke Drummond       RegisterValue reg_val;
31980af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
32080af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
321f4786785SAidan Dodds     }
322f4786785SAidan Dodds     // arguments passed on the stack
323b9c1b51eSKate Stone     else {
3246dd4b579SAidan Dodds       const size_t arg_size = sizeof(uint32_t);
3256dd4b579SAidan Dodds       arg.value = 0;
326b9c1b51eSKate Stone       size_t bytes_read =
32780af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
32880af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
32967dc3e15SAidan Dodds       // advance the stack pointer
33067dc3e15SAidan Dodds       sp += arg_size;
331f4786785SAidan Dodds     }
332f4786785SAidan Dodds     // fail if we couldn't read this argument
333b9c1b51eSKate Stone     if (!success) {
334*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
33580af0b9eSLuke Drummond                 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
336f4786785SAidan Dodds       return false;
337f4786785SAidan Dodds     }
338f4786785SAidan Dodds   }
339f4786785SAidan Dodds   return true;
340f4786785SAidan Dodds }
341f4786785SAidan Dodds 
342b9c1b51eSKate Stone bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
343f4786785SAidan Dodds   // number of arguments passed in registers
34480af0b9eSLuke Drummond   static const uint32_t args_in_reg = 8;
345f4786785SAidan Dodds   // register file offset to first argument
34680af0b9eSLuke Drummond   static const uint32_t reg_offset = 4;
347f4786785SAidan Dodds 
348f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
349f4786785SAidan Dodds 
35097206d57SZachary Turner   Status err;
35117e07c0aSAidan Dodds 
352f4786785SAidan Dodds   // get the current stack pointer
353f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
354f4786785SAidan Dodds 
355b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
356f4786785SAidan Dodds     bool success = false;
357f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
358f4786785SAidan Dodds     // arguments passed in registers
35980af0b9eSLuke Drummond     if (i < args_in_reg) {
36080af0b9eSLuke Drummond       const RegisterInfo *reg =
36180af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
36280af0b9eSLuke Drummond       RegisterValue reg_val;
36380af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
36480af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
365f4786785SAidan Dodds     }
366f4786785SAidan Dodds     // arguments passed on the stack
367b9c1b51eSKate Stone     else {
368f4786785SAidan Dodds       // get the argument type size
369f4786785SAidan Dodds       const size_t arg_size = sizeof(uint64_t);
370f4786785SAidan Dodds       // clear all 64bits
371f4786785SAidan Dodds       arg.value = 0;
372f4786785SAidan Dodds       // read this argument from memory
373b9c1b51eSKate Stone       size_t bytes_read =
37480af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
37580af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
376f4786785SAidan Dodds       // advance the stack pointer
377f4786785SAidan Dodds       sp += arg_size;
378f4786785SAidan Dodds     }
379f4786785SAidan Dodds     // fail if we couldn't read this argument
380b9c1b51eSKate Stone     if (!success) {
381*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
38280af0b9eSLuke Drummond                 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
383f4786785SAidan Dodds       return false;
384f4786785SAidan Dodds     }
385f4786785SAidan Dodds   }
386f4786785SAidan Dodds   return true;
387f4786785SAidan Dodds }
388f4786785SAidan Dodds 
38980af0b9eSLuke Drummond bool GetArgs(ExecutionContext &exe_ctx, ArgItem *arg_list, size_t num_args) {
390f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
391f4786785SAidan Dodds 
392f4786785SAidan Dodds   // verify that we have a target
39380af0b9eSLuke Drummond   if (!exe_ctx.GetTargetPtr()) {
394*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - invalid target", __FUNCTION__);
395f4786785SAidan Dodds     return false;
396f4786785SAidan Dodds   }
397f4786785SAidan Dodds 
39880af0b9eSLuke Drummond   GetArgsCtx ctx = {exe_ctx.GetRegisterContext(), exe_ctx.GetProcessPtr()};
399f4786785SAidan Dodds   assert(ctx.reg_ctx && ctx.process);
400f4786785SAidan Dodds 
401f4786785SAidan Dodds   // dispatch based on architecture
40280af0b9eSLuke Drummond   switch (exe_ctx.GetTargetPtr()->GetArchitecture().GetMachine()) {
403f4786785SAidan Dodds   case llvm::Triple::ArchType::x86:
404f4786785SAidan Dodds     return GetArgsX86(ctx, arg_list, num_args);
405f4786785SAidan Dodds 
406f4786785SAidan Dodds   case llvm::Triple::ArchType::x86_64:
407f4786785SAidan Dodds     return GetArgsX86_64(ctx, arg_list, num_args);
408f4786785SAidan Dodds 
409f4786785SAidan Dodds   case llvm::Triple::ArchType::arm:
410f4786785SAidan Dodds     return GetArgsArm(ctx, arg_list, num_args);
411f4786785SAidan Dodds 
412f4786785SAidan Dodds   case llvm::Triple::ArchType::aarch64:
413f4786785SAidan Dodds     return GetArgsAarch64(ctx, arg_list, num_args);
414f4786785SAidan Dodds 
415f4786785SAidan Dodds   case llvm::Triple::ArchType::mipsel:
416f4786785SAidan Dodds     return GetArgsMipsel(ctx, arg_list, num_args);
417f4786785SAidan Dodds 
418f4786785SAidan Dodds   case llvm::Triple::ArchType::mips64el:
419f4786785SAidan Dodds     return GetArgsMips64el(ctx, arg_list, num_args);
420f4786785SAidan Dodds 
421f4786785SAidan Dodds   default:
422f4786785SAidan Dodds     // unsupported architecture
423b9c1b51eSKate Stone     if (log) {
424*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - architecture not supported: '%s'", __FUNCTION__,
42580af0b9eSLuke Drummond                 exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
426f4786785SAidan Dodds     }
427f4786785SAidan Dodds     return false;
428f4786785SAidan Dodds   }
429f4786785SAidan Dodds }
43000f56eebSLuke Drummond 
431b3bbcb12SLuke Drummond bool IsRenderScriptScriptModule(ModuleSP module) {
432b3bbcb12SLuke Drummond   if (!module)
433b3bbcb12SLuke Drummond     return false;
434b3bbcb12SLuke Drummond   return module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
435b3bbcb12SLuke Drummond                                                 eSymbolTypeData) != nullptr;
436b3bbcb12SLuke Drummond }
437b3bbcb12SLuke Drummond 
43800f56eebSLuke Drummond bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
43905097246SAdrian Prantl   // takes an argument of the form 'num[,num][,num]'. Where 'coord_s' is a
44005097246SAdrian Prantl   // comma separated 1,2 or 3-dimensional coordinate with the whitespace
44105097246SAdrian Prantl   // trimmed. Missing coordinates are defaulted to zero. If parsing of any
44205097246SAdrian Prantl   // elements fails the contents of &coord are undefined and `false` is
44305097246SAdrian Prantl   // returned, `true` otherwise
44400f56eebSLuke Drummond 
44500f56eebSLuke Drummond   RegularExpression regex;
44600f56eebSLuke Drummond   RegularExpression::Match regex_match(3);
44700f56eebSLuke Drummond 
44800f56eebSLuke Drummond   bool matched = false;
44900f56eebSLuke Drummond   if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+),([0-9]+)$")) &&
45000f56eebSLuke Drummond       regex.Execute(coord_s, &regex_match))
45100f56eebSLuke Drummond     matched = true;
45200f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+)$")) &&
45300f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
45400f56eebSLuke Drummond     matched = true;
45500f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([0-9]+)$")) &&
45600f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
45700f56eebSLuke Drummond     matched = true;
45800f56eebSLuke Drummond 
45900f56eebSLuke Drummond   if (!matched)
46000f56eebSLuke Drummond     return false;
46100f56eebSLuke Drummond 
46200f56eebSLuke Drummond   auto get_index = [&](int idx, uint32_t &i) -> bool {
46300f56eebSLuke Drummond     std::string group;
46400f56eebSLuke Drummond     errno = 0;
46500f56eebSLuke Drummond     if (regex_match.GetMatchAtIndex(coord_s.str().c_str(), idx + 1, group))
46600f56eebSLuke Drummond       return !llvm::StringRef(group).getAsInteger<uint32_t>(10, i);
46700f56eebSLuke Drummond     return true;
46800f56eebSLuke Drummond   };
46900f56eebSLuke Drummond 
47000f56eebSLuke Drummond   return get_index(0, coord.x) && get_index(1, coord.y) &&
47100f56eebSLuke Drummond          get_index(2, coord.z);
47200f56eebSLuke Drummond }
47321fed052SAidan Dodds 
47421fed052SAidan Dodds bool SkipPrologue(lldb::ModuleSP &module, Address &addr) {
47521fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
47621fed052SAidan Dodds   SymbolContext sc;
47721fed052SAidan Dodds   uint32_t resolved_flags =
47821fed052SAidan Dodds       module->ResolveSymbolContextForAddress(addr, eSymbolContextFunction, sc);
47921fed052SAidan Dodds   if (resolved_flags & eSymbolContextFunction) {
48021fed052SAidan Dodds     if (sc.function) {
48121fed052SAidan Dodds       const uint32_t offset = sc.function->GetPrologueByteSize();
48221fed052SAidan Dodds       ConstString name = sc.GetFunctionName();
48321fed052SAidan Dodds       if (offset)
48421fed052SAidan Dodds         addr.Slide(offset);
485*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s: Prologue offset for %s is %" PRIu32, __FUNCTION__,
48621fed052SAidan Dodds                 name.AsCString(), offset);
48721fed052SAidan Dodds     }
48821fed052SAidan Dodds     return true;
48921fed052SAidan Dodds   } else
49021fed052SAidan Dodds     return false;
49121fed052SAidan Dodds }
492222b937cSEugene Zelenko } // anonymous namespace
49378f339d1SEwan Crawford 
494b9c1b51eSKate Stone // The ScriptDetails class collects data associated with a single script
495b9c1b51eSKate Stone // instance.
496b9c1b51eSKate Stone struct RenderScriptRuntime::ScriptDetails {
497222b937cSEugene Zelenko   ~ScriptDetails() = default;
49878f339d1SEwan Crawford 
499b9c1b51eSKate Stone   enum ScriptType { eScript, eScriptC };
50078f339d1SEwan Crawford 
50178f339d1SEwan Crawford   // The derived type of the script.
50278f339d1SEwan Crawford   empirical_type<ScriptType> type;
50378f339d1SEwan Crawford   // The name of the original source file.
50480af0b9eSLuke Drummond   empirical_type<std::string> res_name;
50578f339d1SEwan Crawford   // Path to script .so file on the device.
50680af0b9eSLuke Drummond   empirical_type<std::string> shared_lib;
50778f339d1SEwan Crawford   // Directory where kernel objects are cached on device.
50880af0b9eSLuke Drummond   empirical_type<std::string> cache_dir;
50978f339d1SEwan Crawford   // Pointer to the context which owns this script.
51078f339d1SEwan Crawford   empirical_type<lldb::addr_t> context;
51178f339d1SEwan Crawford   // Pointer to the script object itself.
51278f339d1SEwan Crawford   empirical_type<lldb::addr_t> script;
51378f339d1SEwan Crawford };
51478f339d1SEwan Crawford 
51580af0b9eSLuke Drummond // This Element class represents the Element object in RS, defining the type
51680af0b9eSLuke Drummond // associated with an Allocation.
517b9c1b51eSKate Stone struct RenderScriptRuntime::Element {
51815f2bd95SEwan Crawford   // Taken from rsDefines.h
519b9c1b51eSKate Stone   enum DataKind {
52015f2bd95SEwan Crawford     RS_KIND_USER,
52115f2bd95SEwan Crawford     RS_KIND_PIXEL_L = 7,
52215f2bd95SEwan Crawford     RS_KIND_PIXEL_A,
52315f2bd95SEwan Crawford     RS_KIND_PIXEL_LA,
52415f2bd95SEwan Crawford     RS_KIND_PIXEL_RGB,
52515f2bd95SEwan Crawford     RS_KIND_PIXEL_RGBA,
52615f2bd95SEwan Crawford     RS_KIND_PIXEL_DEPTH,
52715f2bd95SEwan Crawford     RS_KIND_PIXEL_YUV,
52815f2bd95SEwan Crawford     RS_KIND_INVALID = 100
52915f2bd95SEwan Crawford   };
53078f339d1SEwan Crawford 
53115f2bd95SEwan Crawford   // Taken from rsDefines.h
532b9c1b51eSKate Stone   enum DataType {
53315f2bd95SEwan Crawford     RS_TYPE_NONE = 0,
53415f2bd95SEwan Crawford     RS_TYPE_FLOAT_16,
53515f2bd95SEwan Crawford     RS_TYPE_FLOAT_32,
53615f2bd95SEwan Crawford     RS_TYPE_FLOAT_64,
53715f2bd95SEwan Crawford     RS_TYPE_SIGNED_8,
53815f2bd95SEwan Crawford     RS_TYPE_SIGNED_16,
53915f2bd95SEwan Crawford     RS_TYPE_SIGNED_32,
54015f2bd95SEwan Crawford     RS_TYPE_SIGNED_64,
54115f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_8,
54215f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_16,
54315f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_32,
54415f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_64,
5452e920715SEwan Crawford     RS_TYPE_BOOLEAN,
5462e920715SEwan Crawford 
5472e920715SEwan Crawford     RS_TYPE_UNSIGNED_5_6_5,
5482e920715SEwan Crawford     RS_TYPE_UNSIGNED_5_5_5_1,
5492e920715SEwan Crawford     RS_TYPE_UNSIGNED_4_4_4_4,
5502e920715SEwan Crawford 
5512e920715SEwan Crawford     RS_TYPE_MATRIX_4X4,
5522e920715SEwan Crawford     RS_TYPE_MATRIX_3X3,
5532e920715SEwan Crawford     RS_TYPE_MATRIX_2X2,
5542e920715SEwan Crawford 
5552e920715SEwan Crawford     RS_TYPE_ELEMENT = 1000,
5562e920715SEwan Crawford     RS_TYPE_TYPE,
5572e920715SEwan Crawford     RS_TYPE_ALLOCATION,
5582e920715SEwan Crawford     RS_TYPE_SAMPLER,
5592e920715SEwan Crawford     RS_TYPE_SCRIPT,
5602e920715SEwan Crawford     RS_TYPE_MESH,
5612e920715SEwan Crawford     RS_TYPE_PROGRAM_FRAGMENT,
5622e920715SEwan Crawford     RS_TYPE_PROGRAM_VERTEX,
5632e920715SEwan Crawford     RS_TYPE_PROGRAM_RASTER,
5642e920715SEwan Crawford     RS_TYPE_PROGRAM_STORE,
5652e920715SEwan Crawford     RS_TYPE_FONT,
5662e920715SEwan Crawford 
5672e920715SEwan Crawford     RS_TYPE_INVALID = 10000
56878f339d1SEwan Crawford   };
56978f339d1SEwan Crawford 
5708b244e21SEwan Crawford   std::vector<Element> children; // Child Element fields for structs
571b9c1b51eSKate Stone   empirical_type<lldb::addr_t>
572b9c1b51eSKate Stone       element_ptr; // Pointer to the RS Element of the Type
573b9c1b51eSKate Stone   empirical_type<DataType>
574b9c1b51eSKate Stone       type; // Type of each data pointer stored by the allocation
575b9c1b51eSKate Stone   empirical_type<DataKind>
576b9c1b51eSKate Stone       type_kind; // Defines pixel type if Allocation is created from an image
577b9c1b51eSKate Stone   empirical_type<uint32_t>
578b9c1b51eSKate Stone       type_vec_size; // Vector size of each data point, e.g '4' for uchar4
5798b244e21SEwan Crawford   empirical_type<uint32_t> field_count; // Number of Subelements
5808b244e21SEwan Crawford   empirical_type<uint32_t> datum_size;  // Size of a single Element with padding
5818b244e21SEwan Crawford   empirical_type<uint32_t> padding;     // Number of padding bytes
582b9c1b51eSKate Stone   empirical_type<uint32_t>
5834ebdee0aSBruce Mitchener       array_size;        // Number of items in array, only needed for structs
5848b244e21SEwan Crawford   ConstString type_name; // Name of type, only needed for structs
5858b244e21SEwan Crawford 
5860e4c4821SAdrian Prantl   static ConstString
587b3f7f69dSAidan Dodds   GetFallbackStructName(); // Print this as the type name of a struct Element
5888b244e21SEwan Crawford                            // If we can't resolve the actual struct name
5898b59062aSEwan Crawford 
59080af0b9eSLuke Drummond   bool ShouldRefresh() const {
5918b59062aSEwan Crawford     const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
592b9c1b51eSKate Stone     const bool valid_type =
593b9c1b51eSKate Stone         type.isValid() && type_vec_size.isValid() && type_kind.isValid();
5948b59062aSEwan Crawford     return !valid_ptr || !valid_type || !datum_size.isValid();
5958b59062aSEwan Crawford   }
5968b244e21SEwan Crawford };
5978b244e21SEwan Crawford 
5988b244e21SEwan Crawford // This AllocationDetails class collects data associated with a single
5998b244e21SEwan Crawford // allocation instance.
600b9c1b51eSKate Stone struct RenderScriptRuntime::AllocationDetails {
601b9c1b51eSKate Stone   struct Dimension {
60215f2bd95SEwan Crawford     uint32_t dim_1;
60315f2bd95SEwan Crawford     uint32_t dim_2;
60415f2bd95SEwan Crawford     uint32_t dim_3;
60580af0b9eSLuke Drummond     uint32_t cube_map;
60615f2bd95SEwan Crawford 
607b9c1b51eSKate Stone     Dimension() {
60815f2bd95SEwan Crawford       dim_1 = 0;
60915f2bd95SEwan Crawford       dim_2 = 0;
61015f2bd95SEwan Crawford       dim_3 = 0;
61180af0b9eSLuke Drummond       cube_map = 0;
61215f2bd95SEwan Crawford     }
61378f339d1SEwan Crawford   };
61478f339d1SEwan Crawford 
615b9c1b51eSKate Stone   // The FileHeader struct specifies the header we use for writing allocations
61680af0b9eSLuke Drummond   // to a binary file. Our format begins with the ASCII characters "RSAD",
61780af0b9eSLuke Drummond   // identifying the file as an allocation dump. Member variables dims and
61880af0b9eSLuke Drummond   // hdr_size are then written consecutively, immediately followed by an
61980af0b9eSLuke Drummond   // instance of the ElementHeader struct. Because Elements can contain
62080af0b9eSLuke Drummond   // subelements, there may be more than one instance of the ElementHeader
62180af0b9eSLuke Drummond   // struct. With this first instance being the root element, and the other
62280af0b9eSLuke Drummond   // instances being the root's descendants. To identify which instances are an
62305097246SAdrian Prantl   // ElementHeader's children, each struct is immediately followed by a
62405097246SAdrian Prantl   // sequence of consecutive offsets to the start of its child structs. These
62505097246SAdrian Prantl   // offsets are
62680af0b9eSLuke Drummond   // 4 bytes in size, and the 0 offset signifies no more children.
627b9c1b51eSKate Stone   struct FileHeader {
62855232f09SEwan Crawford     uint8_t ident[4];  // ASCII 'RSAD' identifying the file
62926e52a70SEwan Crawford     uint32_t dims[3];  // Dimensions
63026e52a70SEwan Crawford     uint16_t hdr_size; // Header size in bytes, including all element headers
63126e52a70SEwan Crawford   };
63226e52a70SEwan Crawford 
633b9c1b51eSKate Stone   struct ElementHeader {
63455232f09SEwan Crawford     uint16_t type;         // DataType enum
63555232f09SEwan Crawford     uint32_t kind;         // DataKind enum
63655232f09SEwan Crawford     uint32_t element_size; // Size of a single element, including padding
63726e52a70SEwan Crawford     uint16_t vector_size;  // Vector width
63826e52a70SEwan Crawford     uint32_t array_size;   // Number of elements in array
63955232f09SEwan Crawford   };
64055232f09SEwan Crawford 
64115f2bd95SEwan Crawford   // Monotonically increasing from 1
642b3f7f69dSAidan Dodds   static uint32_t ID;
64315f2bd95SEwan Crawford 
64405097246SAdrian Prantl   // Maps Allocation DataType enum and vector size to printable strings using
64505097246SAdrian Prantl   // mapping from RenderScript numerical types summary documentation
64615f2bd95SEwan Crawford   static const char *RsDataTypeToString[][4];
64715f2bd95SEwan Crawford 
64815f2bd95SEwan Crawford   // Maps Allocation DataKind enum to printable strings
64915f2bd95SEwan Crawford   static const char *RsDataKindToString[];
65015f2bd95SEwan Crawford 
651a0f08674SEwan Crawford   // Maps allocation types to format sizes for printing.
652b3f7f69dSAidan Dodds   static const uint32_t RSTypeToFormat[][3];
653a0f08674SEwan Crawford 
65415f2bd95SEwan Crawford   // Give each allocation an ID as a way
65515f2bd95SEwan Crawford   // for commands to reference it.
656b3f7f69dSAidan Dodds   const uint32_t id;
65715f2bd95SEwan Crawford 
65880af0b9eSLuke Drummond   // Allocation Element type
65980af0b9eSLuke Drummond   RenderScriptRuntime::Element element;
66080af0b9eSLuke Drummond   // Dimensions of the Allocation
66180af0b9eSLuke Drummond   empirical_type<Dimension> dimension;
66280af0b9eSLuke Drummond   // Pointer to address of the RS Allocation
66380af0b9eSLuke Drummond   empirical_type<lldb::addr_t> address;
66480af0b9eSLuke Drummond   // Pointer to the data held by the Allocation
66580af0b9eSLuke Drummond   empirical_type<lldb::addr_t> data_ptr;
66680af0b9eSLuke Drummond   // Pointer to the RS Type of the Allocation
66780af0b9eSLuke Drummond   empirical_type<lldb::addr_t> type_ptr;
66880af0b9eSLuke Drummond   // Pointer to the RS Context of the Allocation
66980af0b9eSLuke Drummond   empirical_type<lldb::addr_t> context;
67080af0b9eSLuke Drummond   // Size of the allocation
67180af0b9eSLuke Drummond   empirical_type<uint32_t> size;
67280af0b9eSLuke Drummond   // Stride between rows of the allocation
67380af0b9eSLuke Drummond   empirical_type<uint32_t> stride;
67415f2bd95SEwan Crawford 
67515f2bd95SEwan Crawford   // Give each allocation an id, so we can reference it in user commands.
676b3f7f69dSAidan Dodds   AllocationDetails() : id(ID++) {}
6778b59062aSEwan Crawford 
67880af0b9eSLuke Drummond   bool ShouldRefresh() const {
6798b59062aSEwan Crawford     bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
6808b59062aSEwan Crawford     valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
681b9c1b51eSKate Stone     return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
68280af0b9eSLuke Drummond            element.ShouldRefresh();
6838b59062aSEwan Crawford   }
68415f2bd95SEwan Crawford };
68515f2bd95SEwan Crawford 
6860e4c4821SAdrian Prantl ConstString RenderScriptRuntime::Element::GetFallbackStructName() {
687fe06b5adSAdrian McCarthy   static const ConstString FallbackStructName("struct");
688fe06b5adSAdrian McCarthy   return FallbackStructName;
689fe06b5adSAdrian McCarthy }
6908b244e21SEwan Crawford 
691b3f7f69dSAidan Dodds uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
69215f2bd95SEwan Crawford 
693b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
694b9c1b51eSKate Stone     "User",       "Undefined",   "Undefined", "Undefined",
695b9c1b51eSKate Stone     "Undefined",  "Undefined",   "Undefined", // Enum jumps from 0 to 7
696b3f7f69dSAidan Dodds     "L Pixel",    "A Pixel",     "LA Pixel",  "RGB Pixel",
697b3f7f69dSAidan Dodds     "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
69815f2bd95SEwan Crawford 
699b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
70015f2bd95SEwan Crawford     {"None", "None", "None", "None"},
70115f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
70215f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
70315f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
70415f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
70515f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
70615f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
70715f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
70815f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
70915f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
71015f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
71115f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
7122e920715SEwan Crawford     {"bool", "bool2", "bool3", "bool4"},
7132e920715SEwan Crawford     {"packed_565", "packed_565", "packed_565", "packed_565"},
7142e920715SEwan Crawford     {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
7152e920715SEwan Crawford     {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
7162e920715SEwan Crawford     {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
7172e920715SEwan Crawford     {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
7182e920715SEwan Crawford     {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
7192e920715SEwan Crawford 
7202e920715SEwan Crawford     // Handlers
7212e920715SEwan Crawford     {"RS Element", "RS Element", "RS Element", "RS Element"},
7222e920715SEwan Crawford     {"RS Type", "RS Type", "RS Type", "RS Type"},
7232e920715SEwan Crawford     {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
7242e920715SEwan Crawford     {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
7252e920715SEwan Crawford     {"RS Script", "RS Script", "RS Script", "RS Script"},
7262e920715SEwan Crawford 
7272e920715SEwan Crawford     // Deprecated
7282e920715SEwan Crawford     {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
729b9c1b51eSKate Stone     {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
730b9c1b51eSKate Stone      "RS Program Fragment"},
731b9c1b51eSKate Stone     {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
732b9c1b51eSKate Stone      "RS Program Vertex"},
733b9c1b51eSKate Stone     {"RS Program Raster", "RS Program Raster", "RS Program Raster",
734b9c1b51eSKate Stone      "RS Program Raster"},
735b9c1b51eSKate Stone     {"RS Program Store", "RS Program Store", "RS Program Store",
736b9c1b51eSKate Stone      "RS Program Store"},
737b3f7f69dSAidan Dodds     {"RS Font", "RS Font", "RS Font", "RS Font"}};
73878f339d1SEwan Crawford 
739a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
740b9c1b51eSKate Stone enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
741a0f08674SEwan Crawford 
742b9c1b51eSKate Stone // { format enum of single element, format enum of element vector, size of
743b9c1b51eSKate Stone // element}
744b3f7f69dSAidan Dodds const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
74580af0b9eSLuke Drummond     // RS_TYPE_NONE
74680af0b9eSLuke Drummond     {eFormatHex, eFormatHex, 1},
74780af0b9eSLuke Drummond     // RS_TYPE_FLOAT_16
74880af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat16, 2},
74980af0b9eSLuke Drummond     // RS_TYPE_FLOAT_32
75080af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
75180af0b9eSLuke Drummond     // RS_TYPE_FLOAT_64
75280af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
75380af0b9eSLuke Drummond     // RS_TYPE_SIGNED_8
75480af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
75580af0b9eSLuke Drummond     // RS_TYPE_SIGNED_16
75680af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
75780af0b9eSLuke Drummond     // RS_TYPE_SIGNED_32
75880af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
75980af0b9eSLuke Drummond     // RS_TYPE_SIGNED_64
76080af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
76180af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_8
76280af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
76380af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_16
76480af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
76580af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_32
76680af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
76780af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_64
76880af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
76980af0b9eSLuke Drummond     // RS_TYPE_BOOL
77080af0b9eSLuke Drummond     {eFormatBoolean, eFormatBoolean, 1},
77180af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_5_6_5
77280af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
77380af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_5_5_5_1
77480af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
77580af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_4_4_4_4
77680af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
77780af0b9eSLuke Drummond     // RS_TYPE_MATRIX_4X4
77880af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
77980af0b9eSLuke Drummond     // RS_TYPE_MATRIX_3X3
78080af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
78180af0b9eSLuke Drummond     // RS_TYPE_MATRIX_2X2
78280af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
783a0f08674SEwan Crawford 
7845ec532a9SColin Riley // Static Functions
7855ec532a9SColin Riley LanguageRuntime *
786b9c1b51eSKate Stone RenderScriptRuntime::CreateInstance(Process *process,
787b9c1b51eSKate Stone                                     lldb::LanguageType language) {
7885ec532a9SColin Riley 
7895ec532a9SColin Riley   if (language == eLanguageTypeExtRenderScript)
7905ec532a9SColin Riley     return new RenderScriptRuntime(process);
7915ec532a9SColin Riley   else
792b3f7f69dSAidan Dodds     return nullptr;
7935ec532a9SColin Riley }
7945ec532a9SColin Riley 
79580af0b9eSLuke Drummond // Callback with a module to search for matching symbols. We first check that
79680af0b9eSLuke Drummond // the module contains RS kernels. Then look for a symbol which matches our
79780af0b9eSLuke Drummond // kernel name. The breakpoint address is finally set using the address of this
79880af0b9eSLuke Drummond // symbol.
79998156583SEwan Crawford Searcher::CallbackReturn
800b9c1b51eSKate Stone RSBreakpointResolver::SearchCallback(SearchFilter &filter,
801b9c1b51eSKate Stone                                      SymbolContext &context, Address *, bool) {
80298156583SEwan Crawford   ModuleSP module = context.module_sp;
80398156583SEwan Crawford 
804b3bbcb12SLuke Drummond   if (!module || !IsRenderScriptScriptModule(module))
80598156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
80698156583SEwan Crawford 
807b9c1b51eSKate Stone   // Attempt to set a breakpoint on the kernel name symbol within the module
80880af0b9eSLuke Drummond   // library. If it's not found, it's likely debug info is unavailable - try to
80980af0b9eSLuke Drummond   // set a breakpoint on <name>.expand.
810b9c1b51eSKate Stone   const Symbol *kernel_sym =
811b9c1b51eSKate Stone       module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
812b9c1b51eSKate Stone   if (!kernel_sym) {
81398156583SEwan Crawford     std::string kernel_name_expanded(m_kernel_name.AsCString());
81498156583SEwan Crawford     kernel_name_expanded.append(".expand");
815b9c1b51eSKate Stone     kernel_sym = module->FindFirstSymbolWithNameAndType(
816b9c1b51eSKate Stone         ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
81798156583SEwan Crawford   }
81898156583SEwan Crawford 
819b9c1b51eSKate Stone   if (kernel_sym) {
82098156583SEwan Crawford     Address bp_addr = kernel_sym->GetAddress();
82198156583SEwan Crawford     if (filter.AddressPasses(bp_addr))
82298156583SEwan Crawford       m_breakpoint->AddLocation(bp_addr);
82398156583SEwan Crawford   }
82498156583SEwan Crawford 
82598156583SEwan Crawford   return Searcher::eCallbackReturnContinue;
82698156583SEwan Crawford }
82798156583SEwan Crawford 
828b3bbcb12SLuke Drummond Searcher::CallbackReturn
829b3bbcb12SLuke Drummond RSReduceBreakpointResolver::SearchCallback(lldb_private::SearchFilter &filter,
830b3bbcb12SLuke Drummond                                            lldb_private::SymbolContext &context,
831b3bbcb12SLuke Drummond                                            Address *, bool) {
832b3bbcb12SLuke Drummond   // We need to have access to the list of reductions currently parsed, as
83305097246SAdrian Prantl   // reduce names don't actually exist as symbols in a module. They are only
83405097246SAdrian Prantl   // identifiable by parsing the .rs.info packet, or finding the expand symbol.
83505097246SAdrian Prantl   // We therefore need access to the list of parsed rs modules to properly
83605097246SAdrian Prantl   // resolve reduction names.
837b3bbcb12SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
838b3bbcb12SLuke Drummond   ModuleSP module = context.module_sp;
839b3bbcb12SLuke Drummond 
840b3bbcb12SLuke Drummond   if (!module || !IsRenderScriptScriptModule(module))
841b3bbcb12SLuke Drummond     return Searcher::eCallbackReturnContinue;
842b3bbcb12SLuke Drummond 
843b3bbcb12SLuke Drummond   if (!m_rsmodules)
844b3bbcb12SLuke Drummond     return Searcher::eCallbackReturnContinue;
845b3bbcb12SLuke Drummond 
846b3bbcb12SLuke Drummond   for (const auto &module_desc : *m_rsmodules) {
847b3bbcb12SLuke Drummond     if (module_desc->m_module != module)
848b3bbcb12SLuke Drummond       continue;
849b3bbcb12SLuke Drummond 
850b3bbcb12SLuke Drummond     for (const auto &reduction : module_desc->m_reductions) {
851b3bbcb12SLuke Drummond       if (reduction.m_reduce_name != m_reduce_name)
852b3bbcb12SLuke Drummond         continue;
853b3bbcb12SLuke Drummond 
854b3bbcb12SLuke Drummond       std::array<std::pair<ConstString, int>, 5> funcs{
855b3bbcb12SLuke Drummond           {{reduction.m_init_name, eKernelTypeInit},
856b3bbcb12SLuke Drummond            {reduction.m_accum_name, eKernelTypeAccum},
857b3bbcb12SLuke Drummond            {reduction.m_comb_name, eKernelTypeComb},
858b3bbcb12SLuke Drummond            {reduction.m_outc_name, eKernelTypeOutC},
859b3bbcb12SLuke Drummond            {reduction.m_halter_name, eKernelTypeHalter}}};
860b3bbcb12SLuke Drummond 
861b3bbcb12SLuke Drummond       for (const auto &kernel : funcs) {
862b3bbcb12SLuke Drummond         // Skip constituent functions that don't match our spec
863b3bbcb12SLuke Drummond         if (!(m_kernel_types & kernel.second))
864b3bbcb12SLuke Drummond           continue;
865b3bbcb12SLuke Drummond 
866b3bbcb12SLuke Drummond         const auto kernel_name = kernel.first;
867b3bbcb12SLuke Drummond         const auto symbol = module->FindFirstSymbolWithNameAndType(
868b3bbcb12SLuke Drummond             kernel_name, eSymbolTypeCode);
869b3bbcb12SLuke Drummond         if (!symbol)
870b3bbcb12SLuke Drummond           continue;
871b3bbcb12SLuke Drummond 
872b3bbcb12SLuke Drummond         auto address = symbol->GetAddress();
873b3bbcb12SLuke Drummond         if (filter.AddressPasses(address)) {
874b3bbcb12SLuke Drummond           bool new_bp;
87581fc84faSLuke Drummond           if (!SkipPrologue(module, address)) {
876*63e5fb76SJonas Devlieghere             LLDB_LOGF(log, "%s: Error trying to skip prologue", __FUNCTION__);
87781fc84faSLuke Drummond           }
878b3bbcb12SLuke Drummond           m_breakpoint->AddLocation(address, &new_bp);
879*63e5fb76SJonas Devlieghere           LLDB_LOGF(log, "%s: %s reduction breakpoint on %s in %s",
880*63e5fb76SJonas Devlieghere                     __FUNCTION__, new_bp ? "new" : "existing",
881*63e5fb76SJonas Devlieghere                     kernel_name.GetCString(),
882b3bbcb12SLuke Drummond                     address.GetModule()->GetFileSpec().GetCString());
883b3bbcb12SLuke Drummond         }
884b3bbcb12SLuke Drummond       }
885b3bbcb12SLuke Drummond     }
886b3bbcb12SLuke Drummond   }
887b3bbcb12SLuke Drummond   return eCallbackReturnContinue;
888b3bbcb12SLuke Drummond }
889b3bbcb12SLuke Drummond 
89021fed052SAidan Dodds Searcher::CallbackReturn RSScriptGroupBreakpointResolver::SearchCallback(
89121fed052SAidan Dodds     SearchFilter &filter, SymbolContext &context, Address *addr,
89221fed052SAidan Dodds     bool containing) {
89321fed052SAidan Dodds 
89421fed052SAidan Dodds   if (!m_breakpoint)
89521fed052SAidan Dodds     return eCallbackReturnContinue;
89621fed052SAidan Dodds 
89721fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
89821fed052SAidan Dodds   ModuleSP &module = context.module_sp;
89921fed052SAidan Dodds 
90021fed052SAidan Dodds   if (!module || !IsRenderScriptScriptModule(module))
90121fed052SAidan Dodds     return Searcher::eCallbackReturnContinue;
90221fed052SAidan Dodds 
90321fed052SAidan Dodds   std::vector<std::string> names;
90421fed052SAidan Dodds   m_breakpoint->GetNames(names);
90521fed052SAidan Dodds   if (names.empty())
90621fed052SAidan Dodds     return eCallbackReturnContinue;
90721fed052SAidan Dodds 
90821fed052SAidan Dodds   for (auto &name : names) {
90921fed052SAidan Dodds     const RSScriptGroupDescriptorSP sg = FindScriptGroup(ConstString(name));
91021fed052SAidan Dodds     if (!sg) {
911*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s: could not find script group for %s", __FUNCTION__,
91221fed052SAidan Dodds                 name.c_str());
91321fed052SAidan Dodds       continue;
91421fed052SAidan Dodds     }
91521fed052SAidan Dodds 
916*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s: Found ScriptGroup for %s", __FUNCTION__, name.c_str());
91721fed052SAidan Dodds 
91821fed052SAidan Dodds     for (const RSScriptGroupDescriptor::Kernel &k : sg->m_kernels) {
91921fed052SAidan Dodds       if (log) {
920*63e5fb76SJonas Devlieghere         LLDB_LOGF(log, "%s: Adding breakpoint for %s", __FUNCTION__,
92121fed052SAidan Dodds                   k.m_name.AsCString());
922*63e5fb76SJonas Devlieghere         LLDB_LOGF(log, "%s: Kernel address 0x%" PRIx64, __FUNCTION__, k.m_addr);
92321fed052SAidan Dodds       }
92421fed052SAidan Dodds 
92521fed052SAidan Dodds       const lldb_private::Symbol *sym =
92621fed052SAidan Dodds           module->FindFirstSymbolWithNameAndType(k.m_name, eSymbolTypeCode);
92721fed052SAidan Dodds       if (!sym) {
928*63e5fb76SJonas Devlieghere         LLDB_LOGF(log, "%s: Unable to find symbol for %s", __FUNCTION__,
92921fed052SAidan Dodds                   k.m_name.AsCString());
93021fed052SAidan Dodds         continue;
93121fed052SAidan Dodds       }
93221fed052SAidan Dodds 
93321fed052SAidan Dodds       if (log) {
934*63e5fb76SJonas Devlieghere         LLDB_LOGF(log, "%s: Found symbol name is %s", __FUNCTION__,
93521fed052SAidan Dodds                   sym->GetName().AsCString());
93621fed052SAidan Dodds       }
93721fed052SAidan Dodds 
93821fed052SAidan Dodds       auto address = sym->GetAddress();
93921fed052SAidan Dodds       if (!SkipPrologue(module, address)) {
940*63e5fb76SJonas Devlieghere         LLDB_LOGF(log, "%s: Error trying to skip prologue", __FUNCTION__);
94121fed052SAidan Dodds       }
94221fed052SAidan Dodds 
94321fed052SAidan Dodds       bool new_bp;
94421fed052SAidan Dodds       m_breakpoint->AddLocation(address, &new_bp);
94521fed052SAidan Dodds 
946*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s: Placed %sbreakpoint on %s", __FUNCTION__,
94721fed052SAidan Dodds                 new_bp ? "new " : "", k.m_name.AsCString());
94821fed052SAidan Dodds 
94905097246SAdrian Prantl       // exit after placing the first breakpoint if we do not intend to stop on
95005097246SAdrian Prantl       // all kernels making up this script group
95121fed052SAidan Dodds       if (!m_stop_on_all)
95221fed052SAidan Dodds         break;
95321fed052SAidan Dodds     }
95421fed052SAidan Dodds   }
95521fed052SAidan Dodds 
95621fed052SAidan Dodds   return eCallbackReturnContinue;
95721fed052SAidan Dodds }
95821fed052SAidan Dodds 
959b9c1b51eSKate Stone void RenderScriptRuntime::Initialize() {
960b9c1b51eSKate Stone   PluginManager::RegisterPlugin(GetPluginNameStatic(),
961b9c1b51eSKate Stone                                 "RenderScript language support", CreateInstance,
962b3f7f69dSAidan Dodds                                 GetCommandObject);
9635ec532a9SColin Riley }
9645ec532a9SColin Riley 
965b9c1b51eSKate Stone void RenderScriptRuntime::Terminate() {
9665ec532a9SColin Riley   PluginManager::UnregisterPlugin(CreateInstance);
9675ec532a9SColin Riley }
9685ec532a9SColin Riley 
969b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginNameStatic() {
97080af0b9eSLuke Drummond   static ConstString plugin_name("renderscript");
97180af0b9eSLuke Drummond   return plugin_name;
9725ec532a9SColin Riley }
9735ec532a9SColin Riley 
974ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
975b9c1b51eSKate Stone RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
976b9c1b51eSKate Stone   if (module_sp) {
977b3bbcb12SLuke Drummond     if (IsRenderScriptScriptModule(module_sp))
978ef20b08fSColin Riley       return eModuleKindKernelObj;
9794640cde1SColin Riley 
9804640cde1SColin Riley     // Is this the main RS runtime library
9814640cde1SColin Riley     const ConstString rs_lib("libRS.so");
982b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
9834640cde1SColin Riley       return eModuleKindLibRS;
9844640cde1SColin Riley     }
9854640cde1SColin Riley 
9864640cde1SColin Riley     const ConstString rs_driverlib("libRSDriver.so");
987b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
9884640cde1SColin Riley       return eModuleKindDriver;
9894640cde1SColin Riley     }
9904640cde1SColin Riley 
99115f2bd95SEwan Crawford     const ConstString rs_cpureflib("libRSCpuRef.so");
992b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
9934640cde1SColin Riley       return eModuleKindImpl;
9944640cde1SColin Riley     }
995ef20b08fSColin Riley   }
996ef20b08fSColin Riley   return eModuleKindIgnored;
997ef20b08fSColin Riley }
998ef20b08fSColin Riley 
999b9c1b51eSKate Stone bool RenderScriptRuntime::IsRenderScriptModule(
1000b9c1b51eSKate Stone     const lldb::ModuleSP &module_sp) {
1001ef20b08fSColin Riley   return GetModuleKind(module_sp) != eModuleKindIgnored;
1002ef20b08fSColin Riley }
1003ef20b08fSColin Riley 
1004b9c1b51eSKate Stone void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
1005bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1006ef20b08fSColin Riley 
1007ef20b08fSColin Riley   size_t num_modules = module_list.GetSize();
1008b9c1b51eSKate Stone   for (size_t i = 0; i < num_modules; i++) {
1009ef20b08fSColin Riley     auto mod = module_list.GetModuleAtIndex(i);
1010b9c1b51eSKate Stone     if (IsRenderScriptModule(mod)) {
1011ef20b08fSColin Riley       LoadModule(mod);
1012ef20b08fSColin Riley     }
1013ef20b08fSColin Riley   }
1014ef20b08fSColin Riley }
1015ef20b08fSColin Riley 
10165ec532a9SColin Riley // PluginInterface protocol
1017b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginName() {
10185ec532a9SColin Riley   return GetPluginNameStatic();
10195ec532a9SColin Riley }
10205ec532a9SColin Riley 
1021b9c1b51eSKate Stone uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; }
10225ec532a9SColin Riley 
1023b9c1b51eSKate Stone bool RenderScriptRuntime::GetDynamicTypeAndAddress(
1024b9c1b51eSKate Stone     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
10255f57b6eeSEnrico Granata     TypeAndOrName &class_type_or_name, Address &address,
1026b9c1b51eSKate Stone     Value::ValueType &value_type) {
10275ec532a9SColin Riley   return false;
10285ec532a9SColin Riley }
10295ec532a9SColin Riley 
1030c74275bcSEnrico Granata TypeAndOrName
1031b9c1b51eSKate Stone RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
1032b9c1b51eSKate Stone                                       ValueObject &static_value) {
1033c74275bcSEnrico Granata   return type_and_or_name;
1034c74275bcSEnrico Granata }
1035c74275bcSEnrico Granata 
1036b9c1b51eSKate Stone bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
10375ec532a9SColin Riley   return false;
10385ec532a9SColin Riley }
10395ec532a9SColin Riley 
10405ec532a9SColin Riley lldb::BreakpointResolverSP
104180af0b9eSLuke Drummond RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bp, bool catch_bp,
1042b9c1b51eSKate Stone                                              bool throw_bp) {
10435ec532a9SColin Riley   BreakpointResolverSP resolver_sp;
10445ec532a9SColin Riley   return resolver_sp;
10455ec532a9SColin Riley }
10465ec532a9SColin Riley 
1047b9c1b51eSKate Stone const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
1048b9c1b51eSKate Stone     {
10494640cde1SColin Riley         // rsdScript
1050b9c1b51eSKate Stone         {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
1051b9c1b51eSKate Stone                           "NS0_7ScriptCEPKcS7_PKhjj",
1052b9c1b51eSKate Stone          "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
1053b9c1b51eSKate Stone          "7ScriptCEPKcS7_PKhmj",
1054b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1055b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInit},
1056b9c1b51eSKate Stone         {"rsdScriptInvokeForEachMulti",
1057b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1058b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
1059b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1060b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
1061b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1062b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
1063b9c1b51eSKate Stone         {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
1064b9c1b51eSKate Stone                                   "script7ContextEPKNS0_6ScriptEjPvj",
1065b9c1b51eSKate Stone          "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
1066b9c1b51eSKate Stone          "6ScriptEjPvm",
1067b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1068b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
10694640cde1SColin Riley 
10704640cde1SColin Riley         // rsdAllocation
1071b9c1b51eSKate Stone         {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
1072b9c1b51eSKate Stone                               "ontextEPNS0_10AllocationEb",
1073b9c1b51eSKate Stone          "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
1074b9c1b51eSKate Stone          "10AllocationEb",
1075b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1076b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
1077b9c1b51eSKate Stone         {"rsdAllocationRead2D",
1078b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1079b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1080b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1081b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1082b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1083b9c1b51eSKate Stone         {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1084b9c1b51eSKate Stone                                  "ript7ContextEPNS0_10AllocationE",
1085b9c1b51eSKate Stone          "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1086b9c1b51eSKate Stone          "10AllocationE",
1087b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1088b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
108921fed052SAidan Dodds 
109021fed052SAidan Dodds         // renderscript script groups
109121fed052SAidan Dodds         {"rsdDebugHintScriptGroup2", "_ZN7android12renderscript21debugHintScrip"
109221fed052SAidan Dodds                                      "tGroup2EPKcjPKPFvPK24RsExpandKernelDriver"
109321fed052SAidan Dodds                                      "InfojjjEj",
109421fed052SAidan Dodds          "_ZN7android12renderscript21debugHintScriptGroup2EPKcjPKPFvPK24RsExpan"
109521fed052SAidan Dodds          "dKernelDriverInfojjjEj",
109621fed052SAidan Dodds          0, RenderScriptRuntime::eModuleKindImpl,
109721fed052SAidan Dodds          &lldb_private::RenderScriptRuntime::CaptureDebugHintScriptGroup2}};
10984640cde1SColin Riley 
1099b9c1b51eSKate Stone const size_t RenderScriptRuntime::s_runtimeHookCount =
1100b9c1b51eSKate Stone     sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
11014640cde1SColin Riley 
1102b9c1b51eSKate Stone bool RenderScriptRuntime::HookCallback(void *baton,
1103b9c1b51eSKate Stone                                        StoppointCallbackContext *ctx,
1104b9c1b51eSKate Stone                                        lldb::user_id_t break_id,
1105b9c1b51eSKate Stone                                        lldb::user_id_t break_loc_id) {
110680af0b9eSLuke Drummond   RuntimeHook *hook = (RuntimeHook *)baton;
110780af0b9eSLuke Drummond   ExecutionContext exe_ctx(ctx->exe_ctx_ref);
11084640cde1SColin Riley 
1109056f6f18SAlex Langford   RenderScriptRuntime *lang_rt = llvm::cast<RenderScriptRuntime>(
1110056f6f18SAlex Langford       exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1111056f6f18SAlex Langford           eLanguageTypeExtRenderScript));
11124640cde1SColin Riley 
111380af0b9eSLuke Drummond   lang_rt->HookCallback(hook, exe_ctx);
11144640cde1SColin Riley 
11154640cde1SColin Riley   return false;
11164640cde1SColin Riley }
11174640cde1SColin Riley 
111880af0b9eSLuke Drummond void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
111980af0b9eSLuke Drummond                                        ExecutionContext &exe_ctx) {
11204640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11214640cde1SColin Riley 
1122*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - '%s'", __FUNCTION__, hook->defn->name);
11234640cde1SColin Riley 
112480af0b9eSLuke Drummond   if (hook->defn->grabber) {
112580af0b9eSLuke Drummond     (this->*(hook->defn->grabber))(hook, exe_ctx);
11264640cde1SColin Riley   }
11274640cde1SColin Riley }
11284640cde1SColin Riley 
112921fed052SAidan Dodds void RenderScriptRuntime::CaptureDebugHintScriptGroup2(
113021fed052SAidan Dodds     RuntimeHook *hook_info, ExecutionContext &context) {
113121fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
113221fed052SAidan Dodds 
113321fed052SAidan Dodds   enum {
113421fed052SAidan Dodds     eGroupName = 0,
113521fed052SAidan Dodds     eGroupNameSize,
113621fed052SAidan Dodds     eKernel,
113721fed052SAidan Dodds     eKernelCount,
113821fed052SAidan Dodds   };
113921fed052SAidan Dodds 
114021fed052SAidan Dodds   std::array<ArgItem, 4> args{{
114121fed052SAidan Dodds       {ArgItem::ePointer, 0}, // const char         *groupName
114221fed052SAidan Dodds       {ArgItem::eInt32, 0},   // const uint32_t      groupNameSize
114321fed052SAidan Dodds       {ArgItem::ePointer, 0}, // const ExpandFuncTy *kernel
114421fed052SAidan Dodds       {ArgItem::eInt32, 0},   // const uint32_t      kernelCount
114521fed052SAidan Dodds   }};
114621fed052SAidan Dodds 
114721fed052SAidan Dodds   if (!GetArgs(context, args.data(), args.size())) {
1148*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - Error while reading the function parameters",
114921fed052SAidan Dodds               __FUNCTION__);
115021fed052SAidan Dodds     return;
115121fed052SAidan Dodds   } else if (log) {
1152*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - groupName    : 0x%" PRIx64, __FUNCTION__,
115321fed052SAidan Dodds               addr_t(args[eGroupName]));
1154*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - groupNameSize: %" PRIu64, __FUNCTION__,
115521fed052SAidan Dodds               uint64_t(args[eGroupNameSize]));
1156*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - kernel       : 0x%" PRIx64, __FUNCTION__,
115721fed052SAidan Dodds               addr_t(args[eKernel]));
1158*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - kernelCount  : %" PRIu64, __FUNCTION__,
115921fed052SAidan Dodds               uint64_t(args[eKernelCount]));
116021fed052SAidan Dodds   }
116121fed052SAidan Dodds 
116221fed052SAidan Dodds   // parse script group name
116321fed052SAidan Dodds   ConstString group_name;
116421fed052SAidan Dodds   {
116597206d57SZachary Turner     Status err;
116621fed052SAidan Dodds     const uint64_t len = uint64_t(args[eGroupNameSize]);
116721fed052SAidan Dodds     std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]);
116821fed052SAidan Dodds     m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err);
116921fed052SAidan Dodds     buffer.get()[len] = '\0';
117021fed052SAidan Dodds     if (!err.Success()) {
1171*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "Error reading scriptgroup name from target");
117221fed052SAidan Dodds       return;
117321fed052SAidan Dodds     } else {
1174*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "Extracted scriptgroup name %s", buffer.get());
117521fed052SAidan Dodds     }
117621fed052SAidan Dodds     // write back the script group name
117721fed052SAidan Dodds     group_name.SetCString(buffer.get());
117821fed052SAidan Dodds   }
117921fed052SAidan Dodds 
118021fed052SAidan Dodds   // create or access existing script group
118121fed052SAidan Dodds   RSScriptGroupDescriptorSP group;
118221fed052SAidan Dodds   {
118321fed052SAidan Dodds     // search for existing script group
118421fed052SAidan Dodds     for (auto sg : m_scriptGroups) {
118521fed052SAidan Dodds       if (sg->m_name == group_name) {
118621fed052SAidan Dodds         group = sg;
118721fed052SAidan Dodds         break;
118821fed052SAidan Dodds       }
118921fed052SAidan Dodds     }
119021fed052SAidan Dodds     if (!group) {
1191796ac80bSJonas Devlieghere       group = std::make_shared<RSScriptGroupDescriptor>();
119221fed052SAidan Dodds       group->m_name = group_name;
119321fed052SAidan Dodds       m_scriptGroups.push_back(group);
119421fed052SAidan Dodds     } else {
119521fed052SAidan Dodds       // already have this script group
1196*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "Attempt to add duplicate script group %s",
119721fed052SAidan Dodds                 group_name.AsCString());
119821fed052SAidan Dodds       return;
119921fed052SAidan Dodds     }
120021fed052SAidan Dodds   }
120121fed052SAidan Dodds   assert(group);
120221fed052SAidan Dodds 
120321fed052SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
120421fed052SAidan Dodds   std::vector<addr_t> kernels;
120521fed052SAidan Dodds   // parse kernel addresses in script group
120621fed052SAidan Dodds   for (uint64_t i = 0; i < uint64_t(args[eKernelCount]); ++i) {
120721fed052SAidan Dodds     RSScriptGroupDescriptor::Kernel kernel;
120821fed052SAidan Dodds     // extract script group kernel addresses from the target
120921fed052SAidan Dodds     const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size;
121021fed052SAidan Dodds     uint64_t kernel_addr = 0;
121197206d57SZachary Turner     Status err;
121221fed052SAidan Dodds     size_t read =
121321fed052SAidan Dodds         m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err);
121421fed052SAidan Dodds     if (!err.Success() || read != target_ptr_size) {
1215*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "Error parsing kernel address %" PRIu64 " in script group",
121621fed052SAidan Dodds                 i);
121721fed052SAidan Dodds       return;
121821fed052SAidan Dodds     }
1219*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "Extracted scriptgroup kernel address - 0x%" PRIx64,
122021fed052SAidan Dodds               kernel_addr);
122121fed052SAidan Dodds     kernel.m_addr = kernel_addr;
122221fed052SAidan Dodds 
122321fed052SAidan Dodds     // try to resolve the associated kernel name
122421fed052SAidan Dodds     if (!ResolveKernelName(kernel.m_addr, kernel.m_name)) {
1225*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "Parsed scriptgroup kernel %" PRIu64 " - 0x%" PRIx64, i,
122621fed052SAidan Dodds                 kernel_addr);
122721fed052SAidan Dodds       return;
122821fed052SAidan Dodds     }
122921fed052SAidan Dodds 
123021fed052SAidan Dodds     // try to find the non '.expand' function
123121fed052SAidan Dodds     {
123221fed052SAidan Dodds       const llvm::StringRef expand(".expand");
123321fed052SAidan Dodds       const llvm::StringRef name_ref = kernel.m_name.GetStringRef();
123421fed052SAidan Dodds       if (name_ref.endswith(expand)) {
123521fed052SAidan Dodds         const ConstString base_kernel(name_ref.drop_back(expand.size()));
123621fed052SAidan Dodds         // verify this function is a valid kernel
123721fed052SAidan Dodds         if (IsKnownKernel(base_kernel)) {
123821fed052SAidan Dodds           kernel.m_name = base_kernel;
1239*63e5fb76SJonas Devlieghere           LLDB_LOGF(log, "%s - found non expand version '%s'", __FUNCTION__,
124021fed052SAidan Dodds                     base_kernel.GetCString());
124121fed052SAidan Dodds         }
124221fed052SAidan Dodds       }
124321fed052SAidan Dodds     }
124421fed052SAidan Dodds     // add to a list of script group kernels we know about
124521fed052SAidan Dodds     group->m_kernels.push_back(kernel);
124621fed052SAidan Dodds   }
124721fed052SAidan Dodds 
124821fed052SAidan Dodds   // Resolve any pending scriptgroup breakpoints
124921fed052SAidan Dodds   {
125021fed052SAidan Dodds     Target &target = m_process->GetTarget();
125121fed052SAidan Dodds     const BreakpointList &list = target.GetBreakpointList();
125221fed052SAidan Dodds     const size_t num_breakpoints = list.GetSize();
1253*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "Resolving %zu breakpoints", num_breakpoints);
125421fed052SAidan Dodds     for (size_t i = 0; i < num_breakpoints; ++i) {
125521fed052SAidan Dodds       const BreakpointSP bp = list.GetBreakpointAtIndex(i);
125621fed052SAidan Dodds       if (bp) {
125721fed052SAidan Dodds         if (bp->MatchesName(group_name.AsCString())) {
1258*63e5fb76SJonas Devlieghere           LLDB_LOGF(log, "Found breakpoint with name %s",
125921fed052SAidan Dodds                     group_name.AsCString());
126021fed052SAidan Dodds           bp->ResolveBreakpoint();
126121fed052SAidan Dodds         }
126221fed052SAidan Dodds       }
126321fed052SAidan Dodds     }
126421fed052SAidan Dodds   }
126521fed052SAidan Dodds }
126621fed052SAidan Dodds 
1267b9c1b51eSKate Stone void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
126880af0b9eSLuke Drummond     RuntimeHook *hook, ExecutionContext &exe_ctx) {
1269e09c44b6SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1270e09c44b6SAidan Dodds 
1271b9c1b51eSKate Stone   enum {
1272f4786785SAidan Dodds     eRsContext = 0,
1273f4786785SAidan Dodds     eRsScript,
1274f4786785SAidan Dodds     eRsSlot,
1275f4786785SAidan Dodds     eRsAIns,
1276f4786785SAidan Dodds     eRsInLen,
1277f4786785SAidan Dodds     eRsAOut,
1278f4786785SAidan Dodds     eRsUsr,
1279f4786785SAidan Dodds     eRsUsrLen,
1280f4786785SAidan Dodds     eRsSc,
1281f4786785SAidan Dodds   };
1282e09c44b6SAidan Dodds 
12831ee07253SSaleem Abdulrasool   std::array<ArgItem, 9> args{{
1284f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Context       *rsc
1285f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Script              *s
1286f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // uint32_t             slot
1287f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Allocation   **aIns
1288f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               inLen
1289f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Allocation          *aout
1290f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const void          *usr
1291f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               usrLen
1292f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall  *sc
12931ee07253SSaleem Abdulrasool   }};
1294e09c44b6SAidan Dodds 
129580af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1296b9c1b51eSKate Stone   if (!success) {
1297*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - Error while reading the function parameters",
1298b9c1b51eSKate Stone               __FUNCTION__);
1299e09c44b6SAidan Dodds     return;
1300e09c44b6SAidan Dodds   }
1301e09c44b6SAidan Dodds 
1302e09c44b6SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
130397206d57SZachary Turner   Status err;
1304e09c44b6SAidan Dodds   std::vector<uint64_t> allocs;
1305e09c44b6SAidan Dodds 
1306e09c44b6SAidan Dodds   // traverse allocation list
1307b9c1b51eSKate Stone   for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1308e09c44b6SAidan Dodds     // calculate offest to allocation pointer
1309f4786785SAidan Dodds     const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1310e09c44b6SAidan Dodds 
131180af0b9eSLuke Drummond     // Note: due to little endian layout, reading 32bits or 64bits into res
131280af0b9eSLuke Drummond     // will give the correct results.
131380af0b9eSLuke Drummond     uint64_t result = 0;
131480af0b9eSLuke Drummond     size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
131580af0b9eSLuke Drummond     if (read != target_ptr_size || !err.Success()) {
1316*63e5fb76SJonas Devlieghere       LLDB_LOGF(log,
1317b9c1b51eSKate Stone                 "%s - Error while reading allocation list argument %" PRIu64,
1318b9c1b51eSKate Stone                 __FUNCTION__, i);
1319b9c1b51eSKate Stone     } else {
132080af0b9eSLuke Drummond       allocs.push_back(result);
1321e09c44b6SAidan Dodds     }
1322e09c44b6SAidan Dodds   }
1323e09c44b6SAidan Dodds 
1324e09c44b6SAidan Dodds   // if there is an output allocation track it
132580af0b9eSLuke Drummond   if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
132680af0b9eSLuke Drummond     allocs.push_back(alloc_out);
1327e09c44b6SAidan Dodds   }
1328e09c44b6SAidan Dodds 
1329e09c44b6SAidan Dodds   // for all allocations we have found
1330b9c1b51eSKate Stone   for (const uint64_t alloc_addr : allocs) {
13315d057637SLuke Drummond     AllocationDetails *alloc = LookUpAllocation(alloc_addr);
13325d057637SLuke Drummond     if (!alloc)
13335d057637SLuke Drummond       alloc = CreateAllocation(alloc_addr);
13345d057637SLuke Drummond 
1335b9c1b51eSKate Stone     if (alloc) {
1336e09c44b6SAidan Dodds       // save the allocation address
1337b9c1b51eSKate Stone       if (alloc->address.isValid()) {
1338e09c44b6SAidan Dodds         // check the allocation address we already have matches
1339e09c44b6SAidan Dodds         assert(*alloc->address.get() == alloc_addr);
1340b9c1b51eSKate Stone       } else {
1341e09c44b6SAidan Dodds         alloc->address = alloc_addr;
1342e09c44b6SAidan Dodds       }
1343e09c44b6SAidan Dodds 
1344e09c44b6SAidan Dodds       // save the context
1345b9c1b51eSKate Stone       if (log) {
1346b9c1b51eSKate Stone         if (alloc->context.isValid() &&
1347b9c1b51eSKate Stone             *alloc->context.get() != addr_t(args[eRsContext]))
1348*63e5fb76SJonas Devlieghere           LLDB_LOGF(log, "%s - Allocation used by multiple contexts",
1349b9c1b51eSKate Stone                     __FUNCTION__);
1350e09c44b6SAidan Dodds       }
1351f4786785SAidan Dodds       alloc->context = addr_t(args[eRsContext]);
1352e09c44b6SAidan Dodds     }
1353e09c44b6SAidan Dodds   }
1354e09c44b6SAidan Dodds 
1355e09c44b6SAidan Dodds   // make sure we track this script object
1356b9c1b51eSKate Stone   if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1357b9c1b51eSKate Stone           LookUpScript(addr_t(args[eRsScript]), true)) {
1358b9c1b51eSKate Stone     if (log) {
1359b9c1b51eSKate Stone       if (script->context.isValid() &&
1360b9c1b51eSKate Stone           *script->context.get() != addr_t(args[eRsContext]))
1361*63e5fb76SJonas Devlieghere         LLDB_LOGF(log, "%s - Script used by multiple contexts", __FUNCTION__);
1362e09c44b6SAidan Dodds     }
1363f4786785SAidan Dodds     script->context = addr_t(args[eRsContext]);
1364e09c44b6SAidan Dodds   }
1365e09c44b6SAidan Dodds }
1366e09c44b6SAidan Dodds 
136780af0b9eSLuke Drummond void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1368b9c1b51eSKate Stone                                               ExecutionContext &context) {
13694640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
13704640cde1SColin Riley 
1371b9c1b51eSKate Stone   enum {
1372f4786785SAidan Dodds     eRsContext,
1373f4786785SAidan Dodds     eRsScript,
1374f4786785SAidan Dodds     eRsId,
1375f4786785SAidan Dodds     eRsData,
1376f4786785SAidan Dodds     eRsLength,
1377f4786785SAidan Dodds   };
13784640cde1SColin Riley 
13791ee07253SSaleem Abdulrasool   std::array<ArgItem, 5> args{{
1380f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1381f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsScript
1382f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsId
1383f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsData
1384f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsLength
13851ee07253SSaleem Abdulrasool   }};
13864640cde1SColin Riley 
1387f4786785SAidan Dodds   bool success = GetArgs(context, &args[0], args.size());
1388b9c1b51eSKate Stone   if (!success) {
1389*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error reading the function parameters.", __FUNCTION__);
139082780287SAidan Dodds     return;
139182780287SAidan Dodds   }
13924640cde1SColin Riley 
1393b9c1b51eSKate Stone   if (log) {
1394*63e5fb76SJonas Devlieghere     LLDB_LOGF(log,
1395*63e5fb76SJonas Devlieghere               "%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1396b9c1b51eSKate Stone               ":%" PRIu64 "bytes.",
1397b9c1b51eSKate Stone               __FUNCTION__, uint64_t(args[eRsContext]),
1398b9c1b51eSKate Stone               uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1399f4786785SAidan Dodds               uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
14004640cde1SColin Riley 
1401f4786785SAidan Dodds     addr_t script_addr = addr_t(args[eRsScript]);
1402b9c1b51eSKate Stone     if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
14034640cde1SColin Riley       auto rsm = m_scriptMappings[script_addr];
1404b9c1b51eSKate Stone       if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1405f4786785SAidan Dodds         auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1406*63e5fb76SJonas Devlieghere         LLDB_LOGF(log, "%s - Setting of '%s' within '%s' inferred",
1407*63e5fb76SJonas Devlieghere                   __FUNCTION__, rsg.m_name.AsCString(),
1408f4786785SAidan Dodds                   rsm->m_module->GetFileSpec().GetFilename().AsCString());
14094640cde1SColin Riley       }
14104640cde1SColin Riley     }
14114640cde1SColin Riley   }
14124640cde1SColin Riley }
14134640cde1SColin Riley 
141480af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
141580af0b9eSLuke Drummond                                                 ExecutionContext &exe_ctx) {
14164640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14174640cde1SColin Riley 
1418b9c1b51eSKate Stone   enum { eRsContext, eRsAlloc, eRsForceZero };
14194640cde1SColin Riley 
14201ee07253SSaleem Abdulrasool   std::array<ArgItem, 3> args{{
1421f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1422f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1423f4786785SAidan Dodds       ArgItem{ArgItem::eBool, 0},    // eRsForceZero
14241ee07253SSaleem Abdulrasool   }};
14254640cde1SColin Riley 
142680af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
142780af0b9eSLuke Drummond   if (!success) {
1428*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error while reading the function parameters",
1429b9c1b51eSKate Stone               __FUNCTION__);
143080af0b9eSLuke Drummond     return;
143182780287SAidan Dodds   }
14324640cde1SColin Riley 
1433*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1434*63e5fb76SJonas Devlieghere             __FUNCTION__, uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]),
1435*63e5fb76SJonas Devlieghere             uint64_t(args[eRsForceZero]));
143678f339d1SEwan Crawford 
14375d057637SLuke Drummond   AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
143878f339d1SEwan Crawford   if (alloc)
1439f4786785SAidan Dodds     alloc->context = uint64_t(args[eRsContext]);
14404640cde1SColin Riley }
14414640cde1SColin Riley 
144280af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
144380af0b9eSLuke Drummond                                                    ExecutionContext &exe_ctx) {
1444e69df382SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1445e69df382SEwan Crawford 
1446b9c1b51eSKate Stone   enum {
1447f4786785SAidan Dodds     eRsContext,
1448f4786785SAidan Dodds     eRsAlloc,
1449f4786785SAidan Dodds   };
1450e69df382SEwan Crawford 
14511ee07253SSaleem Abdulrasool   std::array<ArgItem, 2> args{{
1452f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1453f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
14541ee07253SSaleem Abdulrasool   }};
1455f4786785SAidan Dodds 
145680af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1457b9c1b51eSKate Stone   if (!success) {
1458*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error while reading the function parameters.",
1459b9c1b51eSKate Stone               __FUNCTION__);
1460b3f7f69dSAidan Dodds     return;
1461e69df382SEwan Crawford   }
1462e69df382SEwan Crawford 
1463*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1464b9c1b51eSKate Stone             uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1465e69df382SEwan Crawford 
1466b9c1b51eSKate Stone   for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1467d5b44036SJonas Devlieghere     auto &allocation_up = *iter; // get the unique pointer
1468d5b44036SJonas Devlieghere     if (allocation_up->address.isValid() &&
1469d5b44036SJonas Devlieghere         *allocation_up->address.get() == addr_t(args[eRsAlloc])) {
1470e69df382SEwan Crawford       m_allocations.erase(iter);
1471*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - deleted allocation entry.", __FUNCTION__);
1472e69df382SEwan Crawford       return;
1473e69df382SEwan Crawford     }
1474e69df382SEwan Crawford   }
1475e69df382SEwan Crawford 
1476*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - couldn't find destroyed allocation.", __FUNCTION__);
1477e69df382SEwan Crawford }
1478e69df382SEwan Crawford 
147980af0b9eSLuke Drummond void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
148080af0b9eSLuke Drummond                                             ExecutionContext &exe_ctx) {
14814640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14824640cde1SColin Riley 
148397206d57SZachary Turner   Status err;
148480af0b9eSLuke Drummond   Process *process = exe_ctx.GetProcessPtr();
14854640cde1SColin Riley 
1486b9c1b51eSKate Stone   enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
14874640cde1SColin Riley 
1488b9c1b51eSKate Stone   std::array<ArgItem, 4> args{
1489b9c1b51eSKate Stone       {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
14901ee07253SSaleem Abdulrasool        ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
149180af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1492b9c1b51eSKate Stone   if (!success) {
1493*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error while reading the function parameters.",
1494b9c1b51eSKate Stone               __FUNCTION__);
149582780287SAidan Dodds     return;
149682780287SAidan Dodds   }
149782780287SAidan Dodds 
149880af0b9eSLuke Drummond   std::string res_name;
149980af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
150080af0b9eSLuke Drummond   if (err.Fail()) {
1501*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error reading res_name: %s.", __FUNCTION__,
150280af0b9eSLuke Drummond               err.AsCString());
15034640cde1SColin Riley   }
15044640cde1SColin Riley 
150580af0b9eSLuke Drummond   std::string cache_dir;
150680af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
150780af0b9eSLuke Drummond   if (err.Fail()) {
1508*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error reading cache_dir: %s.", __FUNCTION__,
150980af0b9eSLuke Drummond               err.AsCString());
15104640cde1SColin Riley   }
15114640cde1SColin Riley 
1512*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1513*63e5fb76SJonas Devlieghere             __FUNCTION__, uint64_t(args[eRsContext]), uint64_t(args[eRsScript]),
1514*63e5fb76SJonas Devlieghere             res_name.c_str(), cache_dir.c_str());
15154640cde1SColin Riley 
151680af0b9eSLuke Drummond   if (res_name.size() > 0) {
15174640cde1SColin Riley     StreamString strm;
151880af0b9eSLuke Drummond     strm.Printf("librs.%s.so", res_name.c_str());
15194640cde1SColin Riley 
1520f4786785SAidan Dodds     ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1521b9c1b51eSKate Stone     if (script) {
152278f339d1SEwan Crawford       script->type = ScriptDetails::eScriptC;
152380af0b9eSLuke Drummond       script->cache_dir = cache_dir;
152480af0b9eSLuke Drummond       script->res_name = res_name;
1525c156427dSZachary Turner       script->shared_lib = strm.GetString();
1526f4786785SAidan Dodds       script->context = addr_t(args[eRsContext]);
152778f339d1SEwan Crawford     }
15284640cde1SColin Riley 
1529*63e5fb76SJonas Devlieghere     LLDB_LOGF(log,
1530*63e5fb76SJonas Devlieghere               "%s - '%s' tagged with context 0x%" PRIx64
1531b9c1b51eSKate Stone               " and script 0x%" PRIx64 ".",
1532b9c1b51eSKate Stone               __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1533b9c1b51eSKate Stone               uint64_t(args[eRsScript]));
1534b9c1b51eSKate Stone   } else if (log) {
1535*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - resource name invalid, Script not tagged.",
1536*63e5fb76SJonas Devlieghere               __FUNCTION__);
15374640cde1SColin Riley   }
15384640cde1SColin Riley }
15394640cde1SColin Riley 
1540b9c1b51eSKate Stone void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1541b9c1b51eSKate Stone                                            ModuleKind kind) {
15424640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
15434640cde1SColin Riley 
1544b9c1b51eSKate Stone   if (!module) {
15454640cde1SColin Riley     return;
15464640cde1SColin Riley   }
15474640cde1SColin Riley 
154882780287SAidan Dodds   Target &target = GetProcess()->GetTarget();
154921fed052SAidan Dodds   const llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
155082780287SAidan Dodds 
155180af0b9eSLuke Drummond   if (machine != llvm::Triple::ArchType::x86 &&
155280af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::arm &&
155380af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::aarch64 &&
155480af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mipsel &&
155580af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mips64el &&
155680af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::x86_64) {
1557*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - unable to hook runtime functions.", __FUNCTION__);
15584640cde1SColin Riley     return;
15594640cde1SColin Riley   }
15604640cde1SColin Riley 
156121fed052SAidan Dodds   const uint32_t target_ptr_size =
156221fed052SAidan Dodds       target.GetArchitecture().GetAddressByteSize();
156321fed052SAidan Dodds 
156421fed052SAidan Dodds   std::array<bool, s_runtimeHookCount> hook_placed;
156521fed052SAidan Dodds   hook_placed.fill(false);
15664640cde1SColin Riley 
1567b9c1b51eSKate Stone   for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
15684640cde1SColin Riley     const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1569b9c1b51eSKate Stone     if (hook_defn->kind != kind) {
15704640cde1SColin Riley       continue;
15714640cde1SColin Riley     }
15724640cde1SColin Riley 
157380af0b9eSLuke Drummond     const char *symbol_name = (target_ptr_size == 4)
157480af0b9eSLuke Drummond                                   ? hook_defn->symbol_name_m32
1575b9c1b51eSKate Stone                                   : hook_defn->symbol_name_m64;
157682780287SAidan Dodds 
1577b9c1b51eSKate Stone     const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1578b9c1b51eSKate Stone         ConstString(symbol_name), eSymbolTypeCode);
1579b9c1b51eSKate Stone     if (!sym) {
1580b9c1b51eSKate Stone       if (log) {
1581*63e5fb76SJonas Devlieghere         LLDB_LOGF(log, "%s - symbol '%s' related to the function %s not found",
1582b3f7f69dSAidan Dodds                   __FUNCTION__, symbol_name, hook_defn->name);
158382780287SAidan Dodds       }
158482780287SAidan Dodds       continue;
158582780287SAidan Dodds     }
15864640cde1SColin Riley 
1587358cf1eaSGreg Clayton     addr_t addr = sym->GetLoadAddress(&target);
1588b9c1b51eSKate Stone     if (addr == LLDB_INVALID_ADDRESS) {
1589*63e5fb76SJonas Devlieghere       LLDB_LOGF(log,
1590*63e5fb76SJonas Devlieghere                 "%s - unable to resolve the address of hook function '%s' "
1591b9c1b51eSKate Stone                 "with symbol '%s'.",
1592b3f7f69dSAidan Dodds                 __FUNCTION__, hook_defn->name, symbol_name);
15934640cde1SColin Riley       continue;
1594b9c1b51eSKate Stone     } else {
1595*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - function %s, address resolved at 0x%" PRIx64,
1596b3f7f69dSAidan Dodds                 __FUNCTION__, hook_defn->name, addr);
159782780287SAidan Dodds     }
15984640cde1SColin Riley 
15994640cde1SColin Riley     RuntimeHookSP hook(new RuntimeHook());
16004640cde1SColin Riley     hook->address = addr;
16014640cde1SColin Riley     hook->defn = hook_defn;
16024640cde1SColin Riley     hook->bp_sp = target.CreateBreakpoint(addr, true, false);
16034640cde1SColin Riley     hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
16044640cde1SColin Riley     m_runtimeHooks[addr] = hook;
1605b9c1b51eSKate Stone     if (log) {
1606*63e5fb76SJonas Devlieghere       LLDB_LOGF(log,
1607*63e5fb76SJonas Devlieghere                 "%s - successfully hooked '%s' in '%s' version %" PRIu64
1608b9c1b51eSKate Stone                 " at 0x%" PRIx64 ".",
1609b9c1b51eSKate Stone                 __FUNCTION__, hook_defn->name,
1610b9c1b51eSKate Stone                 module->GetFileSpec().GetFilename().AsCString(),
1611b3f7f69dSAidan Dodds                 (uint64_t)hook_defn->version, (uint64_t)addr);
16124640cde1SColin Riley     }
161321fed052SAidan Dodds     hook_placed[idx] = true;
161421fed052SAidan Dodds   }
161521fed052SAidan Dodds 
161621fed052SAidan Dodds   // log any unhooked function
161721fed052SAidan Dodds   if (log) {
161821fed052SAidan Dodds     for (size_t i = 0; i < hook_placed.size(); ++i) {
161921fed052SAidan Dodds       if (hook_placed[i])
162021fed052SAidan Dodds         continue;
162121fed052SAidan Dodds       const HookDefn &hook_defn = s_runtimeHookDefns[i];
162221fed052SAidan Dodds       if (hook_defn.kind != kind)
162321fed052SAidan Dodds         continue;
1624*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - function %s was not hooked", __FUNCTION__,
162521fed052SAidan Dodds                 hook_defn.name);
162621fed052SAidan Dodds     }
16274640cde1SColin Riley   }
16284640cde1SColin Riley }
16294640cde1SColin Riley 
1630b9c1b51eSKate Stone void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
16314640cde1SColin Riley   if (!rsmodule_sp)
16324640cde1SColin Riley     return;
16334640cde1SColin Riley 
16344640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
16354640cde1SColin Riley 
16364640cde1SColin Riley   const ModuleSP module = rsmodule_sp->m_module;
16374640cde1SColin Riley   const FileSpec &file = module->GetPlatformFileSpec();
16384640cde1SColin Riley 
163905097246SAdrian Prantl   // Iterate over all of the scripts that we currently know of. Note: We cant
164005097246SAdrian Prantl   // push or pop to m_scripts here or it may invalidate rs_script.
1641b9c1b51eSKate Stone   for (const auto &rs_script : m_scripts) {
164278f339d1SEwan Crawford     // Extract the expected .so file path for this script.
164380af0b9eSLuke Drummond     std::string shared_lib;
164480af0b9eSLuke Drummond     if (!rs_script->shared_lib.get(shared_lib))
164578f339d1SEwan Crawford       continue;
164678f339d1SEwan Crawford 
164778f339d1SEwan Crawford     // Only proceed if the module that has loaded corresponds to this script.
164880af0b9eSLuke Drummond     if (file.GetFilename() != ConstString(shared_lib.c_str()))
164978f339d1SEwan Crawford       continue;
165078f339d1SEwan Crawford 
165178f339d1SEwan Crawford     // Obtain the script address which we use as a key.
165278f339d1SEwan Crawford     lldb::addr_t script;
165378f339d1SEwan Crawford     if (!rs_script->script.get(script))
165478f339d1SEwan Crawford       continue;
165578f339d1SEwan Crawford 
165678f339d1SEwan Crawford     // If we have a script mapping for the current script.
1657b9c1b51eSKate Stone     if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
165878f339d1SEwan Crawford       // if the module we have stored is different to the one we just received.
1659b9c1b51eSKate Stone       if (m_scriptMappings[script] != rsmodule_sp) {
1660*63e5fb76SJonas Devlieghere         LLDB_LOGF(
1661*63e5fb76SJonas Devlieghere             log,
1662b9c1b51eSKate Stone             "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1663b9c1b51eSKate Stone             __FUNCTION__, (uint64_t)script,
1664b9c1b51eSKate Stone             rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
16654640cde1SColin Riley       }
16664640cde1SColin Riley     }
166778f339d1SEwan Crawford     // We don't have a script mapping for the current script.
1668b9c1b51eSKate Stone     else {
166978f339d1SEwan Crawford       // Obtain the script resource name.
167080af0b9eSLuke Drummond       std::string res_name;
167180af0b9eSLuke Drummond       if (rs_script->res_name.get(res_name))
167278f339d1SEwan Crawford         // Set the modules resource name.
167380af0b9eSLuke Drummond         rsmodule_sp->m_resname = res_name;
167478f339d1SEwan Crawford       // Add Script/Module pair to map.
167578f339d1SEwan Crawford       m_scriptMappings[script] = rsmodule_sp;
1676*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1677b9c1b51eSKate Stone                 __FUNCTION__, (uint64_t)script,
1678b9c1b51eSKate Stone                 rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
16794640cde1SColin Riley     }
16804640cde1SColin Riley   }
16814640cde1SColin Riley }
16824640cde1SColin Riley 
1683b9c1b51eSKate Stone // Uses the Target API to evaluate the expression passed as a parameter to the
168480af0b9eSLuke Drummond // function The result of that expression is returned an unsigned 64 bit int,
168580af0b9eSLuke Drummond // via the result* parameter. Function returns true on success, and false on
168680af0b9eSLuke Drummond // failure
168780af0b9eSLuke Drummond bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1688b9c1b51eSKate Stone                                            StackFrame *frame_ptr,
1689b9c1b51eSKate Stone                                            uint64_t *result) {
169015f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1691*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s(%s)", __FUNCTION__, expr);
169215f2bd95SEwan Crawford 
169315f2bd95SEwan Crawford   ValueObjectSP expr_result;
16948433fdbeSAidan Dodds   EvaluateExpressionOptions options;
16958433fdbeSAidan Dodds   options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
169615f2bd95SEwan Crawford   // Perform the actual expression evaluation
169780af0b9eSLuke Drummond   auto &target = GetProcess()->GetTarget();
169880af0b9eSLuke Drummond   target.EvaluateExpression(expr, frame_ptr, expr_result, options);
169915f2bd95SEwan Crawford 
1700b9c1b51eSKate Stone   if (!expr_result) {
1701*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s: couldn't evaluate expression.", __FUNCTION__);
170215f2bd95SEwan Crawford     return false;
170315f2bd95SEwan Crawford   }
170415f2bd95SEwan Crawford 
170515f2bd95SEwan Crawford   // The result of the expression is invalid
1706b9c1b51eSKate Stone   if (!expr_result->GetError().Success()) {
170797206d57SZachary Turner     Status err = expr_result->GetError();
170880af0b9eSLuke Drummond     // Expression returned is void, so this is actually a success
1709a35912daSKrasimir Georgiev     if (err.GetError() == UserExpression::kNoResult) {
1710*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - expression returned void.", __FUNCTION__);
171115f2bd95SEwan Crawford 
171215f2bd95SEwan Crawford       result = nullptr;
171315f2bd95SEwan Crawford       return true;
171415f2bd95SEwan Crawford     }
171515f2bd95SEwan Crawford 
1716*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error evaluating expression result: %s", __FUNCTION__,
1717b3f7f69dSAidan Dodds               err.AsCString());
171815f2bd95SEwan Crawford     return false;
171915f2bd95SEwan Crawford   }
172015f2bd95SEwan Crawford 
172115f2bd95SEwan Crawford   bool success = false;
172280af0b9eSLuke Drummond   // We only read the result as an uint32_t.
172380af0b9eSLuke Drummond   *result = expr_result->GetValueAsUnsigned(0, &success);
172415f2bd95SEwan Crawford 
1725b9c1b51eSKate Stone   if (!success) {
1726*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - couldn't convert expression result to uint32_t",
1727b9c1b51eSKate Stone               __FUNCTION__);
172815f2bd95SEwan Crawford     return false;
172915f2bd95SEwan Crawford   }
173015f2bd95SEwan Crawford 
173115f2bd95SEwan Crawford   return true;
173215f2bd95SEwan Crawford }
173315f2bd95SEwan Crawford 
1734b9c1b51eSKate Stone namespace {
1735836d9651SEwan Crawford // Used to index expression format strings
1736b9c1b51eSKate Stone enum ExpressionStrings {
1737836d9651SEwan Crawford   eExprGetOffsetPtr = 0,
1738836d9651SEwan Crawford   eExprAllocGetType,
1739836d9651SEwan Crawford   eExprTypeDimX,
1740836d9651SEwan Crawford   eExprTypeDimY,
1741836d9651SEwan Crawford   eExprTypeDimZ,
1742836d9651SEwan Crawford   eExprTypeElemPtr,
1743836d9651SEwan Crawford   eExprElementType,
1744836d9651SEwan Crawford   eExprElementKind,
1745836d9651SEwan Crawford   eExprElementVec,
1746836d9651SEwan Crawford   eExprElementFieldCount,
1747836d9651SEwan Crawford   eExprSubelementsId,
1748836d9651SEwan Crawford   eExprSubelementsName,
1749ea0636b5SEwan Crawford   eExprSubelementsArrSize,
1750ea0636b5SEwan Crawford 
175180af0b9eSLuke Drummond   _eExprLast // keep at the end, implicit size of the array runtime_expressions
1752836d9651SEwan Crawford };
175315f2bd95SEwan Crawford 
1754ea0636b5SEwan Crawford // max length of an expanded expression
1755ea0636b5SEwan Crawford const int jit_max_expr_size = 512;
1756ea0636b5SEwan Crawford 
1757ea0636b5SEwan Crawford // Retrieve the string to JIT for the given expression
175836d783ebSDavid Gross #define JIT_TEMPLATE_CONTEXT "void* ctxt = (void*)rsDebugGetContextWrapper(0x%" PRIx64 "); "
1759b9c1b51eSKate Stone const char *JITTemplate(ExpressionStrings e) {
1760ea0636b5SEwan Crawford   // Format strings containing the expressions we may need to evaluate.
176180af0b9eSLuke Drummond   static std::array<const char *, _eExprLast> runtime_expressions = {
1762b9c1b51eSKate Stone       {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1763b9c1b51eSKate Stone        "(int*)_"
1764b9c1b51eSKate Stone        "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1765b9c1b51eSKate Stone        "CubemapFace"
176636d783ebSDavid Gross        "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)", // eExprGetOffsetPtr
176715f2bd95SEwan Crawford 
176815f2bd95SEwan Crawford        // Type* rsaAllocationGetType(Context*, Allocation*)
176936d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "(void*)rsaAllocationGetType(ctxt, 0x%" PRIx64 ")", // eExprAllocGetType
177015f2bd95SEwan Crawford 
177180af0b9eSLuke Drummond        // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
177280af0b9eSLuke Drummond        // data in the following way mHal.state.dimX; mHal.state.dimY;
177305097246SAdrian Prantl        // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement;
177405097246SAdrian Prantl        // into typeData Need to specify 32 or 64 bit for uint_t since this
177505097246SAdrian Prantl        // differs between devices
177636d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
177736d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
177836d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[0]", // eExprTypeDimX
177936d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
178036d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
178136d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[1]", // eExprTypeDimY
178236d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
178336d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
178436d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[2]", // eExprTypeDimZ
178536d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
178636d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
178736d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[5]", // eExprTypeElemPtr
178815f2bd95SEwan Crawford 
178915f2bd95SEwan Crawford        // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1790b9c1b51eSKate Stone        // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1791b9c1b51eSKate Stone        // elemData
179236d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
179336d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
179436d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[0]", // eExprElementType
179536d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
179636d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
179736d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[1]", // eExprElementKind
179836d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
179936d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
180036d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[3]", // eExprElementVec
180136d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
180236d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
180336d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[4]", // eExprElementFieldCount
18048b244e21SEwan Crawford 
1805b9c1b51eSKate Stone        // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
180680af0b9eSLuke Drummond        // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1807b9c1b51eSKate Stone        // Needed for Allocations of structs to gather details about
180880af0b9eSLuke Drummond        // fields/Subelements Element* of field
180936d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1810b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
181136d783ebSDavid Gross        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
181236d783ebSDavid Gross        ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]", // eExprSubelementsId
18138b244e21SEwan Crawford 
1814577570b4SAidan Dodds        // Name of field
181536d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1816b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
181736d783ebSDavid Gross        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
181836d783ebSDavid Gross        ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]", // eExprSubelementsName
18198b244e21SEwan Crawford 
1820577570b4SAidan Dodds        // Array size of field
182136d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1822b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
182336d783ebSDavid Gross        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
182436d783ebSDavid Gross        ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}}; // eExprSubelementsArrSize
1825ea0636b5SEwan Crawford 
182680af0b9eSLuke Drummond   return runtime_expressions[e];
1827ea0636b5SEwan Crawford }
1828ea0636b5SEwan Crawford } // end of the anonymous namespace
1829ea0636b5SEwan Crawford 
183005097246SAdrian Prantl // JITs the RS runtime for the internal data pointer of an allocation. Is
183105097246SAdrian Prantl // passed x,y,z coordinates for the pointer to a specific element. Then sets
183205097246SAdrian Prantl // the data_ptr member in Allocation with the result. Returns true on success,
183305097246SAdrian Prantl // false otherwise
183480af0b9eSLuke Drummond bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1835b9c1b51eSKate Stone                                          StackFrame *frame_ptr, uint32_t x,
1836b9c1b51eSKate Stone                                          uint32_t y, uint32_t z) {
183715f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
183815f2bd95SEwan Crawford 
183980af0b9eSLuke Drummond   if (!alloc->address.isValid()) {
1840*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
184115f2bd95SEwan Crawford     return false;
184215f2bd95SEwan Crawford   }
184315f2bd95SEwan Crawford 
184480af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
184580af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
184615f2bd95SEwan Crawford 
184780af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
184880af0b9eSLuke Drummond                          *alloc->address.get(), x, y, z);
184980af0b9eSLuke Drummond   if (written < 0) {
1850*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
185115f2bd95SEwan Crawford     return false;
185280af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
1853*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
185415f2bd95SEwan Crawford     return false;
185515f2bd95SEwan Crawford   }
185615f2bd95SEwan Crawford 
185715f2bd95SEwan Crawford   uint64_t result = 0;
185880af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
185915f2bd95SEwan Crawford     return false;
186015f2bd95SEwan Crawford 
186180af0b9eSLuke Drummond   addr_t data_ptr = static_cast<lldb::addr_t>(result);
186280af0b9eSLuke Drummond   alloc->data_ptr = data_ptr;
186315f2bd95SEwan Crawford 
186415f2bd95SEwan Crawford   return true;
186515f2bd95SEwan Crawford }
186615f2bd95SEwan Crawford 
186715f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
186880af0b9eSLuke Drummond // Then sets the type_ptr member in Allocation with the result. Returns true on
186980af0b9eSLuke Drummond // success, false otherwise
187080af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1871b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
187215f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
187315f2bd95SEwan Crawford 
187480af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->context.isValid()) {
1875*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
187615f2bd95SEwan Crawford     return false;
187715f2bd95SEwan Crawford   }
187815f2bd95SEwan Crawford 
187980af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprAllocGetType);
188080af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
188115f2bd95SEwan Crawford 
188280af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
188380af0b9eSLuke Drummond                          *alloc->context.get(), *alloc->address.get());
188480af0b9eSLuke Drummond   if (written < 0) {
1885*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
188615f2bd95SEwan Crawford     return false;
188780af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
1888*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
188915f2bd95SEwan Crawford     return false;
189015f2bd95SEwan Crawford   }
189115f2bd95SEwan Crawford 
189215f2bd95SEwan Crawford   uint64_t result = 0;
189380af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
189415f2bd95SEwan Crawford     return false;
189515f2bd95SEwan Crawford 
189615f2bd95SEwan Crawford   addr_t type_ptr = static_cast<lldb::addr_t>(result);
189780af0b9eSLuke Drummond   alloc->type_ptr = type_ptr;
189815f2bd95SEwan Crawford 
189915f2bd95SEwan Crawford   return true;
190015f2bd95SEwan Crawford }
190115f2bd95SEwan Crawford 
1902b9c1b51eSKate Stone // JITs the RS runtime for information about the dimensions and type of an
190305097246SAdrian Prantl // allocation Then sets dimension and element_ptr members in Allocation with
190405097246SAdrian Prantl // the result. Returns true on success, false otherwise
190580af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1906b9c1b51eSKate Stone                                         StackFrame *frame_ptr) {
190715f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
190815f2bd95SEwan Crawford 
190980af0b9eSLuke Drummond   if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
1910*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - Failed to find allocation details.", __FUNCTION__);
191115f2bd95SEwan Crawford     return false;
191215f2bd95SEwan Crawford   }
191315f2bd95SEwan Crawford 
191415f2bd95SEwan Crawford   // Expression is different depending on if device is 32 or 64 bit
191580af0b9eSLuke Drummond   uint32_t target_ptr_size =
1916b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
191780af0b9eSLuke Drummond   const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
191815f2bd95SEwan Crawford 
191915f2bd95SEwan Crawford   // We want 4 elements from packed data
1920b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
19214c1d6ee8SJonas Devlieghere   static_assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1),
1922b9c1b51eSKate Stone                 "Invalid number of expressions");
192315f2bd95SEwan Crawford 
192480af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
192515f2bd95SEwan Crawford   uint64_t results[num_exprs];
192615f2bd95SEwan Crawford 
1927b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; ++i) {
192880af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
192936d783ebSDavid Gross     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str,
193036d783ebSDavid Gross                            *alloc->context.get(), bits, *alloc->type_ptr.get());
193180af0b9eSLuke Drummond     if (written < 0) {
1932*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
193315f2bd95SEwan Crawford       return false;
193480af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
1935*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
193615f2bd95SEwan Crawford       return false;
193715f2bd95SEwan Crawford     }
193815f2bd95SEwan Crawford 
193915f2bd95SEwan Crawford     // Perform expression evaluation
194080af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
194115f2bd95SEwan Crawford       return false;
194215f2bd95SEwan Crawford   }
194315f2bd95SEwan Crawford 
194415f2bd95SEwan Crawford   // Assign results to allocation members
194515f2bd95SEwan Crawford   AllocationDetails::Dimension dims;
194615f2bd95SEwan Crawford   dims.dim_1 = static_cast<uint32_t>(results[0]);
194715f2bd95SEwan Crawford   dims.dim_2 = static_cast<uint32_t>(results[1]);
194815f2bd95SEwan Crawford   dims.dim_3 = static_cast<uint32_t>(results[2]);
194980af0b9eSLuke Drummond   alloc->dimension = dims;
195015f2bd95SEwan Crawford 
195180af0b9eSLuke Drummond   addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
195280af0b9eSLuke Drummond   alloc->element.element_ptr = element_ptr;
195315f2bd95SEwan Crawford 
1954*63e5fb76SJonas Devlieghere   LLDB_LOGF(log,
1955*63e5fb76SJonas Devlieghere             "%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
1956b9c1b51eSKate Stone             ") Element*: 0x%" PRIx64 ".",
195780af0b9eSLuke Drummond             __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
195815f2bd95SEwan Crawford 
195915f2bd95SEwan Crawford   return true;
196015f2bd95SEwan Crawford }
196115f2bd95SEwan Crawford 
196280af0b9eSLuke Drummond // JITs the RS runtime for information about the Element of an allocation Then
196380af0b9eSLuke Drummond // sets type, type_vec_size, field_count and type_kind members in Element with
196480af0b9eSLuke Drummond // the result. Returns true on success, false otherwise
1965b9c1b51eSKate Stone bool RenderScriptRuntime::JITElementPacked(Element &elem,
1966b9c1b51eSKate Stone                                            const lldb::addr_t context,
1967b9c1b51eSKate Stone                                            StackFrame *frame_ptr) {
196815f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
196915f2bd95SEwan Crawford 
1970b9c1b51eSKate Stone   if (!elem.element_ptr.isValid()) {
1971*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
197215f2bd95SEwan Crawford     return false;
197315f2bd95SEwan Crawford   }
197415f2bd95SEwan Crawford 
19758b244e21SEwan Crawford   // We want 4 elements from packed data
1976b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
19774c1d6ee8SJonas Devlieghere   static_assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1),
1978b9c1b51eSKate Stone                 "Invalid number of expressions");
197915f2bd95SEwan Crawford 
198080af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
198115f2bd95SEwan Crawford   uint64_t results[num_exprs];
198215f2bd95SEwan Crawford 
1983b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; i++) {
198480af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
198580af0b9eSLuke Drummond     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
198680af0b9eSLuke Drummond                            *elem.element_ptr.get());
198780af0b9eSLuke Drummond     if (written < 0) {
1988*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
198915f2bd95SEwan Crawford       return false;
199080af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
1991*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
199215f2bd95SEwan Crawford       return false;
199315f2bd95SEwan Crawford     }
199415f2bd95SEwan Crawford 
199515f2bd95SEwan Crawford     // Perform expression evaluation
199680af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
199715f2bd95SEwan Crawford       return false;
199815f2bd95SEwan Crawford   }
199915f2bd95SEwan Crawford 
200015f2bd95SEwan Crawford   // Assign results to allocation members
20018b244e21SEwan Crawford   elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
2002b9c1b51eSKate Stone   elem.type_kind =
2003b9c1b51eSKate Stone       static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
20048b244e21SEwan Crawford   elem.type_vec_size = static_cast<uint32_t>(results[2]);
20058b244e21SEwan Crawford   elem.field_count = static_cast<uint32_t>(results[3]);
200615f2bd95SEwan Crawford 
2007*63e5fb76SJonas Devlieghere   LLDB_LOGF(log,
2008*63e5fb76SJonas Devlieghere             "%s - data type %" PRIu32 ", pixel type %" PRIu32
2009b9c1b51eSKate Stone             ", vector size %" PRIu32 ", field count %" PRIu32,
2010b9c1b51eSKate Stone             __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
2011b9c1b51eSKate Stone             *elem.type_vec_size.get(), *elem.field_count.get());
20128b244e21SEwan Crawford 
2013b9c1b51eSKate Stone   // If this Element has subelements then JIT rsaElementGetSubElements() for
2014b9c1b51eSKate Stone   // details about its fields
2015a6682a41SJonas Devlieghere   return !(*elem.field_count.get() > 0 &&
2016a6682a41SJonas Devlieghere            !JITSubelements(elem, context, frame_ptr));
20178b244e21SEwan Crawford }
20188b244e21SEwan Crawford 
2019b9c1b51eSKate Stone // JITs the RS runtime for information about the subelements/fields of a struct
202080af0b9eSLuke Drummond // allocation This is necessary for infering the struct type so we can pretty
202180af0b9eSLuke Drummond // print the allocation's contents. Returns true on success, false otherwise
2022b9c1b51eSKate Stone bool RenderScriptRuntime::JITSubelements(Element &elem,
2023b9c1b51eSKate Stone                                          const lldb::addr_t context,
2024b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
20258b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
20268b244e21SEwan Crawford 
2027b9c1b51eSKate Stone   if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
2028*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
20298b244e21SEwan Crawford     return false;
20308b244e21SEwan Crawford   }
20318b244e21SEwan Crawford 
20328b244e21SEwan Crawford   const short num_exprs = 3;
20334c1d6ee8SJonas Devlieghere   static_assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1),
2034b9c1b51eSKate Stone                 "Invalid number of expressions");
20358b244e21SEwan Crawford 
2036ea0636b5SEwan Crawford   char expr_buffer[jit_max_expr_size];
20378b244e21SEwan Crawford   uint64_t results;
20388b244e21SEwan Crawford 
20398b244e21SEwan Crawford   // Iterate over struct fields.
20408b244e21SEwan Crawford   const uint32_t field_count = *elem.field_count.get();
2041b9c1b51eSKate Stone   for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
20428b244e21SEwan Crawford     Element child;
2043b9c1b51eSKate Stone     for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
204480af0b9eSLuke Drummond       const char *fmt_str =
2045b9c1b51eSKate Stone           JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
204680af0b9eSLuke Drummond       int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
204736d783ebSDavid Gross                              context, field_count, field_count, field_count,
204880af0b9eSLuke Drummond                              *elem.element_ptr.get(), field_count, field_index);
204980af0b9eSLuke Drummond       if (written < 0) {
2050*63e5fb76SJonas Devlieghere         LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
20518b244e21SEwan Crawford         return false;
205280af0b9eSLuke Drummond       } else if (written >= jit_max_expr_size) {
2053*63e5fb76SJonas Devlieghere         LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
20548b244e21SEwan Crawford         return false;
20558b244e21SEwan Crawford       }
20568b244e21SEwan Crawford 
20578b244e21SEwan Crawford       // Perform expression evaluation
20588b244e21SEwan Crawford       if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
20598b244e21SEwan Crawford         return false;
20608b244e21SEwan Crawford 
2061*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
20628b244e21SEwan Crawford 
2063b9c1b51eSKate Stone       switch (expr_index) {
20648b244e21SEwan Crawford       case 0: // Element* of child
20658b244e21SEwan Crawford         child.element_ptr = static_cast<addr_t>(results);
20668b244e21SEwan Crawford         break;
20678b244e21SEwan Crawford       case 1: // Name of child
20688b244e21SEwan Crawford       {
20698b244e21SEwan Crawford         lldb::addr_t address = static_cast<addr_t>(results);
207097206d57SZachary Turner         Status err;
20718b244e21SEwan Crawford         std::string name;
20728b244e21SEwan Crawford         GetProcess()->ReadCStringFromMemory(address, name, err);
20738b244e21SEwan Crawford         if (!err.Fail())
20748b244e21SEwan Crawford           child.type_name = ConstString(name);
2075b9c1b51eSKate Stone         else {
2076*63e5fb76SJonas Devlieghere           LLDB_LOGF(log, "%s - warning: Couldn't read field name.",
2077b9c1b51eSKate Stone                     __FUNCTION__);
20788b244e21SEwan Crawford         }
20798b244e21SEwan Crawford         break;
20808b244e21SEwan Crawford       }
20818b244e21SEwan Crawford       case 2: // Array size of child
20828b244e21SEwan Crawford         child.array_size = static_cast<uint32_t>(results);
20838b244e21SEwan Crawford         break;
20848b244e21SEwan Crawford       }
20858b244e21SEwan Crawford     }
20868b244e21SEwan Crawford 
20878b244e21SEwan Crawford     // We need to recursively JIT each Element field of the struct since
20888b244e21SEwan Crawford     // structs can be nested inside structs.
20898b244e21SEwan Crawford     if (!JITElementPacked(child, context, frame_ptr))
20908b244e21SEwan Crawford       return false;
20918b244e21SEwan Crawford     elem.children.push_back(child);
20928b244e21SEwan Crawford   }
20938b244e21SEwan Crawford 
2094b9c1b51eSKate Stone   // Try to infer the name of the struct type so we can pretty print the
2095b9c1b51eSKate Stone   // allocation contents.
20968b244e21SEwan Crawford   FindStructTypeName(elem, frame_ptr);
209715f2bd95SEwan Crawford 
209815f2bd95SEwan Crawford   return true;
209915f2bd95SEwan Crawford }
210015f2bd95SEwan Crawford 
2101a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
2102b9c1b51eSKate Stone // The `elem_size` parameter represents the size of a single element, including
210380af0b9eSLuke Drummond // padding. Which is needed as an offset from the last element pointer. Using
210480af0b9eSLuke Drummond // this offset minus the starting address we can calculate the size of the
210580af0b9eSLuke Drummond // allocation. Returns true on success, false otherwise
210680af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
2107b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
2108a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2109a0f08674SEwan Crawford 
211080af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
211180af0b9eSLuke Drummond       !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
2112*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
2113a0f08674SEwan Crawford     return false;
2114a0f08674SEwan Crawford   }
2115a0f08674SEwan Crawford 
2116a0f08674SEwan Crawford   // Find dimensions
211780af0b9eSLuke Drummond   uint32_t dim_x = alloc->dimension.get()->dim_1;
211880af0b9eSLuke Drummond   uint32_t dim_y = alloc->dimension.get()->dim_2;
211980af0b9eSLuke Drummond   uint32_t dim_z = alloc->dimension.get()->dim_3;
2120a0f08674SEwan Crawford 
2121b9c1b51eSKate Stone   // Our plan of jitting the last element address doesn't seem to work for
212280af0b9eSLuke Drummond   // struct Allocations` Instead try to infer the size ourselves without any
212380af0b9eSLuke Drummond   // inter element padding.
212480af0b9eSLuke Drummond   if (alloc->element.children.size() > 0) {
2125b9c1b51eSKate Stone     if (dim_x == 0)
2126b9c1b51eSKate Stone       dim_x = 1;
2127b9c1b51eSKate Stone     if (dim_y == 0)
2128b9c1b51eSKate Stone       dim_y = 1;
2129b9c1b51eSKate Stone     if (dim_z == 0)
2130b9c1b51eSKate Stone       dim_z = 1;
21318b244e21SEwan Crawford 
213280af0b9eSLuke Drummond     alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
21338b244e21SEwan Crawford 
2134*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - inferred size of struct allocation %" PRIu32 ".",
213580af0b9eSLuke Drummond               __FUNCTION__, *alloc->size.get());
21368b244e21SEwan Crawford     return true;
21378b244e21SEwan Crawford   }
21388b244e21SEwan Crawford 
213980af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
214080af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
21418b244e21SEwan Crawford 
2142a0f08674SEwan Crawford   // Calculate last element
2143a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 0 : dim_x - 1;
2144a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 0 : dim_y - 1;
2145a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 0 : dim_z - 1;
2146a0f08674SEwan Crawford 
214780af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
214880af0b9eSLuke Drummond                          *alloc->address.get(), dim_x, dim_y, dim_z);
214980af0b9eSLuke Drummond   if (written < 0) {
2150*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
2151a0f08674SEwan Crawford     return false;
215280af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
2153*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
2154a0f08674SEwan Crawford     return false;
2155a0f08674SEwan Crawford   }
2156a0f08674SEwan Crawford 
2157a0f08674SEwan Crawford   uint64_t result = 0;
215880af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2159a0f08674SEwan Crawford     return false;
2160a0f08674SEwan Crawford 
2161a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2162a0f08674SEwan Crawford   // Find pointer to last element and add on size of an element
216380af0b9eSLuke Drummond   alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
216480af0b9eSLuke Drummond                 *alloc->element.datum_size.get();
2165a0f08674SEwan Crawford 
2166a0f08674SEwan Crawford   return true;
2167a0f08674SEwan Crawford }
2168a0f08674SEwan Crawford 
2169b9c1b51eSKate Stone // JITs the RS runtime for information about the stride between rows in the
217005097246SAdrian Prantl // allocation. This is done to detect padding, since allocated memory is
217105097246SAdrian Prantl // 16-byte aligned. Returns true on success, false otherwise
217280af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
2173b9c1b51eSKate Stone                                               StackFrame *frame_ptr) {
2174a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2175a0f08674SEwan Crawford 
217680af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
2177*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
2178a0f08674SEwan Crawford     return false;
2179a0f08674SEwan Crawford   }
2180a0f08674SEwan Crawford 
218180af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
218280af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
2183a0f08674SEwan Crawford 
218480af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
218580af0b9eSLuke Drummond                          *alloc->address.get(), 0, 1, 0);
218680af0b9eSLuke Drummond   if (written < 0) {
2187*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
2188a0f08674SEwan Crawford     return false;
218980af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
2190*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
2191a0f08674SEwan Crawford     return false;
2192a0f08674SEwan Crawford   }
2193a0f08674SEwan Crawford 
2194a0f08674SEwan Crawford   uint64_t result = 0;
219580af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2196a0f08674SEwan Crawford     return false;
2197a0f08674SEwan Crawford 
2198a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
219980af0b9eSLuke Drummond   alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
2200a0f08674SEwan Crawford 
2201a0f08674SEwan Crawford   return true;
2202a0f08674SEwan Crawford }
2203a0f08674SEwan Crawford 
220415f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
220580af0b9eSLuke Drummond bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2206b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
220715f2bd95SEwan Crawford   // GetOffsetPointer()
220880af0b9eSLuke Drummond   if (!JITDataPointer(alloc, frame_ptr))
220915f2bd95SEwan Crawford     return false;
221015f2bd95SEwan Crawford 
221115f2bd95SEwan Crawford   // rsaAllocationGetType()
221280af0b9eSLuke Drummond   if (!JITTypePointer(alloc, frame_ptr))
221315f2bd95SEwan Crawford     return false;
221415f2bd95SEwan Crawford 
221515f2bd95SEwan Crawford   // rsaTypeGetNativeData()
221680af0b9eSLuke Drummond   if (!JITTypePacked(alloc, frame_ptr))
221715f2bd95SEwan Crawford     return false;
221815f2bd95SEwan Crawford 
221915f2bd95SEwan Crawford   // rsaElementGetNativeData()
222080af0b9eSLuke Drummond   if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
222115f2bd95SEwan Crawford     return false;
222215f2bd95SEwan Crawford 
22238b244e21SEwan Crawford   // Sets the datum_size member in Element
222480af0b9eSLuke Drummond   SetElementSize(alloc->element);
22258b244e21SEwan Crawford 
222655232f09SEwan Crawford   // Use GetOffsetPointer() to infer size of the allocation
2227a6682a41SJonas Devlieghere   return JITAllocationSize(alloc, frame_ptr);
222855232f09SEwan Crawford }
222955232f09SEwan Crawford 
2230b9c1b51eSKate Stone // Function attempts to set the type_name member of the paramaterised Element
223105097246SAdrian Prantl // object. This string should be the name of the struct type the Element
223205097246SAdrian Prantl // represents. We need this string for pretty printing the Element to users.
2233b9c1b51eSKate Stone void RenderScriptRuntime::FindStructTypeName(Element &elem,
2234b9c1b51eSKate Stone                                              StackFrame *frame_ptr) {
22358b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
22368b244e21SEwan Crawford 
22378b244e21SEwan Crawford   if (!elem.type_name.IsEmpty()) // Name already set
22388b244e21SEwan Crawford     return;
22398b244e21SEwan Crawford   else
2240b9c1b51eSKate Stone     elem.type_name = Element::GetFallbackStructName(); // Default type name if
2241b9c1b51eSKate Stone                                                        // we don't succeed
22428b244e21SEwan Crawford 
22438b244e21SEwan Crawford   // Find all the global variables from the script rs modules
224480af0b9eSLuke Drummond   VariableList var_list;
22458b244e21SEwan Crawford   for (auto module_sp : m_rsmodules)
224695eae423SZachary Turner     module_sp->m_module->FindGlobalVariables(
224734cda14bSPavel Labath         RegularExpression(llvm::StringRef(".")), UINT32_MAX, var_list);
22488b244e21SEwan Crawford 
2249b9c1b51eSKate Stone   // Iterate over all the global variables looking for one with a matching type
225005097246SAdrian Prantl   // to the Element. We make the assumption a match exists since there needs to
225105097246SAdrian Prantl   // be a global variable to reflect the struct type back into java host code.
225280af0b9eSLuke Drummond   for (uint32_t i = 0; i < var_list.GetSize(); ++i) {
225380af0b9eSLuke Drummond     const VariableSP var_sp(var_list.GetVariableAtIndex(i));
22548b244e21SEwan Crawford     if (!var_sp)
22558b244e21SEwan Crawford       continue;
22568b244e21SEwan Crawford 
22578b244e21SEwan Crawford     ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
22588b244e21SEwan Crawford     if (!valobj_sp)
22598b244e21SEwan Crawford       continue;
22608b244e21SEwan Crawford 
22618b244e21SEwan Crawford     // Find the number of variable fields.
2262b9c1b51eSKate Stone     // If it has no fields, or more fields than our Element, then it can't be
226305097246SAdrian Prantl     // the struct we're looking for. Don't check for equality since RS can add
226405097246SAdrian Prantl     // extra struct members for padding.
22658b244e21SEwan Crawford     size_t num_children = valobj_sp->GetNumChildren();
22668b244e21SEwan Crawford     if (num_children > elem.children.size() || num_children == 0)
22678b244e21SEwan Crawford       continue;
22688b244e21SEwan Crawford 
226905097246SAdrian Prantl     // Iterate over children looking for members with matching field names. If
227005097246SAdrian Prantl     // all the field names match, this is likely the struct we want.
2271b9c1b51eSKate Stone     //   TODO: This could be made more robust by also checking children data
2272b9c1b51eSKate Stone     //   sizes, or array size
22738b244e21SEwan Crawford     bool found = true;
227480af0b9eSLuke Drummond     for (size_t i = 0; i < num_children; ++i) {
227580af0b9eSLuke Drummond       ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
227680af0b9eSLuke Drummond       if (!child || (child->GetName() != elem.children[i].type_name)) {
22778b244e21SEwan Crawford         found = false;
22788b244e21SEwan Crawford         break;
22798b244e21SEwan Crawford       }
22808b244e21SEwan Crawford     }
22818b244e21SEwan Crawford 
2282b9c1b51eSKate Stone     // RS can add extra struct members for padding in the format
2283b9c1b51eSKate Stone     // '#rs_padding_[0-9]+'
2284b9c1b51eSKate Stone     if (found && num_children < elem.children.size()) {
2285b3f7f69dSAidan Dodds       const uint32_t size_diff = elem.children.size() - num_children;
2286*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2287b9c1b51eSKate Stone                 size_diff);
22888b244e21SEwan Crawford 
228980af0b9eSLuke Drummond       for (uint32_t i = 0; i < size_diff; ++i) {
22900e4c4821SAdrian Prantl         ConstString name = elem.children[num_children + i].type_name;
22918b244e21SEwan Crawford         if (strcmp(name.AsCString(), "#rs_padding") < 0)
22928b244e21SEwan Crawford           found = false;
22938b244e21SEwan Crawford       }
22948b244e21SEwan Crawford     }
22958b244e21SEwan Crawford 
229680af0b9eSLuke Drummond     // We've found a global variable with matching type
2297b9c1b51eSKate Stone     if (found) {
22988b244e21SEwan Crawford       // Dereference since our Element type isn't a pointer.
2299b9c1b51eSKate Stone       if (valobj_sp->IsPointerType()) {
230097206d57SZachary Turner         Status err;
23018b244e21SEwan Crawford         ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
23028b244e21SEwan Crawford         if (!err.Fail())
23038b244e21SEwan Crawford           valobj_sp = deref_valobj;
23048b244e21SEwan Crawford       }
23058b244e21SEwan Crawford 
23068b244e21SEwan Crawford       // Save name of variable in Element.
23078b244e21SEwan Crawford       elem.type_name = valobj_sp->GetTypeName();
2308*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - element name set to %s", __FUNCTION__,
2309b9c1b51eSKate Stone                 elem.type_name.AsCString());
23108b244e21SEwan Crawford 
23118b244e21SEwan Crawford       return;
23128b244e21SEwan Crawford     }
23138b244e21SEwan Crawford   }
23148b244e21SEwan Crawford }
23158b244e21SEwan Crawford 
2316b9c1b51eSKate Stone // Function sets the datum_size member of Element. Representing the size of a
231705097246SAdrian Prantl // single instance including padding. Assumes the relevant allocation
231805097246SAdrian Prantl // information has already been jitted.
2319b9c1b51eSKate Stone void RenderScriptRuntime::SetElementSize(Element &elem) {
23208b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
23218b244e21SEwan Crawford   const Element::DataType type = *elem.type.get();
2322b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2323b9c1b51eSKate Stone          "Invalid allocation type");
232455232f09SEwan Crawford 
2325b3f7f69dSAidan Dodds   const uint32_t vec_size = *elem.type_vec_size.get();
2326b3f7f69dSAidan Dodds   uint32_t data_size = 0;
2327b3f7f69dSAidan Dodds   uint32_t padding = 0;
232855232f09SEwan Crawford 
23298b244e21SEwan Crawford   // Element is of a struct type, calculate size recursively.
2330b9c1b51eSKate Stone   if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2331b9c1b51eSKate Stone     for (Element &child : elem.children) {
23328b244e21SEwan Crawford       SetElementSize(child);
2333b9c1b51eSKate Stone       const uint32_t array_size =
2334b9c1b51eSKate Stone           child.array_size.isValid() ? *child.array_size.get() : 1;
23358b244e21SEwan Crawford       data_size += *child.datum_size.get() * array_size;
23368b244e21SEwan Crawford     }
23378b244e21SEwan Crawford   }
2338b3f7f69dSAidan Dodds   // These have been packed already
2339b3f7f69dSAidan Dodds   else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2340b3f7f69dSAidan Dodds            type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2341b9c1b51eSKate Stone            type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
23422e920715SEwan Crawford     data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2343b9c1b51eSKate Stone   } else if (type < Element::RS_TYPE_ELEMENT) {
2344b9c1b51eSKate Stone     data_size =
2345b9c1b51eSKate Stone         vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
23462e920715SEwan Crawford     if (vec_size == 3)
23472e920715SEwan Crawford       padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2348b9c1b51eSKate Stone   } else
2349b9c1b51eSKate Stone     data_size =
2350b9c1b51eSKate Stone         GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
23518b244e21SEwan Crawford 
23528b244e21SEwan Crawford   elem.padding = padding;
23538b244e21SEwan Crawford   elem.datum_size = data_size + padding;
2354*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - element size set to %" PRIu32, __FUNCTION__,
2355b9c1b51eSKate Stone             data_size + padding);
235655232f09SEwan Crawford }
235755232f09SEwan Crawford 
235805097246SAdrian Prantl // Given an allocation, this function copies the allocation contents from
235905097246SAdrian Prantl // device into a buffer on the heap. Returning a shared pointer to the buffer
236005097246SAdrian Prantl // containing the data.
236155232f09SEwan Crawford std::shared_ptr<uint8_t>
236280af0b9eSLuke Drummond RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2363b9c1b51eSKate Stone                                        StackFrame *frame_ptr) {
236455232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
236555232f09SEwan Crawford 
236655232f09SEwan Crawford   // JIT all the allocation details
236780af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
2368*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info",
2369b9c1b51eSKate Stone               __FUNCTION__);
237055232f09SEwan Crawford 
237180af0b9eSLuke Drummond     if (!RefreshAllocation(alloc, frame_ptr)) {
2372*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - couldn't JIT allocation details", __FUNCTION__);
237355232f09SEwan Crawford       return nullptr;
237455232f09SEwan Crawford     }
237555232f09SEwan Crawford   }
237655232f09SEwan Crawford 
237780af0b9eSLuke Drummond   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
237880af0b9eSLuke Drummond          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
237980af0b9eSLuke Drummond          "Allocation information not available");
238055232f09SEwan Crawford 
238155232f09SEwan Crawford   // Allocate a buffer to copy data into
238280af0b9eSLuke Drummond   const uint32_t size = *alloc->size.get();
238355232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2384b9c1b51eSKate Stone   if (!buffer) {
2385*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - couldn't allocate a %" PRIu32 " byte buffer",
2386b9c1b51eSKate Stone               __FUNCTION__, size);
238755232f09SEwan Crawford     return nullptr;
238855232f09SEwan Crawford   }
238955232f09SEwan Crawford 
239055232f09SEwan Crawford   // Read the inferior memory
239197206d57SZachary Turner   Status err;
239280af0b9eSLuke Drummond   lldb::addr_t data_ptr = *alloc->data_ptr.get();
239380af0b9eSLuke Drummond   GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
239480af0b9eSLuke Drummond   if (err.Fail()) {
2395*63e5fb76SJonas Devlieghere     LLDB_LOGF(log,
2396*63e5fb76SJonas Devlieghere               "%s - '%s' Couldn't read %" PRIu32
2397b9c1b51eSKate Stone               " bytes of allocation data from 0x%" PRIx64,
239880af0b9eSLuke Drummond               __FUNCTION__, err.AsCString(), size, data_ptr);
239955232f09SEwan Crawford     return nullptr;
240055232f09SEwan Crawford   }
240155232f09SEwan Crawford 
240255232f09SEwan Crawford   return buffer;
240355232f09SEwan Crawford }
240455232f09SEwan Crawford 
240505097246SAdrian Prantl // Function copies data from a binary file into an allocation. There is a
240605097246SAdrian Prantl // header at the start of the file, FileHeader, before the data content itself.
2407b9c1b51eSKate Stone // Information from this header is used to display warnings to the user about
2408b9c1b51eSKate Stone // incompatibilities
2409b9c1b51eSKate Stone bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
241080af0b9eSLuke Drummond                                          const char *path,
2411b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
241255232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
241355232f09SEwan Crawford 
241455232f09SEwan Crawford   // Find allocation with the given id
241555232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
241655232f09SEwan Crawford   if (!alloc)
241755232f09SEwan Crawford     return false;
241855232f09SEwan Crawford 
2419*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - found allocation 0x%" PRIx64, __FUNCTION__,
2420b9c1b51eSKate Stone             *alloc->address.get());
242155232f09SEwan Crawford 
242255232f09SEwan Crawford   // JIT all the allocation details
242380af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
2424*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info.",
2425b9c1b51eSKate Stone               __FUNCTION__);
242655232f09SEwan Crawford 
2427b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
2428*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - couldn't JIT allocation details", __FUNCTION__);
24294cfc9198SSylvestre Ledru       return false;
243055232f09SEwan Crawford     }
243155232f09SEwan Crawford   }
243255232f09SEwan Crawford 
2433b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2434b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2435b9c1b51eSKate Stone          alloc->element.datum_size.isValid() &&
2436b9c1b51eSKate Stone          "Allocation information not available");
243755232f09SEwan Crawford 
243855232f09SEwan Crawford   // Check we can read from file
24398f3be7a3SJonas Devlieghere   FileSpec file(path);
24408f3be7a3SJonas Devlieghere   FileSystem::Instance().Resolve(file);
2441dbd7fabaSJonas Devlieghere   if (!FileSystem::Instance().Exists(file)) {
244280af0b9eSLuke Drummond     strm.Printf("Error: File %s does not exist", path);
244355232f09SEwan Crawford     strm.EOL();
244455232f09SEwan Crawford     return false;
244555232f09SEwan Crawford   }
244655232f09SEwan Crawford 
24477c5310bbSJonas Devlieghere   if (!FileSystem::Instance().Readable(file)) {
244880af0b9eSLuke Drummond     strm.Printf("Error: File %s does not have readable permissions", path);
244955232f09SEwan Crawford     strm.EOL();
245055232f09SEwan Crawford     return false;
245155232f09SEwan Crawford   }
245255232f09SEwan Crawford 
245355232f09SEwan Crawford   // Read file into data buffer
245487e403aaSJonas Devlieghere   auto data_sp = FileSystem::Instance().CreateDataBuffer(file.GetPath());
245555232f09SEwan Crawford 
245655232f09SEwan Crawford   // Cast start of buffer to FileHeader and use pointer to read metadata
245780af0b9eSLuke Drummond   void *file_buf = data_sp->GetBytes();
245880af0b9eSLuke Drummond   if (file_buf == nullptr ||
2459b9c1b51eSKate Stone       data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2460b9c1b51eSKate Stone                                 sizeof(AllocationDetails::ElementHeader))) {
246180af0b9eSLuke Drummond     strm.Printf("Error: File %s does not contain enough data for header", path);
246226e52a70SEwan Crawford     strm.EOL();
246326e52a70SEwan Crawford     return false;
246426e52a70SEwan Crawford   }
2465b9c1b51eSKate Stone   const AllocationDetails::FileHeader *file_header =
246680af0b9eSLuke Drummond       static_cast<AllocationDetails::FileHeader *>(file_buf);
246755232f09SEwan Crawford 
246826e52a70SEwan Crawford   // Check file starts with ascii characters "RSAD"
2469b9c1b51eSKate Stone   if (memcmp(file_header->ident, "RSAD", 4)) {
2470b9c1b51eSKate Stone     strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2471b9c1b51eSKate Stone                 "dump. Are you sure this is the correct file?");
247226e52a70SEwan Crawford     strm.EOL();
247326e52a70SEwan Crawford     return false;
247426e52a70SEwan Crawford   }
247526e52a70SEwan Crawford 
247626e52a70SEwan Crawford   // Look at the type of the root element in the header
247780af0b9eSLuke Drummond   AllocationDetails::ElementHeader root_el_hdr;
247880af0b9eSLuke Drummond   memcpy(&root_el_hdr, static_cast<uint8_t *>(file_buf) +
2479b9c1b51eSKate Stone                            sizeof(AllocationDetails::FileHeader),
248026e52a70SEwan Crawford          sizeof(AllocationDetails::ElementHeader));
248155232f09SEwan Crawford 
2482*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - header type %" PRIu32 ", element size %" PRIu32,
248380af0b9eSLuke Drummond             __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
248455232f09SEwan Crawford 
2485b9c1b51eSKate Stone   // Check if the target allocation and file both have the same number of bytes
2486b9c1b51eSKate Stone   // for an Element
248780af0b9eSLuke Drummond   if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2488b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2489b9c1b51eSKate Stone                 " bytes, allocation %" PRIu32 " bytes",
249080af0b9eSLuke Drummond                 root_el_hdr.element_size, *alloc->element.datum_size.get());
249155232f09SEwan Crawford     strm.EOL();
249255232f09SEwan Crawford   }
249355232f09SEwan Crawford 
249426e52a70SEwan Crawford   // Check if the target allocation and file both have the same type
2495b3f7f69dSAidan Dodds   const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
249680af0b9eSLuke Drummond   const uint32_t file_type = root_el_hdr.type;
249726e52a70SEwan Crawford 
2498b9c1b51eSKate Stone   if (file_type > Element::RS_TYPE_FONT) {
249926e52a70SEwan Crawford     strm.Printf("Warning: File has unknown allocation type");
250026e52a70SEwan Crawford     strm.EOL();
2501b9c1b51eSKate Stone   } else if (alloc_type != file_type) {
2502b9c1b51eSKate Stone     // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2503b9c1b51eSKate Stone     // array
250480af0b9eSLuke Drummond     uint32_t target_type_name_idx = alloc_type;
250580af0b9eSLuke Drummond     uint32_t head_type_name_idx = file_type;
2506b9c1b51eSKate Stone     if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2507b9c1b51eSKate Stone         alloc_type <= Element::RS_TYPE_FONT)
250880af0b9eSLuke Drummond       target_type_name_idx = static_cast<Element::DataType>(
2509b9c1b51eSKate Stone           (alloc_type - Element::RS_TYPE_ELEMENT) +
2510b3f7f69dSAidan Dodds           Element::RS_TYPE_MATRIX_2X2 + 1);
25112e920715SEwan Crawford 
2512b9c1b51eSKate Stone     if (file_type >= Element::RS_TYPE_ELEMENT &&
2513b9c1b51eSKate Stone         file_type <= Element::RS_TYPE_FONT)
251480af0b9eSLuke Drummond       head_type_name_idx = static_cast<Element::DataType>(
2515b9c1b51eSKate Stone           (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2516b9c1b51eSKate Stone           1);
25172e920715SEwan Crawford 
251880af0b9eSLuke Drummond     const char *head_type_name =
251980af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
252080af0b9eSLuke Drummond     const char *target_type_name =
252180af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
252255232f09SEwan Crawford 
2523b9c1b51eSKate Stone     strm.Printf(
2524b9c1b51eSKate Stone         "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
252580af0b9eSLuke Drummond         head_type_name, target_type_name);
252655232f09SEwan Crawford     strm.EOL();
252755232f09SEwan Crawford   }
252855232f09SEwan Crawford 
252926e52a70SEwan Crawford   // Advance buffer past header
253080af0b9eSLuke Drummond   file_buf = static_cast<uint8_t *>(file_buf) + file_header->hdr_size;
253126e52a70SEwan Crawford 
253255232f09SEwan Crawford   // Calculate size of allocation data in file
253380af0b9eSLuke Drummond   size_t size = data_sp->GetByteSize() - file_header->hdr_size;
253455232f09SEwan Crawford 
253505097246SAdrian Prantl   // Check if the target allocation and file both have the same total data
253605097246SAdrian Prantl   // size.
2537b3f7f69dSAidan Dodds   const uint32_t alloc_size = *alloc->size.get();
253880af0b9eSLuke Drummond   if (alloc_size != size) {
2539b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2540b9c1b51eSKate Stone                 " bytes, allocation 0x%" PRIx32 " bytes",
254180af0b9eSLuke Drummond                 (uint64_t)size, alloc_size);
254255232f09SEwan Crawford     strm.EOL();
254380af0b9eSLuke Drummond     // Set length to copy to minimum
254480af0b9eSLuke Drummond     size = alloc_size < size ? alloc_size : size;
254555232f09SEwan Crawford   }
254655232f09SEwan Crawford 
254755232f09SEwan Crawford   // Copy file data from our buffer into the target allocation.
254855232f09SEwan Crawford   lldb::addr_t alloc_data = *alloc->data_ptr.get();
254997206d57SZachary Turner   Status err;
255080af0b9eSLuke Drummond   size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
255180af0b9eSLuke Drummond   if (!err.Success() || written != size) {
255280af0b9eSLuke Drummond     strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
255355232f09SEwan Crawford     strm.EOL();
255455232f09SEwan Crawford     return false;
255555232f09SEwan Crawford   }
255655232f09SEwan Crawford 
255780af0b9eSLuke Drummond   strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2558b9c1b51eSKate Stone               alloc->id);
255955232f09SEwan Crawford   strm.EOL();
256055232f09SEwan Crawford 
256155232f09SEwan Crawford   return true;
256255232f09SEwan Crawford }
256355232f09SEwan Crawford 
2564b9c1b51eSKate Stone // Function takes as parameters a byte buffer, which will eventually be written
256580af0b9eSLuke Drummond // to file as the element header, an offset into that buffer, and an Element
256605097246SAdrian Prantl // that will be saved into the buffer at the parametrised offset. Return value
256705097246SAdrian Prantl // is the new offset after writing the element into the buffer. Elements are
256805097246SAdrian Prantl // saved to the file as the ElementHeader struct followed by offsets to the
256905097246SAdrian Prantl // structs of all the element's children.
2570b9c1b51eSKate Stone size_t RenderScriptRuntime::PopulateElementHeaders(
2571b9c1b51eSKate Stone     const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2572b9c1b51eSKate Stone     const Element &elem) {
257305097246SAdrian Prantl   // File struct for an element header with all the relevant details copied
257405097246SAdrian Prantl   // from elem. We assume members are valid already.
257526e52a70SEwan Crawford   AllocationDetails::ElementHeader elem_header;
257626e52a70SEwan Crawford   elem_header.type = *elem.type.get();
257726e52a70SEwan Crawford   elem_header.kind = *elem.type_kind.get();
257826e52a70SEwan Crawford   elem_header.element_size = *elem.datum_size.get();
257926e52a70SEwan Crawford   elem_header.vector_size = *elem.type_vec_size.get();
2580b9c1b51eSKate Stone   elem_header.array_size =
2581b9c1b51eSKate Stone       elem.array_size.isValid() ? *elem.array_size.get() : 0;
258226e52a70SEwan Crawford   const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
258326e52a70SEwan Crawford 
258405097246SAdrian Prantl   // Copy struct into buffer and advance offset We assume that header_buffer
258505097246SAdrian Prantl   // has been checked for nullptr before this method is called
258626e52a70SEwan Crawford   memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
258726e52a70SEwan Crawford   offset += elem_header_size;
258826e52a70SEwan Crawford 
258926e52a70SEwan Crawford   // Starting offset of child ElementHeader struct
2590b9c1b51eSKate Stone   size_t child_offset =
2591b9c1b51eSKate Stone       offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2592b9c1b51eSKate Stone   for (const RenderScriptRuntime::Element &child : elem.children) {
2593b9c1b51eSKate Stone     // Recursively populate the buffer with the element header structs of
259480af0b9eSLuke Drummond     // children. Then save the offsets where they were set after the parent
259580af0b9eSLuke Drummond     // element header.
259626e52a70SEwan Crawford     memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
259726e52a70SEwan Crawford     offset += sizeof(uint32_t);
259826e52a70SEwan Crawford 
259926e52a70SEwan Crawford     child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
260026e52a70SEwan Crawford   }
260126e52a70SEwan Crawford 
260226e52a70SEwan Crawford   // Zero indicates no more children
260326e52a70SEwan Crawford   memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
260426e52a70SEwan Crawford 
260526e52a70SEwan Crawford   return child_offset;
260626e52a70SEwan Crawford }
260726e52a70SEwan Crawford 
2608b9c1b51eSKate Stone // Given an Element object this function returns the total size needed in the
260980af0b9eSLuke Drummond // file header to store the element's details. Taking into account the size of
261080af0b9eSLuke Drummond // the element header struct, plus the offsets to all the element's children.
2611b9c1b51eSKate Stone // Function is recursive so that the size of all ancestors is taken into
2612b9c1b51eSKate Stone // account.
2613b9c1b51eSKate Stone size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
261480af0b9eSLuke Drummond   // Offsets to children plus zero terminator
261580af0b9eSLuke Drummond   size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
261680af0b9eSLuke Drummond   // Size of header struct with type details
261780af0b9eSLuke Drummond   size += sizeof(AllocationDetails::ElementHeader);
261826e52a70SEwan Crawford 
261926e52a70SEwan Crawford   // Calculate recursively for all descendants
262026e52a70SEwan Crawford   for (const Element &child : elem.children)
262126e52a70SEwan Crawford     size += CalculateElementHeaderSize(child);
262226e52a70SEwan Crawford 
262326e52a70SEwan Crawford   return size;
262426e52a70SEwan Crawford }
262526e52a70SEwan Crawford 
262605097246SAdrian Prantl // Function copies allocation contents into a binary file. This file can then
262705097246SAdrian Prantl // be loaded later into a different allocation. There is a header, FileHeader,
262880af0b9eSLuke Drummond // before the allocation data containing meta-data.
2629b9c1b51eSKate Stone bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
263080af0b9eSLuke Drummond                                          const char *path,
2631b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
263255232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
263355232f09SEwan Crawford 
263455232f09SEwan Crawford   // Find allocation with the given id
263555232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
263655232f09SEwan Crawford   if (!alloc)
263755232f09SEwan Crawford     return false;
263855232f09SEwan Crawford 
2639*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2640b9c1b51eSKate Stone             *alloc->address.get());
264155232f09SEwan Crawford 
264255232f09SEwan Crawford   // JIT all the allocation details
264380af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
2644*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info.",
2645b9c1b51eSKate Stone               __FUNCTION__);
264655232f09SEwan Crawford 
2647b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
2648*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - couldn't JIT allocation details.", __FUNCTION__);
26494cfc9198SSylvestre Ledru       return false;
265055232f09SEwan Crawford     }
265155232f09SEwan Crawford   }
265255232f09SEwan Crawford 
2653b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2654b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() &&
2655b9c1b51eSKate Stone          alloc->element.datum_size.get() &&
2656b9c1b51eSKate Stone          alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2657b3f7f69dSAidan Dodds          "Allocation information not available");
265855232f09SEwan Crawford 
265955232f09SEwan Crawford   // Check we can create writable file
26608f3be7a3SJonas Devlieghere   FileSpec file_spec(path);
26618f3be7a3SJonas Devlieghere   FileSystem::Instance().Resolve(file_spec);
266250bc1ed2SJonas Devlieghere   File file;
266350bc1ed2SJonas Devlieghere   FileSystem::Instance().Open(file, file_spec,
266450bc1ed2SJonas Devlieghere                               File::eOpenOptionWrite |
266550bc1ed2SJonas Devlieghere                                   File::eOpenOptionCanCreate |
2666b9c1b51eSKate Stone                                   File::eOpenOptionTruncate);
266750bc1ed2SJonas Devlieghere 
2668b9c1b51eSKate Stone   if (!file) {
266980af0b9eSLuke Drummond     strm.Printf("Error: Failed to open '%s' for writing", path);
267055232f09SEwan Crawford     strm.EOL();
267155232f09SEwan Crawford     return false;
267255232f09SEwan Crawford   }
267355232f09SEwan Crawford 
267455232f09SEwan Crawford   // Read allocation into buffer of heap memory
267555232f09SEwan Crawford   const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2676b9c1b51eSKate Stone   if (!buffer) {
267755232f09SEwan Crawford     strm.Printf("Error: Couldn't read allocation data into buffer");
267855232f09SEwan Crawford     strm.EOL();
267955232f09SEwan Crawford     return false;
268055232f09SEwan Crawford   }
268155232f09SEwan Crawford 
268255232f09SEwan Crawford   // Create the file header
268355232f09SEwan Crawford   AllocationDetails::FileHeader head;
2684b3f7f69dSAidan Dodds   memcpy(head.ident, "RSAD", 4);
26852d62328aSEwan Crawford   head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
26862d62328aSEwan Crawford   head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
26872d62328aSEwan Crawford   head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
268826e52a70SEwan Crawford 
268926e52a70SEwan Crawford   const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2690b9c1b51eSKate Stone   assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2691b9c1b51eSKate Stone              UINT16_MAX &&
2692b9c1b51eSKate Stone          "Element header too large");
2693b9c1b51eSKate Stone   head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2694b9c1b51eSKate Stone                                         element_header_size);
269555232f09SEwan Crawford 
269655232f09SEwan Crawford   // Write the file header
269755232f09SEwan Crawford   size_t num_bytes = sizeof(AllocationDetails::FileHeader);
2698*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2699b9c1b51eSKate Stone             (uint64_t)num_bytes);
270026e52a70SEwan Crawford 
270197206d57SZachary Turner   Status err = file.Write(&head, num_bytes);
2702b9c1b51eSKate Stone   if (!err.Success()) {
270380af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
270426e52a70SEwan Crawford     strm.EOL();
270526e52a70SEwan Crawford     return false;
270626e52a70SEwan Crawford   }
270726e52a70SEwan Crawford 
270826e52a70SEwan Crawford   // Create the headers describing the element type of the allocation.
2709b9c1b51eSKate Stone   std::shared_ptr<uint8_t> element_header_buffer(
2710b9c1b51eSKate Stone       new uint8_t[element_header_size]);
2711b9c1b51eSKate Stone   if (element_header_buffer == nullptr) {
2712b9c1b51eSKate Stone     strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2713b9c1b51eSKate Stone                 " bytes on the heap",
2714b9c1b51eSKate Stone                 (uint64_t)element_header_size);
271526e52a70SEwan Crawford     strm.EOL();
271626e52a70SEwan Crawford     return false;
271726e52a70SEwan Crawford   }
271826e52a70SEwan Crawford 
271926e52a70SEwan Crawford   PopulateElementHeaders(element_header_buffer, 0, alloc->element);
272026e52a70SEwan Crawford 
272126e52a70SEwan Crawford   // Write headers for allocation element type to file
272226e52a70SEwan Crawford   num_bytes = element_header_size;
2723*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - writing element headers, 0x%" PRIx64 " bytes.",
2724b9c1b51eSKate Stone             __FUNCTION__, (uint64_t)num_bytes);
272526e52a70SEwan Crawford 
272626e52a70SEwan Crawford   err = file.Write(element_header_buffer.get(), num_bytes);
2727b9c1b51eSKate Stone   if (!err.Success()) {
272880af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
272955232f09SEwan Crawford     strm.EOL();
273055232f09SEwan Crawford     return false;
273155232f09SEwan Crawford   }
273255232f09SEwan Crawford 
273355232f09SEwan Crawford   // Write allocation data to file
273455232f09SEwan Crawford   num_bytes = static_cast<size_t>(*alloc->size.get());
2735*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2736b9c1b51eSKate Stone             (uint64_t)num_bytes);
273755232f09SEwan Crawford 
273855232f09SEwan Crawford   err = file.Write(buffer.get(), num_bytes);
2739b9c1b51eSKate Stone   if (!err.Success()) {
274080af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
274155232f09SEwan Crawford     strm.EOL();
274255232f09SEwan Crawford     return false;
274355232f09SEwan Crawford   }
274455232f09SEwan Crawford 
274580af0b9eSLuke Drummond   strm.Printf("Allocation written to file '%s'", path);
274655232f09SEwan Crawford   strm.EOL();
274715f2bd95SEwan Crawford   return true;
274815f2bd95SEwan Crawford }
274915f2bd95SEwan Crawford 
2750b9c1b51eSKate Stone bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
27514640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
27524640cde1SColin Riley 
2753b9c1b51eSKate Stone   if (module_sp) {
2754b9c1b51eSKate Stone     for (const auto &rs_module : m_rsmodules) {
2755b9c1b51eSKate Stone       if (rs_module->m_module == module_sp) {
275605097246SAdrian Prantl         // Check if the user has enabled automatically breaking on all RS
275705097246SAdrian Prantl         // kernels.
27587dc7771cSEwan Crawford         if (m_breakAllKernels)
27597dc7771cSEwan Crawford           BreakOnModuleKernels(rs_module);
27607dc7771cSEwan Crawford 
27615ec532a9SColin Riley         return false;
27625ec532a9SColin Riley       }
27637dc7771cSEwan Crawford     }
2764ef20b08fSColin Riley     bool module_loaded = false;
2765b9c1b51eSKate Stone     switch (GetModuleKind(module_sp)) {
2766b9c1b51eSKate Stone     case eModuleKindKernelObj: {
27674640cde1SColin Riley       RSModuleDescriptorSP module_desc;
2768796ac80bSJonas Devlieghere       module_desc = std::make_shared<RSModuleDescriptor>(module_sp);
2769b9c1b51eSKate Stone       if (module_desc->ParseRSInfo()) {
27705ec532a9SColin Riley         m_rsmodules.push_back(module_desc);
277147d64161SLuke Drummond         module_desc->WarnIfVersionMismatch(GetProcess()
277247d64161SLuke Drummond                                                ->GetTarget()
277347d64161SLuke Drummond                                                .GetDebugger()
277447d64161SLuke Drummond                                                .GetAsyncOutputStream()
277547d64161SLuke Drummond                                                .get());
2776ef20b08fSColin Riley         module_loaded = true;
27775ec532a9SColin Riley       }
2778b9c1b51eSKate Stone       if (module_loaded) {
27794640cde1SColin Riley         FixupScriptDetails(module_desc);
27804640cde1SColin Riley       }
2781ef20b08fSColin Riley       break;
2782ef20b08fSColin Riley     }
2783b9c1b51eSKate Stone     case eModuleKindDriver: {
2784b9c1b51eSKate Stone       if (!m_libRSDriver) {
27854640cde1SColin Riley         m_libRSDriver = module_sp;
27864640cde1SColin Riley         LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
27874640cde1SColin Riley       }
27884640cde1SColin Riley       break;
27894640cde1SColin Riley     }
2790b9c1b51eSKate Stone     case eModuleKindImpl: {
279121fed052SAidan Dodds       if (!m_libRSCpuRef) {
27924640cde1SColin Riley         m_libRSCpuRef = module_sp;
279321fed052SAidan Dodds         LoadRuntimeHooks(m_libRSCpuRef, RenderScriptRuntime::eModuleKindImpl);
279421fed052SAidan Dodds       }
27954640cde1SColin Riley       break;
27964640cde1SColin Riley     }
2797b9c1b51eSKate Stone     case eModuleKindLibRS: {
2798b9c1b51eSKate Stone       if (!m_libRS) {
27994640cde1SColin Riley         m_libRS = module_sp;
28004640cde1SColin Riley         static ConstString gDbgPresentStr("gDebuggerPresent");
2801b9c1b51eSKate Stone         const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2802b9c1b51eSKate Stone             gDbgPresentStr, eSymbolTypeData);
2803b9c1b51eSKate Stone         if (debug_present) {
280497206d57SZachary Turner           Status err;
28054640cde1SColin Riley           uint32_t flag = 0x00000001U;
28064640cde1SColin Riley           Target &target = GetProcess()->GetTarget();
2807358cf1eaSGreg Clayton           addr_t addr = debug_present->GetLoadAddress(&target);
280880af0b9eSLuke Drummond           GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
280980af0b9eSLuke Drummond           if (err.Success()) {
2810*63e5fb76SJonas Devlieghere             LLDB_LOGF(log, "%s - debugger present flag set on debugee.",
2811b9c1b51eSKate Stone                       __FUNCTION__);
28124640cde1SColin Riley 
28134640cde1SColin Riley             m_debuggerPresentFlagged = true;
2814b9c1b51eSKate Stone           } else if (log) {
2815*63e5fb76SJonas Devlieghere             LLDB_LOGF(log, "%s - error writing debugger present flags '%s' ",
281680af0b9eSLuke Drummond                       __FUNCTION__, err.AsCString());
28174640cde1SColin Riley           }
2818b9c1b51eSKate Stone         } else if (log) {
2819*63e5fb76SJonas Devlieghere           LLDB_LOGF(
2820*63e5fb76SJonas Devlieghere               log,
2821b9c1b51eSKate Stone               "%s - error writing debugger present flags - symbol not found",
2822b9c1b51eSKate Stone               __FUNCTION__);
28234640cde1SColin Riley         }
28244640cde1SColin Riley       }
28254640cde1SColin Riley       break;
28264640cde1SColin Riley     }
2827ef20b08fSColin Riley     default:
2828ef20b08fSColin Riley       break;
2829ef20b08fSColin Riley     }
2830ef20b08fSColin Riley     if (module_loaded)
2831ef20b08fSColin Riley       Update();
2832ef20b08fSColin Riley     return module_loaded;
28335ec532a9SColin Riley   }
28345ec532a9SColin Riley   return false;
28355ec532a9SColin Riley }
28365ec532a9SColin Riley 
2837b9c1b51eSKate Stone void RenderScriptRuntime::Update() {
2838b9c1b51eSKate Stone   if (m_rsmodules.size() > 0) {
2839b9c1b51eSKate Stone     if (!m_initiated) {
2840ef20b08fSColin Riley       Initiate();
2841ef20b08fSColin Riley     }
2842ef20b08fSColin Riley   }
2843ef20b08fSColin Riley }
2844ef20b08fSColin Riley 
284547d64161SLuke Drummond void RSModuleDescriptor::WarnIfVersionMismatch(lldb_private::Stream *s) const {
284647d64161SLuke Drummond   if (!s)
284747d64161SLuke Drummond     return;
284847d64161SLuke Drummond 
284947d64161SLuke Drummond   if (m_slang_version.empty() || m_bcc_version.empty()) {
285047d64161SLuke Drummond     s->PutCString("WARNING: Unknown bcc or slang (llvm-rs-cc) version; debug "
285147d64161SLuke Drummond                   "experience may be unreliable");
285247d64161SLuke Drummond     s->EOL();
285347d64161SLuke Drummond   } else if (m_slang_version != m_bcc_version) {
285447d64161SLuke Drummond     s->Printf("WARNING: The debug info emitted by the slang frontend "
285547d64161SLuke Drummond               "(llvm-rs-cc) used to build this module (%s) does not match the "
285647d64161SLuke Drummond               "version of bcc used to generate the debug information (%s). "
285747d64161SLuke Drummond               "This is an unsupported configuration and may result in a poor "
285847d64161SLuke Drummond               "debugging experience; proceed with caution",
285947d64161SLuke Drummond               m_slang_version.c_str(), m_bcc_version.c_str());
286047d64161SLuke Drummond     s->EOL();
286147d64161SLuke Drummond   }
286247d64161SLuke Drummond }
286347d64161SLuke Drummond 
28647f193d69SLuke Drummond bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
28657f193d69SLuke Drummond                                           size_t n_lines) {
28667f193d69SLuke Drummond   // Skip the pragma prototype line
28677f193d69SLuke Drummond   ++lines;
28687f193d69SLuke Drummond   for (; n_lines--; ++lines) {
28697f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
28707f193d69SLuke Drummond     m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
28717f193d69SLuke Drummond   }
28727f193d69SLuke Drummond   return true;
28737f193d69SLuke Drummond }
28747f193d69SLuke Drummond 
28757f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
28767f193d69SLuke Drummond                                                 size_t n_lines) {
28777f193d69SLuke Drummond   // The list of reduction kernels in the `.rs.info` symbol is of the form
28787f193d69SLuke Drummond   // "signature - accumulatordatasize - reduction_name - initializer_name -
287905097246SAdrian Prantl   // accumulator_name - combiner_name - outconverter_name - halter_name" Where
288005097246SAdrian Prantl   // a function is not explicitly named by the user, or is not generated by the
288105097246SAdrian Prantl   // compiler, it is named "." so the dash separated list should always be 8
288205097246SAdrian Prantl   // items long
28837f193d69SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
28847f193d69SLuke Drummond   // Skip the exportReduceCount line
28857f193d69SLuke Drummond   ++lines;
28867f193d69SLuke Drummond   for (; n_lines--; ++lines) {
28877f193d69SLuke Drummond     llvm::SmallVector<llvm::StringRef, 8> spec;
28887f193d69SLuke Drummond     lines->split(spec, " - ");
28897f193d69SLuke Drummond     if (spec.size() != 8) {
28907f193d69SLuke Drummond       if (spec.size() < 8) {
28917f193d69SLuke Drummond         if (log)
28927f193d69SLuke Drummond           log->Error("Error parsing RenderScript reduction spec. wrong number "
28937f193d69SLuke Drummond                      "of fields");
28947f193d69SLuke Drummond         return false;
28957f193d69SLuke Drummond       } else if (log)
28967f193d69SLuke Drummond         log->Warning("Extraneous members in reduction spec: '%s'",
28977f193d69SLuke Drummond                      lines->str().c_str());
28987f193d69SLuke Drummond     }
28997f193d69SLuke Drummond 
29007f193d69SLuke Drummond     const auto sig_s = spec[0];
29017f193d69SLuke Drummond     uint32_t sig;
29027f193d69SLuke Drummond     if (sig_s.getAsInteger(10, sig)) {
29037f193d69SLuke Drummond       if (log)
29047f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid kernel "
29057f193d69SLuke Drummond                    "signature: '%s'",
29067f193d69SLuke Drummond                    sig_s.str().c_str());
29077f193d69SLuke Drummond       return false;
29087f193d69SLuke Drummond     }
29097f193d69SLuke Drummond 
29107f193d69SLuke Drummond     const auto accum_data_size_s = spec[1];
29117f193d69SLuke Drummond     uint32_t accum_data_size;
29127f193d69SLuke Drummond     if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
29137f193d69SLuke Drummond       if (log)
29147f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid "
29157f193d69SLuke Drummond                    "accumulator data size %s",
29167f193d69SLuke Drummond                    accum_data_size_s.str().c_str());
29177f193d69SLuke Drummond       return false;
29187f193d69SLuke Drummond     }
29197f193d69SLuke Drummond 
2920*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "Found RenderScript reduction '%s'", spec[2].str().c_str());
29217f193d69SLuke Drummond 
29227f193d69SLuke Drummond     m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
29237f193d69SLuke Drummond                                                  spec[2], spec[3], spec[4],
29247f193d69SLuke Drummond                                                  spec[5], spec[6], spec[7]));
29257f193d69SLuke Drummond   }
29267f193d69SLuke Drummond   return true;
29277f193d69SLuke Drummond }
29287f193d69SLuke Drummond 
292947d64161SLuke Drummond bool RSModuleDescriptor::ParseVersionInfo(llvm::StringRef *lines,
293047d64161SLuke Drummond                                           size_t n_lines) {
293147d64161SLuke Drummond   // Skip the versionInfo line
293247d64161SLuke Drummond   ++lines;
293347d64161SLuke Drummond   for (; n_lines--; ++lines) {
293447d64161SLuke Drummond     // We're only interested in bcc and slang versions, and ignore all other
293547d64161SLuke Drummond     // versionInfo lines
293647d64161SLuke Drummond     const auto kv_pair = lines->split(" - ");
293747d64161SLuke Drummond     if (kv_pair.first == "slang")
293847d64161SLuke Drummond       m_slang_version = kv_pair.second.str();
293947d64161SLuke Drummond     else if (kv_pair.first == "bcc")
294047d64161SLuke Drummond       m_bcc_version = kv_pair.second.str();
294147d64161SLuke Drummond   }
294247d64161SLuke Drummond   return true;
294347d64161SLuke Drummond }
294447d64161SLuke Drummond 
29457f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
29467f193d69SLuke Drummond                                                  size_t n_lines) {
29477f193d69SLuke Drummond   // Skip the exportForeachCount line
29487f193d69SLuke Drummond   ++lines;
29497f193d69SLuke Drummond   for (; n_lines--; ++lines) {
29507f193d69SLuke Drummond     uint32_t slot;
29517f193d69SLuke Drummond     // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
29527f193d69SLuke Drummond     // pair per line
29537f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
29547f193d69SLuke Drummond     if (kv_pair.first.getAsInteger(10, slot))
29557f193d69SLuke Drummond       return false;
29567f193d69SLuke Drummond     m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
29577f193d69SLuke Drummond   }
29587f193d69SLuke Drummond   return true;
29597f193d69SLuke Drummond }
29607f193d69SLuke Drummond 
29617f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
29627f193d69SLuke Drummond                                              size_t n_lines) {
29637f193d69SLuke Drummond   // Skip the ExportVarCount line
29647f193d69SLuke Drummond   ++lines;
29657f193d69SLuke Drummond   for (; n_lines--; ++lines)
29667f193d69SLuke Drummond     m_globals.push_back(RSGlobalDescriptor(this, *lines));
29677f193d69SLuke Drummond   return true;
29687f193d69SLuke Drummond }
29695ec532a9SColin Riley 
2970b9c1b51eSKate Stone // The .rs.info symbol in renderscript modules contains a string which needs to
297105097246SAdrian Prantl // be parsed. The string is basic and is parsed on a line by line basis.
2972b9c1b51eSKate Stone bool RSModuleDescriptor::ParseRSInfo() {
2973b0be30f7SAidan Dodds   assert(m_module);
29747f193d69SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2975b9c1b51eSKate Stone   const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
2976b9c1b51eSKate Stone       ConstString(".rs.info"), eSymbolTypeData);
2977b0be30f7SAidan Dodds   if (!info_sym)
2978b0be30f7SAidan Dodds     return false;
2979b0be30f7SAidan Dodds 
2980358cf1eaSGreg Clayton   const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
2981b0be30f7SAidan Dodds   if (addr == LLDB_INVALID_ADDRESS)
2982b0be30f7SAidan Dodds     return false;
2983b0be30f7SAidan Dodds 
29845ec532a9SColin Riley   const addr_t size = info_sym->GetByteSize();
29855ec532a9SColin Riley   const FileSpec fs = m_module->GetFileSpec();
29865ec532a9SColin Riley 
298787e403aaSJonas Devlieghere   auto buffer =
298887e403aaSJonas Devlieghere       FileSystem::Instance().CreateDataBuffer(fs.GetPath(), size, addr);
29895ec532a9SColin Riley   if (!buffer)
29905ec532a9SColin Riley     return false;
29915ec532a9SColin Riley 
2992b0be30f7SAidan Dodds   // split rs.info. contents into lines
29937f193d69SLuke Drummond   llvm::SmallVector<llvm::StringRef, 128> info_lines;
29945ec532a9SColin Riley   {
29957f193d69SLuke Drummond     const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
29967f193d69SLuke Drummond     raw_rs_info.split(info_lines, '\n');
2997*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "'.rs.info symbol for '%s':\n%s",
2998*63e5fb76SJonas Devlieghere               m_module->GetFileSpec().GetCString(), raw_rs_info.str().c_str());
2999b0be30f7SAidan Dodds   }
3000b0be30f7SAidan Dodds 
30017f193d69SLuke Drummond   enum {
30027f193d69SLuke Drummond     eExportVar,
30037f193d69SLuke Drummond     eExportForEach,
30047f193d69SLuke Drummond     eExportReduce,
30057f193d69SLuke Drummond     ePragma,
30067f193d69SLuke Drummond     eBuildChecksum,
300747d64161SLuke Drummond     eObjectSlot,
300847d64161SLuke Drummond     eVersionInfo,
30097f193d69SLuke Drummond   };
30107f193d69SLuke Drummond 
3011b3bbcb12SLuke Drummond   const auto rs_info_handler = [](llvm::StringRef name) -> int {
3012b3bbcb12SLuke Drummond     return llvm::StringSwitch<int>(name)
3013b3bbcb12SLuke Drummond         // The number of visible global variables in the script
3014b3bbcb12SLuke Drummond         .Case("exportVarCount", eExportVar)
30157f193d69SLuke Drummond         // The number of RenderScrip `forEach` kernels __attribute__((kernel))
3016b3bbcb12SLuke Drummond         .Case("exportForEachCount", eExportForEach)
3017b3bbcb12SLuke Drummond         // The number of generalreductions: This marked in the script by
3018b3bbcb12SLuke Drummond         // `#pragma reduce()`
3019b3bbcb12SLuke Drummond         .Case("exportReduceCount", eExportReduce)
3020b3bbcb12SLuke Drummond         // Total count of all RenderScript specific `#pragmas` used in the
3021b3bbcb12SLuke Drummond         // script
3022b3bbcb12SLuke Drummond         .Case("pragmaCount", ePragma)
3023b3bbcb12SLuke Drummond         .Case("objectSlotCount", eObjectSlot)
302447d64161SLuke Drummond         .Case("versionInfo", eVersionInfo)
3025b3bbcb12SLuke Drummond         .Default(-1);
3026b3bbcb12SLuke Drummond   };
3027b0be30f7SAidan Dodds 
3028b0be30f7SAidan Dodds   // parse all text lines of .rs.info
3029b9c1b51eSKate Stone   for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
30307f193d69SLuke Drummond     const auto kv_pair = line->split(": ");
30317f193d69SLuke Drummond     const auto key = kv_pair.first;
30327f193d69SLuke Drummond     const auto val = kv_pair.second.trim();
30335ec532a9SColin Riley 
3034b3bbcb12SLuke Drummond     const auto handler = rs_info_handler(key);
3035b3bbcb12SLuke Drummond     if (handler == -1)
30367f193d69SLuke Drummond       continue;
303705097246SAdrian Prantl     // getAsInteger returns `true` on an error condition - we're only
303805097246SAdrian Prantl     // interested in numeric fields at the moment
30397f193d69SLuke Drummond     uint64_t n_lines;
30407f193d69SLuke Drummond     if (val.getAsInteger(10, n_lines)) {
30416302bf6aSPavel Labath       LLDB_LOGV(log, "Failed to parse non-numeric '.rs.info' section {0}",
30426302bf6aSPavel Labath                 line->str());
30437f193d69SLuke Drummond       continue;
30447f193d69SLuke Drummond     }
30457f193d69SLuke Drummond     if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
30467f193d69SLuke Drummond       return false;
30477f193d69SLuke Drummond 
30487f193d69SLuke Drummond     bool success = false;
3049b3bbcb12SLuke Drummond     switch (handler) {
30507f193d69SLuke Drummond     case eExportVar:
30517f193d69SLuke Drummond       success = ParseExportVarCount(line, n_lines);
30527f193d69SLuke Drummond       break;
30537f193d69SLuke Drummond     case eExportForEach:
30547f193d69SLuke Drummond       success = ParseExportForeachCount(line, n_lines);
30557f193d69SLuke Drummond       break;
30567f193d69SLuke Drummond     case eExportReduce:
30577f193d69SLuke Drummond       success = ParseExportReduceCount(line, n_lines);
30587f193d69SLuke Drummond       break;
30597f193d69SLuke Drummond     case ePragma:
30607f193d69SLuke Drummond       success = ParsePragmaCount(line, n_lines);
30617f193d69SLuke Drummond       break;
306247d64161SLuke Drummond     case eVersionInfo:
306347d64161SLuke Drummond       success = ParseVersionInfo(line, n_lines);
306447d64161SLuke Drummond       break;
30657f193d69SLuke Drummond     default: {
3066*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - skipping .rs.info field '%s'", __FUNCTION__,
30677f193d69SLuke Drummond                 line->str().c_str());
30687f193d69SLuke Drummond       continue;
30697f193d69SLuke Drummond     }
30707f193d69SLuke Drummond     }
30717f193d69SLuke Drummond     if (!success)
30727f193d69SLuke Drummond       return false;
30737f193d69SLuke Drummond     line += n_lines;
30747f193d69SLuke Drummond   }
30757f193d69SLuke Drummond   return info_lines.size() > 0;
30765ec532a9SColin Riley }
30775ec532a9SColin Riley 
307897206d57SZachary Turner void RenderScriptRuntime::DumpStatus(Stream &strm) const {
3079b9c1b51eSKate Stone   if (m_libRS) {
30804640cde1SColin Riley     strm.Printf("Runtime Library discovered.");
30814640cde1SColin Riley     strm.EOL();
30824640cde1SColin Riley   }
3083b9c1b51eSKate Stone   if (m_libRSDriver) {
30844640cde1SColin Riley     strm.Printf("Runtime Driver discovered.");
30854640cde1SColin Riley     strm.EOL();
30864640cde1SColin Riley   }
3087b9c1b51eSKate Stone   if (m_libRSCpuRef) {
30884640cde1SColin Riley     strm.Printf("CPU Reference Implementation discovered.");
30894640cde1SColin Riley     strm.EOL();
30904640cde1SColin Riley   }
30914640cde1SColin Riley 
3092b9c1b51eSKate Stone   if (m_runtimeHooks.size()) {
30934640cde1SColin Riley     strm.Printf("Runtime functions hooked:");
30944640cde1SColin Riley     strm.EOL();
3095b9c1b51eSKate Stone     for (auto b : m_runtimeHooks) {
30964640cde1SColin Riley       strm.Indent(b.second->defn->name);
30974640cde1SColin Riley       strm.EOL();
30984640cde1SColin Riley     }
3099b9c1b51eSKate Stone   } else {
31004640cde1SColin Riley     strm.Printf("Runtime is not hooked.");
31014640cde1SColin Riley     strm.EOL();
31024640cde1SColin Riley   }
31034640cde1SColin Riley }
31044640cde1SColin Riley 
3105b9c1b51eSKate Stone void RenderScriptRuntime::DumpContexts(Stream &strm) const {
31064640cde1SColin Riley   strm.Printf("Inferred RenderScript Contexts:");
31074640cde1SColin Riley   strm.EOL();
31084640cde1SColin Riley   strm.IndentMore();
31094640cde1SColin Riley 
31104640cde1SColin Riley   std::map<addr_t, uint64_t> contextReferences;
31114640cde1SColin Riley 
311205097246SAdrian Prantl   // Iterate over all of the currently discovered scripts. Note: We cant push
311305097246SAdrian Prantl   // or pop from m_scripts inside this loop or it may invalidate script.
3114b9c1b51eSKate Stone   for (const auto &script : m_scripts) {
311578f339d1SEwan Crawford     if (!script->context.isValid())
311678f339d1SEwan Crawford       continue;
311778f339d1SEwan Crawford     lldb::addr_t context = *script->context;
311878f339d1SEwan Crawford 
3119b9c1b51eSKate Stone     if (contextReferences.find(context) != contextReferences.end()) {
312078f339d1SEwan Crawford       contextReferences[context]++;
3121b9c1b51eSKate Stone     } else {
312278f339d1SEwan Crawford       contextReferences[context] = 1;
31234640cde1SColin Riley     }
31244640cde1SColin Riley   }
31254640cde1SColin Riley 
3126b9c1b51eSKate Stone   for (const auto &cRef : contextReferences) {
3127b9c1b51eSKate Stone     strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
3128b9c1b51eSKate Stone                 cRef.first, cRef.second);
31294640cde1SColin Riley     strm.EOL();
31304640cde1SColin Riley   }
31314640cde1SColin Riley   strm.IndentLess();
31324640cde1SColin Riley }
31334640cde1SColin Riley 
3134b9c1b51eSKate Stone void RenderScriptRuntime::DumpKernels(Stream &strm) const {
31354640cde1SColin Riley   strm.Printf("RenderScript Kernels:");
31364640cde1SColin Riley   strm.EOL();
31374640cde1SColin Riley   strm.IndentMore();
3138b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
31394640cde1SColin Riley     strm.Printf("Resource '%s':", module->m_resname.c_str());
31404640cde1SColin Riley     strm.EOL();
3141b9c1b51eSKate Stone     for (const auto &kernel : module->m_kernels) {
31424640cde1SColin Riley       strm.Indent(kernel.m_name.AsCString());
31434640cde1SColin Riley       strm.EOL();
31444640cde1SColin Riley     }
31454640cde1SColin Riley   }
31464640cde1SColin Riley   strm.IndentLess();
31474640cde1SColin Riley }
31484640cde1SColin Riley 
3149a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails *
3150b9c1b51eSKate Stone RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
3151a0f08674SEwan Crawford   AllocationDetails *alloc = nullptr;
3152a0f08674SEwan Crawford 
3153a0f08674SEwan Crawford   // See if we can find allocation using id as an index;
3154b9c1b51eSKate Stone   if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
3155b9c1b51eSKate Stone       m_allocations[alloc_id - 1]->id == alloc_id) {
3156a0f08674SEwan Crawford     alloc = m_allocations[alloc_id - 1].get();
3157a0f08674SEwan Crawford     return alloc;
3158a0f08674SEwan Crawford   }
3159a0f08674SEwan Crawford 
3160a0f08674SEwan Crawford   // Fallback to searching
3161b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
3162b9c1b51eSKate Stone     if (a->id == alloc_id) {
3163a0f08674SEwan Crawford       alloc = a.get();
3164a0f08674SEwan Crawford       break;
3165a0f08674SEwan Crawford     }
3166a0f08674SEwan Crawford   }
3167a0f08674SEwan Crawford 
3168b9c1b51eSKate Stone   if (alloc == nullptr) {
3169b9c1b51eSKate Stone     strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
3170b9c1b51eSKate Stone                 alloc_id);
3171a0f08674SEwan Crawford     strm.EOL();
3172a0f08674SEwan Crawford   }
3173a0f08674SEwan Crawford 
3174a0f08674SEwan Crawford   return alloc;
3175a0f08674SEwan Crawford }
3176a0f08674SEwan Crawford 
3177b9c1b51eSKate Stone // Prints the contents of an allocation to the output stream, which may be a
3178b9c1b51eSKate Stone // file
3179b9c1b51eSKate Stone bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
3180b9c1b51eSKate Stone                                          const uint32_t id) {
3181a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3182a0f08674SEwan Crawford 
3183a0f08674SEwan Crawford   // Check we can find the desired allocation
3184a0f08674SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, id);
3185a0f08674SEwan Crawford   if (!alloc)
3186a0f08674SEwan Crawford     return false; // FindAllocByID() will print error message for us here
3187a0f08674SEwan Crawford 
3188*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - found allocation 0x%" PRIx64, __FUNCTION__,
3189b9c1b51eSKate Stone             *alloc->address.get());
3190a0f08674SEwan Crawford 
3191a0f08674SEwan Crawford   // Check we have information about the allocation, if not calculate it
319280af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
3193*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info.",
3194b9c1b51eSKate Stone               __FUNCTION__);
3195a0f08674SEwan Crawford 
3196a0f08674SEwan Crawford     // JIT all the allocation information
3197b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
3198a0f08674SEwan Crawford       strm.Printf("Error: Couldn't JIT allocation details");
3199a0f08674SEwan Crawford       strm.EOL();
3200a0f08674SEwan Crawford       return false;
3201a0f08674SEwan Crawford     }
3202a0f08674SEwan Crawford   }
3203a0f08674SEwan Crawford 
3204a0f08674SEwan Crawford   // Establish format and size of each data element
3205b3f7f69dSAidan Dodds   const uint32_t vec_size = *alloc->element.type_vec_size.get();
32068b244e21SEwan Crawford   const Element::DataType type = *alloc->element.type.get();
3207a0f08674SEwan Crawford 
3208b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
3209b9c1b51eSKate Stone          "Invalid allocation type");
3210a0f08674SEwan Crawford 
32112e920715SEwan Crawford   lldb::Format format;
32122e920715SEwan Crawford   if (type >= Element::RS_TYPE_ELEMENT)
32132e920715SEwan Crawford     format = eFormatHex;
32142e920715SEwan Crawford   else
3215b9c1b51eSKate Stone     format = vec_size == 1
3216b9c1b51eSKate Stone                  ? static_cast<lldb::Format>(
3217b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatSingle])
3218b9c1b51eSKate Stone                  : static_cast<lldb::Format>(
3219b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatVector]);
3220a0f08674SEwan Crawford 
3221b3f7f69dSAidan Dodds   const uint32_t data_size = *alloc->element.datum_size.get();
3222a0f08674SEwan Crawford 
3223*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - element size %" PRIu32 " bytes, including padding",
3224b9c1b51eSKate Stone             __FUNCTION__, data_size);
3225a0f08674SEwan Crawford 
322655232f09SEwan Crawford   // Allocate a buffer to copy data into
322755232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3228b9c1b51eSKate Stone   if (!buffer) {
32292e920715SEwan Crawford     strm.Printf("Error: Couldn't read allocation data");
323055232f09SEwan Crawford     strm.EOL();
323155232f09SEwan Crawford     return false;
323255232f09SEwan Crawford   }
323355232f09SEwan Crawford 
3234a0f08674SEwan Crawford   // Calculate stride between rows as there may be padding at end of rows since
3235a0f08674SEwan Crawford   // allocated memory is 16-byte aligned
3236b9c1b51eSKate Stone   if (!alloc->stride.isValid()) {
3237a0f08674SEwan Crawford     if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
3238a0f08674SEwan Crawford       alloc->stride = 0;
3239b9c1b51eSKate Stone     else if (!JITAllocationStride(alloc, frame_ptr)) {
3240a0f08674SEwan Crawford       strm.Printf("Error: Couldn't calculate allocation row stride");
3241a0f08674SEwan Crawford       strm.EOL();
3242a0f08674SEwan Crawford       return false;
3243a0f08674SEwan Crawford     }
3244a0f08674SEwan Crawford   }
3245b3f7f69dSAidan Dodds   const uint32_t stride = *alloc->stride.get();
3246b3f7f69dSAidan Dodds   const uint32_t size = *alloc->size.get(); // Size of whole allocation
3247b9c1b51eSKate Stone   const uint32_t padding =
3248b9c1b51eSKate Stone       alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3249*63e5fb76SJonas Devlieghere   LLDB_LOGF(log,
3250*63e5fb76SJonas Devlieghere             "%s - stride %" PRIu32 " bytes, size %" PRIu32
3251b9c1b51eSKate Stone             " bytes, padding %" PRIu32,
3252b3f7f69dSAidan Dodds             __FUNCTION__, stride, size, padding);
3253a0f08674SEwan Crawford 
3254a0f08674SEwan Crawford   // Find dimensions used to index loops, so need to be non-zero
3255b3f7f69dSAidan Dodds   uint32_t dim_x = alloc->dimension.get()->dim_1;
3256a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 1 : dim_x;
3257a0f08674SEwan Crawford 
3258b3f7f69dSAidan Dodds   uint32_t dim_y = alloc->dimension.get()->dim_2;
3259a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 1 : dim_y;
3260a0f08674SEwan Crawford 
3261b3f7f69dSAidan Dodds   uint32_t dim_z = alloc->dimension.get()->dim_3;
3262a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 1 : dim_z;
3263a0f08674SEwan Crawford 
326455232f09SEwan Crawford   // Use data extractor to format output
326580af0b9eSLuke Drummond   const uint32_t target_ptr_size =
3266b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3267b9c1b51eSKate Stone   DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
326880af0b9eSLuke Drummond                            target_ptr_size);
326955232f09SEwan Crawford 
3270b3f7f69dSAidan Dodds   uint32_t offset = 0;   // Offset in buffer to next element to be printed
3271b3f7f69dSAidan Dodds   uint32_t prev_row = 0; // Offset to the start of the previous row
3272a0f08674SEwan Crawford 
3273a0f08674SEwan Crawford   // Iterate over allocation dimensions, printing results to user
3274a0f08674SEwan Crawford   strm.Printf("Data (X, Y, Z):");
3275b9c1b51eSKate Stone   for (uint32_t z = 0; z < dim_z; ++z) {
3276b9c1b51eSKate Stone     for (uint32_t y = 0; y < dim_y; ++y) {
3277a0f08674SEwan Crawford       // Use stride to index start of next row.
3278a0f08674SEwan Crawford       if (!(y == 0 && z == 0))
3279a0f08674SEwan Crawford         offset = prev_row + stride;
3280a0f08674SEwan Crawford       prev_row = offset;
3281a0f08674SEwan Crawford 
3282a0f08674SEwan Crawford       // Print each element in the row individually
3283b9c1b51eSKate Stone       for (uint32_t x = 0; x < dim_x; ++x) {
3284b3f7f69dSAidan Dodds         strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3285b9c1b51eSKate Stone         if ((type == Element::RS_TYPE_NONE) &&
3286b9c1b51eSKate Stone             (alloc->element.children.size() > 0) &&
3287b9c1b51eSKate Stone             (alloc->element.type_name != Element::GetFallbackStructName())) {
328805097246SAdrian Prantl           // Here we are dumping an Element of struct type. This is done using
328905097246SAdrian Prantl           // expression evaluation with the name of the struct type and pointer
329005097246SAdrian Prantl           // to element. Don't print the name of the resulting expression,
329105097246SAdrian Prantl           // since this will be '$[0-9]+'
32928b244e21SEwan Crawford           DumpValueObjectOptions expr_options;
32938b244e21SEwan Crawford           expr_options.SetHideName(true);
32948b244e21SEwan Crawford 
32954ebdee0aSBruce Mitchener           // Setup expression as dereferencing a pointer cast to element
329605097246SAdrian Prantl           // address.
3297ea0636b5SEwan Crawford           char expr_char_buffer[jit_max_expr_size];
329880af0b9eSLuke Drummond           int written =
3299b9c1b51eSKate Stone               snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3300b9c1b51eSKate Stone                        alloc->element.type_name.AsCString(),
3301b9c1b51eSKate Stone                        *alloc->data_ptr.get() + offset);
33028b244e21SEwan Crawford 
330380af0b9eSLuke Drummond           if (written < 0 || written >= jit_max_expr_size) {
3304*63e5fb76SJonas Devlieghere             LLDB_LOGF(log, "%s - error in snprintf().", __FUNCTION__);
33058b244e21SEwan Crawford             continue;
33068b244e21SEwan Crawford           }
33078b244e21SEwan Crawford 
33088b244e21SEwan Crawford           // Evaluate expression
33098b244e21SEwan Crawford           ValueObjectSP expr_result;
3310b9c1b51eSKate Stone           GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3311b9c1b51eSKate Stone                                                        frame_ptr, expr_result);
33128b244e21SEwan Crawford 
33138b244e21SEwan Crawford           // Print the results to our stream.
33148b244e21SEwan Crawford           expr_result->Dump(strm, expr_options);
3315b9c1b51eSKate Stone         } else {
331629cb868aSZachary Turner           DumpDataExtractor(alloc_data, &strm, offset, format,
331729cb868aSZachary Turner                             data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0,
331829cb868aSZachary Turner                             0);
33198b244e21SEwan Crawford         }
33208b244e21SEwan Crawford         offset += data_size;
3321a0f08674SEwan Crawford       }
3322a0f08674SEwan Crawford     }
3323a0f08674SEwan Crawford   }
3324a0f08674SEwan Crawford   strm.EOL();
3325a0f08674SEwan Crawford 
3326a0f08674SEwan Crawford   return true;
3327a0f08674SEwan Crawford }
3328a0f08674SEwan Crawford 
332905097246SAdrian Prantl // Function recalculates all our cached information about allocations by
333005097246SAdrian Prantl // jitting the RS runtime regarding each allocation we know about. Returns true
333105097246SAdrian Prantl // if all allocations could be recomputed, false otherwise.
3332b9c1b51eSKate Stone bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3333b9c1b51eSKate Stone                                                   StackFrame *frame_ptr) {
33340d2bfcfbSEwan Crawford   bool success = true;
3335b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
33360d2bfcfbSEwan Crawford     // JIT current allocation information
3337b9c1b51eSKate Stone     if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3338b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3339b9c1b51eSKate Stone                   "\n",
3340b9c1b51eSKate Stone                   alloc->id);
33410d2bfcfbSEwan Crawford       success = false;
33420d2bfcfbSEwan Crawford     }
33430d2bfcfbSEwan Crawford   }
33440d2bfcfbSEwan Crawford 
33450d2bfcfbSEwan Crawford   if (success)
33460d2bfcfbSEwan Crawford     strm.Printf("All allocations successfully recomputed");
33470d2bfcfbSEwan Crawford   strm.EOL();
33480d2bfcfbSEwan Crawford 
33490d2bfcfbSEwan Crawford   return success;
33500d2bfcfbSEwan Crawford }
33510d2bfcfbSEwan Crawford 
335280af0b9eSLuke Drummond // Prints information regarding currently loaded allocations. These details are
335380af0b9eSLuke Drummond // gathered by jitting the runtime, which has as latency. Index parameter
335480af0b9eSLuke Drummond // specifies a single allocation ID to print, or a zero value to print them all
3355b9c1b51eSKate Stone void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3356b9c1b51eSKate Stone                                           const uint32_t index) {
335715f2bd95SEwan Crawford   strm.Printf("RenderScript Allocations:");
335815f2bd95SEwan Crawford   strm.EOL();
335915f2bd95SEwan Crawford   strm.IndentMore();
336015f2bd95SEwan Crawford 
3361b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
3362b649b005SEwan Crawford     // index will only be zero if we want to print all allocations
3363b649b005SEwan Crawford     if (index != 0 && index != alloc->id)
3364b649b005SEwan Crawford       continue;
336515f2bd95SEwan Crawford 
336615f2bd95SEwan Crawford     // JIT current allocation information
336780af0b9eSLuke Drummond     if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3368b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3369b9c1b51eSKate Stone                   alloc->id);
3370b3f7f69dSAidan Dodds       strm.EOL();
337115f2bd95SEwan Crawford       continue;
337215f2bd95SEwan Crawford     }
337315f2bd95SEwan Crawford 
3374b3f7f69dSAidan Dodds     strm.Printf("%" PRIu32 ":", alloc->id);
3375b3f7f69dSAidan Dodds     strm.EOL();
337615f2bd95SEwan Crawford     strm.IndentMore();
337715f2bd95SEwan Crawford 
337815f2bd95SEwan Crawford     strm.Indent("Context: ");
337915f2bd95SEwan Crawford     if (!alloc->context.isValid())
338015f2bd95SEwan Crawford       strm.Printf("unknown\n");
338115f2bd95SEwan Crawford     else
338215f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
338315f2bd95SEwan Crawford 
338415f2bd95SEwan Crawford     strm.Indent("Address: ");
338515f2bd95SEwan Crawford     if (!alloc->address.isValid())
338615f2bd95SEwan Crawford       strm.Printf("unknown\n");
338715f2bd95SEwan Crawford     else
338815f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
338915f2bd95SEwan Crawford 
339015f2bd95SEwan Crawford     strm.Indent("Data pointer: ");
339115f2bd95SEwan Crawford     if (!alloc->data_ptr.isValid())
339215f2bd95SEwan Crawford       strm.Printf("unknown\n");
339315f2bd95SEwan Crawford     else
339415f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
339515f2bd95SEwan Crawford 
339615f2bd95SEwan Crawford     strm.Indent("Dimensions: ");
339715f2bd95SEwan Crawford     if (!alloc->dimension.isValid())
339815f2bd95SEwan Crawford       strm.Printf("unknown\n");
339915f2bd95SEwan Crawford     else
3400b3f7f69dSAidan Dodds       strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3401b9c1b51eSKate Stone                   alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3402b9c1b51eSKate Stone                   alloc->dimension.get()->dim_3);
340315f2bd95SEwan Crawford 
340415f2bd95SEwan Crawford     strm.Indent("Data Type: ");
3405b9c1b51eSKate Stone     if (!alloc->element.type.isValid() ||
3406b9c1b51eSKate Stone         !alloc->element.type_vec_size.isValid())
340715f2bd95SEwan Crawford       strm.Printf("unknown\n");
3408b9c1b51eSKate Stone     else {
34098b244e21SEwan Crawford       const int vector_size = *alloc->element.type_vec_size.get();
34102e920715SEwan Crawford       Element::DataType type = *alloc->element.type.get();
341115f2bd95SEwan Crawford 
34128b244e21SEwan Crawford       if (!alloc->element.type_name.IsEmpty())
34138b244e21SEwan Crawford         strm.Printf("%s\n", alloc->element.type_name.AsCString());
3414b9c1b51eSKate Stone       else {
3415b9c1b51eSKate Stone         // Enum value isn't monotonous, so doesn't always index
3416b9c1b51eSKate Stone         // RsDataTypeToString array
34172e920715SEwan Crawford         if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3418b9c1b51eSKate Stone           type =
3419b9c1b51eSKate Stone               static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3420b3f7f69dSAidan Dodds                                              Element::RS_TYPE_MATRIX_2X2 + 1);
34212e920715SEwan Crawford 
3422b3f7f69dSAidan Dodds         if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3423b3f7f69dSAidan Dodds                      sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3424b3f7f69dSAidan Dodds             vector_size > 4 || vector_size < 1)
342515f2bd95SEwan Crawford           strm.Printf("invalid type\n");
342615f2bd95SEwan Crawford         else
3427b9c1b51eSKate Stone           strm.Printf(
3428b9c1b51eSKate Stone               "%s\n",
3429b9c1b51eSKate Stone               AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3430b3f7f69dSAidan Dodds                                                    [vector_size - 1]);
343115f2bd95SEwan Crawford       }
34322e920715SEwan Crawford     }
343315f2bd95SEwan Crawford 
343415f2bd95SEwan Crawford     strm.Indent("Data Kind: ");
34358b244e21SEwan Crawford     if (!alloc->element.type_kind.isValid())
343615f2bd95SEwan Crawford       strm.Printf("unknown\n");
3437b9c1b51eSKate Stone     else {
34388b244e21SEwan Crawford       const Element::DataKind kind = *alloc->element.type_kind.get();
34398b244e21SEwan Crawford       if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
344015f2bd95SEwan Crawford         strm.Printf("invalid kind\n");
344115f2bd95SEwan Crawford       else
3442b9c1b51eSKate Stone         strm.Printf(
3443b9c1b51eSKate Stone             "%s\n",
3444b9c1b51eSKate Stone             AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
344515f2bd95SEwan Crawford     }
344615f2bd95SEwan Crawford 
344715f2bd95SEwan Crawford     strm.EOL();
344815f2bd95SEwan Crawford     strm.IndentLess();
344915f2bd95SEwan Crawford   }
345015f2bd95SEwan Crawford   strm.IndentLess();
345115f2bd95SEwan Crawford }
345215f2bd95SEwan Crawford 
34537dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
3454b9c1b51eSKate Stone void RenderScriptRuntime::BreakOnModuleKernels(
3455b9c1b51eSKate Stone     const RSModuleDescriptorSP rsmodule_sp) {
3456b9c1b51eSKate Stone   for (const auto &kernel : rsmodule_sp->m_kernels) {
34577dc7771cSEwan Crawford     // Don't set breakpoint on 'root' kernel
34587dc7771cSEwan Crawford     if (strcmp(kernel.m_name.AsCString(), "root") == 0)
34597dc7771cSEwan Crawford       continue;
34607dc7771cSEwan Crawford 
34617dc7771cSEwan Crawford     CreateKernelBreakpoint(kernel.m_name);
34627dc7771cSEwan Crawford   }
34637dc7771cSEwan Crawford }
34647dc7771cSEwan Crawford 
346580af0b9eSLuke Drummond // Method is internally called by the 'kernel breakpoint all' command to enable
346680af0b9eSLuke Drummond // or disable breaking on all kernels. When do_break is true we want to enable
346780af0b9eSLuke Drummond // this functionality. When do_break is false we want to disable it.
3468b9c1b51eSKate Stone void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3469b9c1b51eSKate Stone   Log *log(
3470b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
34717dc7771cSEwan Crawford 
34727dc7771cSEwan Crawford   InitSearchFilter(target);
34737dc7771cSEwan Crawford 
34747dc7771cSEwan Crawford   // Set breakpoints on all the kernels
3475b9c1b51eSKate Stone   if (do_break && !m_breakAllKernels) {
34767dc7771cSEwan Crawford     m_breakAllKernels = true;
34777dc7771cSEwan Crawford 
34787dc7771cSEwan Crawford     for (const auto &module : m_rsmodules)
34797dc7771cSEwan Crawford       BreakOnModuleKernels(module);
34807dc7771cSEwan Crawford 
3481*63e5fb76SJonas Devlieghere     LLDB_LOGF(log,
3482*63e5fb76SJonas Devlieghere               "%s(True) - breakpoints set on all currently loaded kernels.",
3483b9c1b51eSKate Stone               __FUNCTION__);
3484b9c1b51eSKate Stone   } else if (!do_break &&
3485b9c1b51eSKate Stone              m_breakAllKernels) // Breakpoints won't be set on any new kernels.
34867dc7771cSEwan Crawford   {
34877dc7771cSEwan Crawford     m_breakAllKernels = false;
34887dc7771cSEwan Crawford 
3489*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s(False) - breakpoints no longer automatically set.",
3490b9c1b51eSKate Stone               __FUNCTION__);
34917dc7771cSEwan Crawford   }
34927dc7771cSEwan Crawford }
34937dc7771cSEwan Crawford 
349405097246SAdrian Prantl // Given the name of a kernel this function creates a breakpoint using our own
349505097246SAdrian Prantl // breakpoint resolver, and returns the Breakpoint shared pointer.
34967dc7771cSEwan Crawford BreakpointSP
34970e4c4821SAdrian Prantl RenderScriptRuntime::CreateKernelBreakpoint(ConstString name) {
3498b9c1b51eSKate Stone   Log *log(
3499b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
35007dc7771cSEwan Crawford 
3501b9c1b51eSKate Stone   if (!m_filtersp) {
3502*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error, no breakpoint search filter set.",
3503*63e5fb76SJonas Devlieghere               __FUNCTION__);
35047dc7771cSEwan Crawford     return nullptr;
35057dc7771cSEwan Crawford   }
35067dc7771cSEwan Crawford 
35077dc7771cSEwan Crawford   BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3508b842f2ecSJim Ingham   Target &target = GetProcess()->GetTarget();
3509b842f2ecSJim Ingham   BreakpointSP bp = target.CreateBreakpoint(
3510b9c1b51eSKate Stone       m_filtersp, resolver_sp, false, false, false);
35117dc7771cSEwan Crawford 
3512b9c1b51eSKate Stone   // Give RS breakpoints a specific name, so the user can manipulate them as a
3513b9c1b51eSKate Stone   // group.
351497206d57SZachary Turner   Status err;
3515b842f2ecSJim Ingham   target.AddNameToBreakpoint(bp, "RenderScriptKernel", err);
3516b842f2ecSJim Ingham   if (err.Fail() && log)
3517*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error setting break name, '%s'.", __FUNCTION__,
3518b3bbcb12SLuke Drummond               err.AsCString());
3519b3bbcb12SLuke Drummond 
3520b3bbcb12SLuke Drummond   return bp;
3521b3bbcb12SLuke Drummond }
3522b3bbcb12SLuke Drummond 
3523b3bbcb12SLuke Drummond BreakpointSP
35240e4c4821SAdrian Prantl RenderScriptRuntime::CreateReductionBreakpoint(ConstString name,
3525b3bbcb12SLuke Drummond                                                int kernel_types) {
3526b3bbcb12SLuke Drummond   Log *log(
3527b3bbcb12SLuke Drummond       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3528b3bbcb12SLuke Drummond 
3529b3bbcb12SLuke Drummond   if (!m_filtersp) {
3530*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error, no breakpoint search filter set.",
3531*63e5fb76SJonas Devlieghere               __FUNCTION__);
3532b3bbcb12SLuke Drummond     return nullptr;
3533b3bbcb12SLuke Drummond   }
3534b3bbcb12SLuke Drummond 
3535b3bbcb12SLuke Drummond   BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3536b3bbcb12SLuke Drummond       nullptr, name, &m_rsmodules, kernel_types));
3537b842f2ecSJim Ingham   Target &target = GetProcess()->GetTarget();
3538b842f2ecSJim Ingham   BreakpointSP bp = target.CreateBreakpoint(
3539b3bbcb12SLuke Drummond       m_filtersp, resolver_sp, false, false, false);
3540b3bbcb12SLuke Drummond 
3541b3bbcb12SLuke Drummond   // Give RS breakpoints a specific name, so the user can manipulate them as a
3542b3bbcb12SLuke Drummond   // group.
354397206d57SZachary Turner   Status err;
3544b842f2ecSJim Ingham   target.AddNameToBreakpoint(bp, "RenderScriptReduction", err);
3545b842f2ecSJim Ingham   if (err.Fail() && log)
3546*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error setting break name, '%s'.", __FUNCTION__,
3547b9c1b51eSKate Stone               err.AsCString());
354854782db7SEwan Crawford 
35497dc7771cSEwan Crawford   return bp;
35507dc7771cSEwan Crawford }
35517dc7771cSEwan Crawford 
3552b9c1b51eSKate Stone // Given an expression for a variable this function tries to calculate the
355380af0b9eSLuke Drummond // variable's value. If this is possible it returns true and sets the uint64_t
355480af0b9eSLuke Drummond // parameter to the variables unsigned value. Otherwise function returns false.
3555b9c1b51eSKate Stone bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3556b9c1b51eSKate Stone                                                 const char *var_name,
3557b9c1b51eSKate Stone                                                 uint64_t &val) {
3558018f5a7eSEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
355997206d57SZachary Turner   Status err;
3560018f5a7eSEwan Crawford   VariableSP var_sp;
3561018f5a7eSEwan Crawford 
3562018f5a7eSEwan Crawford   // Find variable in stack frame
3563b3f7f69dSAidan Dodds   ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3564b3f7f69dSAidan Dodds       var_name, eNoDynamicValues,
3565b9c1b51eSKate Stone       StackFrame::eExpressionPathOptionCheckPtrVsMember |
3566b9c1b51eSKate Stone           StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
356780af0b9eSLuke Drummond       var_sp, err));
356880af0b9eSLuke Drummond   if (!err.Success()) {
3569*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error, couldn't find '%s' in frame", __FUNCTION__,
3570b9c1b51eSKate Stone               var_name);
3571018f5a7eSEwan Crawford     return false;
3572018f5a7eSEwan Crawford   }
3573018f5a7eSEwan Crawford 
3574b3f7f69dSAidan Dodds   // Find the uint32_t value for the variable
3575018f5a7eSEwan Crawford   bool success = false;
3576018f5a7eSEwan Crawford   val = value_sp->GetValueAsUnsigned(0, &success);
3577b9c1b51eSKate Stone   if (!success) {
3578*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error, couldn't parse '%s' as an uint32_t.",
3579b9c1b51eSKate Stone               __FUNCTION__, var_name);
3580018f5a7eSEwan Crawford     return false;
3581018f5a7eSEwan Crawford   }
3582018f5a7eSEwan Crawford 
3583018f5a7eSEwan Crawford   return true;
3584018f5a7eSEwan Crawford }
3585018f5a7eSEwan Crawford 
3586b9c1b51eSKate Stone // Function attempts to find the current coordinate of a kernel invocation by
358780af0b9eSLuke Drummond // investigating the values of frame variables in the .expand function. These
358880af0b9eSLuke Drummond // coordinates are returned via the coord array reference parameter. Returns
358980af0b9eSLuke Drummond // true if the coordinates could be found, and false otherwise.
3590b9c1b51eSKate Stone bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3591b9c1b51eSKate Stone                                               Thread *thread_ptr) {
359200f56eebSLuke Drummond   static const char *const x_expr = "rsIndex";
359300f56eebSLuke Drummond   static const char *const y_expr = "p->current.y";
359400f56eebSLuke Drummond   static const char *const z_expr = "p->current.z";
35951e05c3bcSGreg Clayton 
35964f8817c2SEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
35974f8817c2SEwan Crawford 
3598b9c1b51eSKate Stone   if (!thread_ptr) {
3599*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - Error, No thread pointer", __FUNCTION__);
36004f8817c2SEwan Crawford 
36014f8817c2SEwan Crawford     return false;
36024f8817c2SEwan Crawford   }
36034f8817c2SEwan Crawford 
3604b9c1b51eSKate Stone   // Walk the call stack looking for a function whose name has the suffix
360580af0b9eSLuke Drummond   // '.expand' and contains the variables we're looking for.
3606b9c1b51eSKate Stone   for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
36074f8817c2SEwan Crawford     if (!thread_ptr->SetSelectedFrameByIndex(i))
36084f8817c2SEwan Crawford       continue;
36094f8817c2SEwan Crawford 
36104f8817c2SEwan Crawford     StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
36114f8817c2SEwan Crawford     if (!frame_sp)
36124f8817c2SEwan Crawford       continue;
36134f8817c2SEwan Crawford 
36144f8817c2SEwan Crawford     // Find the function name
3615991e4453SZachary Turner     const SymbolContext sym_ctx =
3616991e4453SZachary Turner         frame_sp->GetSymbolContext(eSymbolContextFunction);
361700f56eebSLuke Drummond     const ConstString func_name = sym_ctx.GetFunctionName();
361800f56eebSLuke Drummond     if (!func_name)
36194f8817c2SEwan Crawford       continue;
36204f8817c2SEwan Crawford 
3621*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - Inspecting function '%s'", __FUNCTION__,
362200f56eebSLuke Drummond               func_name.GetCString());
36234f8817c2SEwan Crawford 
36244f8817c2SEwan Crawford     // Check if function name has .expand suffix
362500f56eebSLuke Drummond     if (!func_name.GetStringRef().endswith(".expand"))
36264f8817c2SEwan Crawford       continue;
36274f8817c2SEwan Crawford 
3628*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - Found .expand function '%s'", __FUNCTION__,
362900f56eebSLuke Drummond               func_name.GetCString());
36304f8817c2SEwan Crawford 
363105097246SAdrian Prantl     // Get values for variables in .expand frame that tell us the current
363205097246SAdrian Prantl     // kernel invocation
363300f56eebSLuke Drummond     uint64_t x, y, z;
363400f56eebSLuke Drummond     bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
363500f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
363600f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, z_expr, z);
36374f8817c2SEwan Crawford 
363800f56eebSLuke Drummond     if (found) {
363900f56eebSLuke Drummond       // The RenderScript runtime uses uint32_t for these vars. If they're not
364000f56eebSLuke Drummond       // within bounds, our frame parsing is garbage
364100f56eebSLuke Drummond       assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
364200f56eebSLuke Drummond       coord.x = (uint32_t)x;
364300f56eebSLuke Drummond       coord.y = (uint32_t)y;
364400f56eebSLuke Drummond       coord.z = (uint32_t)z;
36454f8817c2SEwan Crawford       return true;
36464f8817c2SEwan Crawford     }
364700f56eebSLuke Drummond   }
36484f8817c2SEwan Crawford   return false;
36494f8817c2SEwan Crawford }
36504f8817c2SEwan Crawford 
3651b9c1b51eSKate Stone // Callback when a kernel breakpoint hits and we're looking for a specific
365280af0b9eSLuke Drummond // coordinate. Baton parameter contains a pointer to the target coordinate we
365305097246SAdrian Prantl // want to break on. Function then checks the .expand frame for the current
365405097246SAdrian Prantl // coordinate and breaks to user if it matches. Parameter 'break_id' is the id
365505097246SAdrian Prantl // of the Breakpoint which made the callback. Parameter 'break_loc_id' is the
365605097246SAdrian Prantl // id for the BreakpointLocation which was hit, a single logical breakpoint can
365705097246SAdrian Prantl // have multiple addresses.
3658b9c1b51eSKate Stone bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3659b9c1b51eSKate Stone                                               StoppointCallbackContext *ctx,
3660b9c1b51eSKate Stone                                               user_id_t break_id,
3661b9c1b51eSKate Stone                                               user_id_t break_loc_id) {
3662b9c1b51eSKate Stone   Log *log(
3663b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3664018f5a7eSEwan Crawford 
3665b9c1b51eSKate Stone   assert(baton &&
3666b9c1b51eSKate Stone          "Error: null baton in conditional kernel breakpoint callback");
3667018f5a7eSEwan Crawford 
3668018f5a7eSEwan Crawford   // Coordinate we want to stop on
366900f56eebSLuke Drummond   RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3670018f5a7eSEwan Crawford 
3671*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__,
3672*63e5fb76SJonas Devlieghere             break_id, target_coord.x, target_coord.y, target_coord.z);
3673018f5a7eSEwan Crawford 
36744f8817c2SEwan Crawford   // Select current thread
3675018f5a7eSEwan Crawford   ExecutionContext context(ctx->exe_ctx_ref);
36764f8817c2SEwan Crawford   Thread *thread_ptr = context.GetThreadPtr();
36774f8817c2SEwan Crawford   assert(thread_ptr && "Null thread pointer");
36784f8817c2SEwan Crawford 
36794f8817c2SEwan Crawford   // Find current kernel invocation from .expand frame variables
368000f56eebSLuke Drummond   RSCoordinate current_coord{};
3681b9c1b51eSKate Stone   if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3682*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - Error, couldn't select .expand stack frame",
3683b9c1b51eSKate Stone               __FUNCTION__);
3684018f5a7eSEwan Crawford     return false;
3685018f5a7eSEwan Crawford   }
3686018f5a7eSEwan Crawford 
3687*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - " FMT_COORD, __FUNCTION__, current_coord.x,
368800f56eebSLuke Drummond             current_coord.y, current_coord.z);
3689018f5a7eSEwan Crawford 
3690b9c1b51eSKate Stone   // Check if the current kernel invocation coordinate matches our target
3691b9c1b51eSKate Stone   // coordinate
369200f56eebSLuke Drummond   if (target_coord == current_coord) {
3693*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
369400f56eebSLuke Drummond               current_coord.y, current_coord.z);
3695018f5a7eSEwan Crawford 
3696b9c1b51eSKate Stone     BreakpointSP breakpoint_sp =
3697b9c1b51eSKate Stone         context.GetTargetPtr()->GetBreakpointByID(break_id);
3698b9c1b51eSKate Stone     assert(breakpoint_sp != nullptr &&
3699b9c1b51eSKate Stone            "Error: Couldn't find breakpoint matching break id for callback");
3700b9c1b51eSKate Stone     breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3701b9c1b51eSKate Stone                                       // should only be hit once.
3702018f5a7eSEwan Crawford     return true;
3703018f5a7eSEwan Crawford   }
3704018f5a7eSEwan Crawford 
3705018f5a7eSEwan Crawford   // No match on coordinate
3706018f5a7eSEwan Crawford   return false;
3707018f5a7eSEwan Crawford }
3708018f5a7eSEwan Crawford 
370900f56eebSLuke Drummond void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
371000f56eebSLuke Drummond                                          const RSCoordinate &coord) {
371100f56eebSLuke Drummond   messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
371200f56eebSLuke Drummond                   coord.x, coord.y, coord.z);
371300f56eebSLuke Drummond   messages.EOL();
371400f56eebSLuke Drummond 
371500f56eebSLuke Drummond   // Allocate memory for the baton, and copy over coordinate
371600f56eebSLuke Drummond   RSCoordinate *baton = new RSCoordinate(coord);
371700f56eebSLuke Drummond 
371800f56eebSLuke Drummond   // Create a callback that will be invoked every time the breakpoint is hit.
371900f56eebSLuke Drummond   // The baton object passed to the handler is the target coordinate we want to
372000f56eebSLuke Drummond   // break on.
372100f56eebSLuke Drummond   bp->SetCallback(KernelBreakpointHit, baton, true);
372200f56eebSLuke Drummond 
372300f56eebSLuke Drummond   // Store a shared pointer to the baton, so the memory will eventually be
372400f56eebSLuke Drummond   // cleaned up after destruction
372500f56eebSLuke Drummond   m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
372600f56eebSLuke Drummond }
372700f56eebSLuke Drummond 
372805097246SAdrian Prantl // Tries to set a breakpoint on the start of a kernel, resolved using the
372905097246SAdrian Prantl // kernel name. Argument 'coords', represents a three dimensional coordinate
373005097246SAdrian Prantl // which can be used to specify a single kernel instance to break on. If this
373105097246SAdrian Prantl // is set then we add a callback to the breakpoint.
373200f56eebSLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
373300f56eebSLuke Drummond                                                   Stream &messages,
373400f56eebSLuke Drummond                                                   const char *name,
373500f56eebSLuke Drummond                                                   const RSCoordinate *coord) {
373600f56eebSLuke Drummond   if (!name)
373700f56eebSLuke Drummond     return false;
37384640cde1SColin Riley 
37397dc7771cSEwan Crawford   InitSearchFilter(target);
374098156583SEwan Crawford 
37414640cde1SColin Riley   ConstString kernel_name(name);
37427dc7771cSEwan Crawford   BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
374300f56eebSLuke Drummond   if (!bp)
374400f56eebSLuke Drummond     return false;
3745018f5a7eSEwan Crawford 
3746018f5a7eSEwan Crawford   // We have a conditional breakpoint on a specific coordinate
374700f56eebSLuke Drummond   if (coord)
374800f56eebSLuke Drummond     SetConditional(bp, messages, *coord);
3749018f5a7eSEwan Crawford 
375000f56eebSLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3751018f5a7eSEwan Crawford 
375200f56eebSLuke Drummond   return true;
37534640cde1SColin Riley }
37544640cde1SColin Riley 
375521fed052SAidan Dodds BreakpointSP
37560e4c4821SAdrian Prantl RenderScriptRuntime::CreateScriptGroupBreakpoint(ConstString name,
375721fed052SAidan Dodds                                                  bool stop_on_all) {
375821fed052SAidan Dodds   Log *log(
375921fed052SAidan Dodds       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
376021fed052SAidan Dodds 
376121fed052SAidan Dodds   if (!m_filtersp) {
3762*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error, no breakpoint search filter set.",
3763*63e5fb76SJonas Devlieghere               __FUNCTION__);
376421fed052SAidan Dodds     return nullptr;
376521fed052SAidan Dodds   }
376621fed052SAidan Dodds 
376721fed052SAidan Dodds   BreakpointResolverSP resolver_sp(new RSScriptGroupBreakpointResolver(
376821fed052SAidan Dodds       nullptr, name, m_scriptGroups, stop_on_all));
3769b842f2ecSJim Ingham   Target &target = GetProcess()->GetTarget();
3770b842f2ecSJim Ingham   BreakpointSP bp = target.CreateBreakpoint(
377121fed052SAidan Dodds       m_filtersp, resolver_sp, false, false, false);
377221fed052SAidan Dodds   // Give RS breakpoints a specific name, so the user can manipulate them as a
377321fed052SAidan Dodds   // group.
377497206d57SZachary Turner   Status err;
3775b842f2ecSJim Ingham   target.AddNameToBreakpoint(bp, name.GetCString(), err);
3776b842f2ecSJim Ingham   if (err.Fail() && log)
3777*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s - error setting break name, '%s'.", __FUNCTION__,
377821fed052SAidan Dodds               err.AsCString());
377921fed052SAidan Dodds   // ask the breakpoint to resolve itself
378021fed052SAidan Dodds   bp->ResolveBreakpoint();
378121fed052SAidan Dodds   return bp;
378221fed052SAidan Dodds }
378321fed052SAidan Dodds 
378421fed052SAidan Dodds bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target,
378521fed052SAidan Dodds                                                        Stream &strm,
37860e4c4821SAdrian Prantl                                                        ConstString name,
378721fed052SAidan Dodds                                                        bool multi) {
378821fed052SAidan Dodds   InitSearchFilter(target);
378921fed052SAidan Dodds   BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi);
379021fed052SAidan Dodds   if (bp)
379121fed052SAidan Dodds     bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
379221fed052SAidan Dodds   return bool(bp);
379321fed052SAidan Dodds }
379421fed052SAidan Dodds 
3795b3bbcb12SLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3796b3bbcb12SLuke Drummond                                                      Stream &messages,
3797b3bbcb12SLuke Drummond                                                      const char *reduce_name,
3798b3bbcb12SLuke Drummond                                                      const RSCoordinate *coord,
3799b3bbcb12SLuke Drummond                                                      int kernel_types) {
3800b3bbcb12SLuke Drummond   if (!reduce_name)
3801b3bbcb12SLuke Drummond     return false;
3802b3bbcb12SLuke Drummond 
3803b3bbcb12SLuke Drummond   InitSearchFilter(target);
3804b3bbcb12SLuke Drummond   BreakpointSP bp =
3805b3bbcb12SLuke Drummond       CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3806b3bbcb12SLuke Drummond   if (!bp)
3807b3bbcb12SLuke Drummond     return false;
3808b3bbcb12SLuke Drummond 
3809b3bbcb12SLuke Drummond   if (coord)
3810b3bbcb12SLuke Drummond     SetConditional(bp, messages, *coord);
3811b3bbcb12SLuke Drummond 
3812b3bbcb12SLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3813b3bbcb12SLuke Drummond 
3814b3bbcb12SLuke Drummond   return true;
3815b3bbcb12SLuke Drummond }
3816b3bbcb12SLuke Drummond 
3817b9c1b51eSKate Stone void RenderScriptRuntime::DumpModules(Stream &strm) const {
38185ec532a9SColin Riley   strm.Printf("RenderScript Modules:");
38195ec532a9SColin Riley   strm.EOL();
38205ec532a9SColin Riley   strm.IndentMore();
3821b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
38224640cde1SColin Riley     module->Dump(strm);
38235ec532a9SColin Riley   }
38245ec532a9SColin Riley   strm.IndentLess();
38255ec532a9SColin Riley }
38265ec532a9SColin Riley 
382778f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails *
3828b9c1b51eSKate Stone RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3829b9c1b51eSKate Stone   for (const auto &s : m_scripts) {
383078f339d1SEwan Crawford     if (s->script.isValid())
383178f339d1SEwan Crawford       if (*s->script == address)
383278f339d1SEwan Crawford         return s.get();
383378f339d1SEwan Crawford   }
3834b9c1b51eSKate Stone   if (create) {
383578f339d1SEwan Crawford     std::unique_ptr<ScriptDetails> s(new ScriptDetails);
383678f339d1SEwan Crawford     s->script = address;
383778f339d1SEwan Crawford     m_scripts.push_back(std::move(s));
3838d10ca9deSEwan Crawford     return m_scripts.back().get();
383978f339d1SEwan Crawford   }
384078f339d1SEwan Crawford   return nullptr;
384178f339d1SEwan Crawford }
384278f339d1SEwan Crawford 
384378f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails *
3844b9c1b51eSKate Stone RenderScriptRuntime::LookUpAllocation(addr_t address) {
3845b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
384678f339d1SEwan Crawford     if (a->address.isValid())
384778f339d1SEwan Crawford       if (*a->address == address)
384878f339d1SEwan Crawford         return a.get();
384978f339d1SEwan Crawford   }
38505d057637SLuke Drummond   return nullptr;
38515d057637SLuke Drummond }
38525d057637SLuke Drummond 
38535d057637SLuke Drummond RenderScriptRuntime::AllocationDetails *
3854b9c1b51eSKate Stone RenderScriptRuntime::CreateAllocation(addr_t address) {
38555d057637SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
38565d057637SLuke Drummond 
38575d057637SLuke Drummond   // Remove any previous allocation which contains the same address
38585d057637SLuke Drummond   auto it = m_allocations.begin();
3859b9c1b51eSKate Stone   while (it != m_allocations.end()) {
3860b9c1b51eSKate Stone     if (*((*it)->address) == address) {
3861*63e5fb76SJonas Devlieghere       LLDB_LOGF(log, "%s - Removing allocation id: %d, address: 0x%" PRIx64,
3862b9c1b51eSKate Stone                 __FUNCTION__, (*it)->id, address);
38635d057637SLuke Drummond 
38645d057637SLuke Drummond       it = m_allocations.erase(it);
3865b9c1b51eSKate Stone     } else {
38665d057637SLuke Drummond       it++;
38675d057637SLuke Drummond     }
38685d057637SLuke Drummond   }
38695d057637SLuke Drummond 
387078f339d1SEwan Crawford   std::unique_ptr<AllocationDetails> a(new AllocationDetails);
387178f339d1SEwan Crawford   a->address = address;
387278f339d1SEwan Crawford   m_allocations.push_back(std::move(a));
3873d10ca9deSEwan Crawford   return m_allocations.back().get();
387478f339d1SEwan Crawford }
387578f339d1SEwan Crawford 
387621fed052SAidan Dodds bool RenderScriptRuntime::ResolveKernelName(lldb::addr_t kernel_addr,
387721fed052SAidan Dodds                                             ConstString &name) {
387821fed052SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
387921fed052SAidan Dodds 
388021fed052SAidan Dodds   Target &target = GetProcess()->GetTarget();
388121fed052SAidan Dodds   Address resolved;
388221fed052SAidan Dodds   // RenderScript module
388321fed052SAidan Dodds   if (!target.GetSectionLoadList().ResolveLoadAddress(kernel_addr, resolved)) {
3884*63e5fb76SJonas Devlieghere     LLDB_LOGF(log, "%s: unable to resolve 0x%" PRIx64 " to a loaded symbol",
388521fed052SAidan Dodds               __FUNCTION__, kernel_addr);
388621fed052SAidan Dodds     return false;
388721fed052SAidan Dodds   }
388821fed052SAidan Dodds 
388921fed052SAidan Dodds   Symbol *sym = resolved.CalculateSymbolContextSymbol();
389021fed052SAidan Dodds   if (!sym)
389121fed052SAidan Dodds     return false;
389221fed052SAidan Dodds 
389321fed052SAidan Dodds   name = sym->GetName();
389421fed052SAidan Dodds   assert(IsRenderScriptModule(resolved.CalculateSymbolContextModule()));
3895*63e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s: 0x%" PRIx64 " resolved to the symbol '%s'", __FUNCTION__,
389621fed052SAidan Dodds             kernel_addr, name.GetCString());
389721fed052SAidan Dodds   return true;
389821fed052SAidan Dodds }
389921fed052SAidan Dodds 
3900b9c1b51eSKate Stone void RSModuleDescriptor::Dump(Stream &strm) const {
39017f193d69SLuke Drummond   int indent = strm.GetIndentLevel();
39027f193d69SLuke Drummond 
39035ec532a9SColin Riley   strm.Indent();
39045ec532a9SColin Riley   m_module->GetFileSpec().Dump(&strm);
39057f193d69SLuke Drummond   strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
39067f193d69SLuke Drummond                                              : "Debug info does not exist.");
39075ec532a9SColin Riley   strm.EOL();
39085ec532a9SColin Riley   strm.IndentMore();
39097f193d69SLuke Drummond 
39105ec532a9SColin Riley   strm.Indent();
3911189598edSColin Riley   strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
39125ec532a9SColin Riley   strm.EOL();
39135ec532a9SColin Riley   strm.IndentMore();
3914b9c1b51eSKate Stone   for (const auto &global : m_globals) {
39155ec532a9SColin Riley     global.Dump(strm);
39165ec532a9SColin Riley   }
39175ec532a9SColin Riley   strm.IndentLess();
39187f193d69SLuke Drummond 
39195ec532a9SColin Riley   strm.Indent();
3920189598edSColin Riley   strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
39215ec532a9SColin Riley   strm.EOL();
39225ec532a9SColin Riley   strm.IndentMore();
3923b9c1b51eSKate Stone   for (const auto &kernel : m_kernels) {
39245ec532a9SColin Riley     kernel.Dump(strm);
39255ec532a9SColin Riley   }
39267f193d69SLuke Drummond   strm.IndentLess();
39277f193d69SLuke Drummond 
39287f193d69SLuke Drummond   strm.Indent();
39294640cde1SColin Riley   strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
39304640cde1SColin Riley   strm.EOL();
39314640cde1SColin Riley   strm.IndentMore();
3932b9c1b51eSKate Stone   for (const auto &key_val : m_pragmas) {
39337f193d69SLuke Drummond     strm.Indent();
39344640cde1SColin Riley     strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
39354640cde1SColin Riley     strm.EOL();
39364640cde1SColin Riley   }
39377f193d69SLuke Drummond   strm.IndentLess();
39387f193d69SLuke Drummond 
39397f193d69SLuke Drummond   strm.Indent();
39407f193d69SLuke Drummond   strm.Printf("Reductions: %" PRIu64,
39417f193d69SLuke Drummond               static_cast<uint64_t>(m_reductions.size()));
39427f193d69SLuke Drummond   strm.EOL();
39437f193d69SLuke Drummond   strm.IndentMore();
39447f193d69SLuke Drummond   for (const auto &reduction : m_reductions) {
39457f193d69SLuke Drummond     reduction.Dump(strm);
39467f193d69SLuke Drummond   }
39477f193d69SLuke Drummond 
39487f193d69SLuke Drummond   strm.SetIndentLevel(indent);
39495ec532a9SColin Riley }
39505ec532a9SColin Riley 
3951b9c1b51eSKate Stone void RSGlobalDescriptor::Dump(Stream &strm) const {
39525ec532a9SColin Riley   strm.Indent(m_name.AsCString());
39534640cde1SColin Riley   VariableList var_list;
395434cda14bSPavel Labath   m_module->m_module->FindGlobalVariables(m_name, nullptr, 1U, var_list);
3955b9c1b51eSKate Stone   if (var_list.GetSize() == 1) {
39564640cde1SColin Riley     auto var = var_list.GetVariableAtIndex(0);
39574640cde1SColin Riley     auto type = var->GetType();
3958b9c1b51eSKate Stone     if (type) {
39594640cde1SColin Riley       strm.Printf(" - ");
39604640cde1SColin Riley       type->DumpTypeName(&strm);
3961b9c1b51eSKate Stone     } else {
39624640cde1SColin Riley       strm.Printf(" - Unknown Type");
39634640cde1SColin Riley     }
3964b9c1b51eSKate Stone   } else {
39654640cde1SColin Riley     strm.Printf(" - variable identified, but not found in binary");
3966b9c1b51eSKate Stone     const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
3967b9c1b51eSKate Stone         m_name, eSymbolTypeData);
3968b9c1b51eSKate Stone     if (s) {
39694640cde1SColin Riley       strm.Printf(" (symbol exists) ");
39704640cde1SColin Riley     }
39714640cde1SColin Riley   }
39724640cde1SColin Riley 
39735ec532a9SColin Riley   strm.EOL();
39745ec532a9SColin Riley }
39755ec532a9SColin Riley 
3976b9c1b51eSKate Stone void RSKernelDescriptor::Dump(Stream &strm) const {
39775ec532a9SColin Riley   strm.Indent(m_name.AsCString());
39785ec532a9SColin Riley   strm.EOL();
39795ec532a9SColin Riley }
39805ec532a9SColin Riley 
39817f193d69SLuke Drummond void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
39827f193d69SLuke Drummond   stream.Indent(m_reduce_name.AsCString());
39837f193d69SLuke Drummond   stream.IndentMore();
39847f193d69SLuke Drummond   stream.EOL();
39857f193d69SLuke Drummond   stream.Indent();
39867f193d69SLuke Drummond   stream.Printf("accumulator: %s", m_accum_name.AsCString());
39877f193d69SLuke Drummond   stream.EOL();
39887f193d69SLuke Drummond   stream.Indent();
39897f193d69SLuke Drummond   stream.Printf("initializer: %s", m_init_name.AsCString());
39907f193d69SLuke Drummond   stream.EOL();
39917f193d69SLuke Drummond   stream.Indent();
39927f193d69SLuke Drummond   stream.Printf("combiner: %s", m_comb_name.AsCString());
39937f193d69SLuke Drummond   stream.EOL();
39947f193d69SLuke Drummond   stream.Indent();
39957f193d69SLuke Drummond   stream.Printf("outconverter: %s", m_outc_name.AsCString());
39967f193d69SLuke Drummond   stream.EOL();
39977f193d69SLuke Drummond   // XXX This is currently unspecified by RenderScript, and unused
39987f193d69SLuke Drummond   // stream.Indent();
39997f193d69SLuke Drummond   // stream.Printf("halter: '%s'", m_init_name.AsCString());
40007f193d69SLuke Drummond   // stream.EOL();
40017f193d69SLuke Drummond   stream.IndentLess();
40027f193d69SLuke Drummond }
40037f193d69SLuke Drummond 
4004b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
40055ec532a9SColin Riley public:
40065ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
4007b9c1b51eSKate Stone       : CommandObjectParsed(
4008b9c1b51eSKate Stone             interpreter, "renderscript module dump",
4009b9c1b51eSKate Stone             "Dumps renderscript specific information for all modules.",
4010b9c1b51eSKate Stone             "renderscript module dump",
4011b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
40125ec532a9SColin Riley 
4013222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
40145ec532a9SColin Riley 
4015b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4016056f6f18SAlex Langford     RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4017056f6f18SAlex Langford         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4018056f6f18SAlex Langford             eLanguageTypeExtRenderScript));
40195ec532a9SColin Riley     runtime->DumpModules(result.GetOutputStream());
40205ec532a9SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
40215ec532a9SColin Riley     return true;
40225ec532a9SColin Riley   }
40235ec532a9SColin Riley };
40245ec532a9SColin Riley 
4025b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
40265ec532a9SColin Riley public:
40275ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
4028b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript module",
4029b9c1b51eSKate Stone                                "Commands that deal with RenderScript modules.",
4030b9c1b51eSKate Stone                                nullptr) {
4031b9c1b51eSKate Stone     LoadSubCommand(
4032b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
4033b9c1b51eSKate Stone                     interpreter)));
40345ec532a9SColin Riley   }
40355ec532a9SColin Riley 
4036222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModule() override = default;
40375ec532a9SColin Riley };
40385ec532a9SColin Riley 
4039b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
40404640cde1SColin Riley public:
40414640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
4042b9c1b51eSKate Stone       : CommandObjectParsed(
4043b9c1b51eSKate Stone             interpreter, "renderscript kernel list",
4044b3f7f69dSAidan Dodds             "Lists renderscript kernel names and associated script resources.",
4045b9c1b51eSKate Stone             "renderscript kernel list",
4046b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
40474640cde1SColin Riley 
4048222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelList() override = default;
40494640cde1SColin Riley 
4050b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4051056f6f18SAlex Langford     RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4052056f6f18SAlex Langford         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4053056f6f18SAlex Langford             eLanguageTypeExtRenderScript));
40544640cde1SColin Riley     runtime->DumpKernels(result.GetOutputStream());
40554640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
40564640cde1SColin Riley     return true;
40574640cde1SColin Riley   }
40584640cde1SColin Riley };
40594640cde1SColin Riley 
40608fe53c49STatyana Krasnukha static constexpr OptionDefinition g_renderscript_reduction_bp_set_options[] = {
4061b3bbcb12SLuke Drummond     {LLDB_OPT_SET_1, false, "function-role", 't',
40628fe53c49STatyana Krasnukha      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOneLiner,
4063b3bbcb12SLuke Drummond      "Break on a comma separated set of reduction kernel types "
4064b3bbcb12SLuke Drummond      "(accumulator,outcoverter,combiner,initializer"},
4065b3bbcb12SLuke Drummond     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
40668fe53c49STatyana Krasnukha      nullptr, {}, 0, eArgTypeValue,
4067b3bbcb12SLuke Drummond      "Set a breakpoint on a single invocation of the kernel with specified "
4068b3bbcb12SLuke Drummond      "coordinate.\n"
4069b3bbcb12SLuke Drummond      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4070b3bbcb12SLuke Drummond      "integers representing kernel dimensions. "
4071b3bbcb12SLuke Drummond      "Any unset dimensions will be defaulted to zero."}};
4072b3bbcb12SLuke Drummond 
4073b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReductionBreakpointSet
4074b3bbcb12SLuke Drummond     : public CommandObjectParsed {
4075b3bbcb12SLuke Drummond public:
4076b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4077b3bbcb12SLuke Drummond       CommandInterpreter &interpreter)
4078b3bbcb12SLuke Drummond       : CommandObjectParsed(
4079b3bbcb12SLuke Drummond             interpreter, "renderscript reduction breakpoint set",
4080b3bbcb12SLuke Drummond             "Set a breakpoint on named RenderScript general reductions",
4081b3bbcb12SLuke Drummond             "renderscript reduction breakpoint set  <kernel_name> [-t "
4082b3bbcb12SLuke Drummond             "<reduction_kernel_type,...>]",
4083b3bbcb12SLuke Drummond             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4084b3bbcb12SLuke Drummond                 eCommandProcessMustBePaused),
4085b3bbcb12SLuke Drummond         m_options(){};
4086b3bbcb12SLuke Drummond 
4087b3bbcb12SLuke Drummond   class CommandOptions : public Options {
4088b3bbcb12SLuke Drummond   public:
4089b3bbcb12SLuke Drummond     CommandOptions()
4090b3bbcb12SLuke Drummond         : Options(),
4091b3bbcb12SLuke Drummond           m_kernel_types(RSReduceBreakpointResolver::eKernelTypeAll) {}
4092b3bbcb12SLuke Drummond 
4093b3bbcb12SLuke Drummond     ~CommandOptions() override = default;
4094b3bbcb12SLuke Drummond 
409597206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4096b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
409797206d57SZachary Turner       Status err;
4098b3bbcb12SLuke Drummond       StreamString err_str;
4099b3bbcb12SLuke Drummond       const int short_option = m_getopt_table[option_idx].val;
4100b3bbcb12SLuke Drummond       switch (short_option) {
4101b3bbcb12SLuke Drummond       case 't':
4102fe11483bSZachary Turner         if (!ParseReductionTypes(option_arg, err_str))
4103b3bbcb12SLuke Drummond           err.SetErrorStringWithFormat(
4104fe11483bSZachary Turner               "Unable to deduce reduction types for %s: %s",
4105fe11483bSZachary Turner               option_arg.str().c_str(), err_str.GetData());
4106b3bbcb12SLuke Drummond         break;
4107b3bbcb12SLuke Drummond       case 'c': {
4108b3bbcb12SLuke Drummond         auto coord = RSCoordinate{};
4109fe11483bSZachary Turner         if (!ParseCoordinate(option_arg, coord))
4110b3bbcb12SLuke Drummond           err.SetErrorStringWithFormat("unable to parse coordinate for %s",
4111fe11483bSZachary Turner                                        option_arg.str().c_str());
4112b3bbcb12SLuke Drummond         else {
4113b3bbcb12SLuke Drummond           m_have_coord = true;
4114b3bbcb12SLuke Drummond           m_coord = coord;
4115b3bbcb12SLuke Drummond         }
4116b3bbcb12SLuke Drummond         break;
4117b3bbcb12SLuke Drummond       }
4118b3bbcb12SLuke Drummond       default:
4119b3bbcb12SLuke Drummond         err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
4120b3bbcb12SLuke Drummond       }
4121b3bbcb12SLuke Drummond       return err;
4122b3bbcb12SLuke Drummond     }
4123b3bbcb12SLuke Drummond 
4124b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4125b3bbcb12SLuke Drummond       m_have_coord = false;
4126b3bbcb12SLuke Drummond     }
4127b3bbcb12SLuke Drummond 
4128b3bbcb12SLuke Drummond     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4129b3bbcb12SLuke Drummond       return llvm::makeArrayRef(g_renderscript_reduction_bp_set_options);
4130b3bbcb12SLuke Drummond     }
4131b3bbcb12SLuke Drummond 
4132fe11483bSZachary Turner     bool ParseReductionTypes(llvm::StringRef option_val,
4133fe11483bSZachary Turner                              StreamString &err_str) {
4134b3bbcb12SLuke Drummond       m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
4135b3bbcb12SLuke Drummond       const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
4136b3bbcb12SLuke Drummond         return llvm::StringSwitch<int>(name)
4137b3bbcb12SLuke Drummond             .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
4138b3bbcb12SLuke Drummond             .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
4139b3bbcb12SLuke Drummond             .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
4140b3bbcb12SLuke Drummond             .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
4141b3bbcb12SLuke Drummond             .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
4142b3bbcb12SLuke Drummond             // Currently not exposed by the runtime
4143b3bbcb12SLuke Drummond             // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
4144b3bbcb12SLuke Drummond             .Default(0);
4145b3bbcb12SLuke Drummond       };
4146b3bbcb12SLuke Drummond 
4147b3bbcb12SLuke Drummond       // Matching a comma separated list of known words is fairly
414805097246SAdrian Prantl       // straightforward with PCRE, but we're using ERE, so we end up with a
414905097246SAdrian Prantl       // little ugliness...
4150b3bbcb12SLuke Drummond       RegularExpression::Match match(/* max_matches */ 5);
4151b3bbcb12SLuke Drummond       RegularExpression match_type_list(
4152b3bbcb12SLuke Drummond           llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
4153b3bbcb12SLuke Drummond 
4154b3bbcb12SLuke Drummond       assert(match_type_list.IsValid());
4155b3bbcb12SLuke Drummond 
4156fe11483bSZachary Turner       if (!match_type_list.Execute(option_val, &match)) {
4157b3bbcb12SLuke Drummond         err_str.PutCString(
4158b3bbcb12SLuke Drummond             "a comma-separated list of kernel types is required");
4159b3bbcb12SLuke Drummond         return false;
4160b3bbcb12SLuke Drummond       }
4161b3bbcb12SLuke Drummond 
4162b3bbcb12SLuke Drummond       // splitting on commas is much easier with llvm::StringRef than regex
4163b3bbcb12SLuke Drummond       llvm::SmallVector<llvm::StringRef, 5> type_names;
4164b3bbcb12SLuke Drummond       llvm::StringRef(option_val).split(type_names, ',');
4165b3bbcb12SLuke Drummond 
4166b3bbcb12SLuke Drummond       for (const auto &name : type_names) {
4167b3bbcb12SLuke Drummond         const int type = reduce_name_to_type(name);
4168b3bbcb12SLuke Drummond         if (!type) {
4169b3bbcb12SLuke Drummond           err_str.Printf("unknown kernel type name %s", name.str().c_str());
4170b3bbcb12SLuke Drummond           return false;
4171b3bbcb12SLuke Drummond         }
4172b3bbcb12SLuke Drummond         m_kernel_types |= type;
4173b3bbcb12SLuke Drummond       }
4174b3bbcb12SLuke Drummond 
4175b3bbcb12SLuke Drummond       return true;
4176b3bbcb12SLuke Drummond     }
4177b3bbcb12SLuke Drummond 
4178b3bbcb12SLuke Drummond     int m_kernel_types;
4179b3bbcb12SLuke Drummond     llvm::StringRef m_reduce_name;
4180b3bbcb12SLuke Drummond     RSCoordinate m_coord;
4181b3bbcb12SLuke Drummond     bool m_have_coord;
4182b3bbcb12SLuke Drummond   };
4183b3bbcb12SLuke Drummond 
4184b3bbcb12SLuke Drummond   Options *GetOptions() override { return &m_options; }
4185b3bbcb12SLuke Drummond 
4186b3bbcb12SLuke Drummond   bool DoExecute(Args &command, CommandReturnObject &result) override {
4187b3bbcb12SLuke Drummond     const size_t argc = command.GetArgumentCount();
4188b3bbcb12SLuke Drummond     if (argc < 1) {
4189b3bbcb12SLuke Drummond       result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
4190b3bbcb12SLuke Drummond                                    "and an optional kernel type list",
4191b3bbcb12SLuke Drummond                                    m_cmd_name.c_str());
4192b3bbcb12SLuke Drummond       result.SetStatus(eReturnStatusFailed);
4193b3bbcb12SLuke Drummond       return false;
4194b3bbcb12SLuke Drummond     }
4195b3bbcb12SLuke Drummond 
4196b3bbcb12SLuke Drummond     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4197b3bbcb12SLuke Drummond         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4198b3bbcb12SLuke Drummond             eLanguageTypeExtRenderScript));
4199b3bbcb12SLuke Drummond 
4200b3bbcb12SLuke Drummond     auto &outstream = result.GetOutputStream();
4201b3bbcb12SLuke Drummond     auto name = command.GetArgumentAtIndex(0);
4202b3bbcb12SLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
4203b3bbcb12SLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4204b3bbcb12SLuke Drummond     if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
4205b3bbcb12SLuke Drummond                                              m_options.m_kernel_types)) {
4206b3bbcb12SLuke Drummond       result.SetStatus(eReturnStatusFailed);
4207b3bbcb12SLuke Drummond       result.AppendError("Error: unable to place breakpoint on reduction");
4208b3bbcb12SLuke Drummond       return false;
4209b3bbcb12SLuke Drummond     }
4210b3bbcb12SLuke Drummond     result.AppendMessage("Breakpoint(s) created");
4211b3bbcb12SLuke Drummond     result.SetStatus(eReturnStatusSuccessFinishResult);
4212b3bbcb12SLuke Drummond     return true;
4213b3bbcb12SLuke Drummond   }
4214b3bbcb12SLuke Drummond 
4215b3bbcb12SLuke Drummond private:
4216b3bbcb12SLuke Drummond   CommandOptions m_options;
4217b3bbcb12SLuke Drummond };
4218b3bbcb12SLuke Drummond 
42198fe53c49STatyana Krasnukha static constexpr OptionDefinition g_renderscript_kernel_bp_set_options[] = {
42201f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
42218fe53c49STatyana Krasnukha      nullptr, {}, 0, eArgTypeValue,
42221f0f5b5bSZachary Turner      "Set a breakpoint on a single invocation of the kernel with specified "
42231f0f5b5bSZachary Turner      "coordinate.\n"
42241f0f5b5bSZachary Turner      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
42251f0f5b5bSZachary Turner      "integers representing kernel dimensions. "
42261f0f5b5bSZachary Turner      "Any unset dimensions will be defaulted to zero."}};
42271f0f5b5bSZachary Turner 
4228b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointSet
4229b9c1b51eSKate Stone     : public CommandObjectParsed {
42304640cde1SColin Riley public:
4231b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4232b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4233b9c1b51eSKate Stone       : CommandObjectParsed(
4234b9c1b51eSKate Stone             interpreter, "renderscript kernel breakpoint set",
4235b3f7f69dSAidan Dodds             "Sets a breakpoint on a renderscript kernel.",
4236b3f7f69dSAidan Dodds             "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
4237b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4238b9c1b51eSKate Stone                 eCommandProcessMustBePaused),
4239b9c1b51eSKate Stone         m_options() {}
42404640cde1SColin Riley 
4241222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
4242222b937cSEugene Zelenko 
4243b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
4244018f5a7eSEwan Crawford 
4245b9c1b51eSKate Stone   class CommandOptions : public Options {
4246018f5a7eSEwan Crawford   public:
4247e1cfbc79STodd Fiala     CommandOptions() : Options() {}
4248018f5a7eSEwan Crawford 
4249222b937cSEugene Zelenko     ~CommandOptions() override = default;
4250018f5a7eSEwan Crawford 
425197206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4252b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
425397206d57SZachary Turner       Status err;
4254018f5a7eSEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
4255018f5a7eSEwan Crawford 
4256b9c1b51eSKate Stone       switch (short_option) {
425700f56eebSLuke Drummond       case 'c': {
425800f56eebSLuke Drummond         auto coord = RSCoordinate{};
425900f56eebSLuke Drummond         if (!ParseCoordinate(option_arg, coord))
426080af0b9eSLuke Drummond           err.SetErrorStringWithFormat(
4261b9c1b51eSKate Stone               "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
4262fe11483bSZachary Turner               option_arg.str().c_str());
426300f56eebSLuke Drummond         else {
426400f56eebSLuke Drummond           m_have_coord = true;
426500f56eebSLuke Drummond           m_coord = coord;
426600f56eebSLuke Drummond         }
4267018f5a7eSEwan Crawford         break;
426800f56eebSLuke Drummond       }
4269018f5a7eSEwan Crawford       default:
427080af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4271018f5a7eSEwan Crawford         break;
4272018f5a7eSEwan Crawford       }
427380af0b9eSLuke Drummond       return err;
4274018f5a7eSEwan Crawford     }
4275018f5a7eSEwan Crawford 
4276b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
427700f56eebSLuke Drummond       m_have_coord = false;
4278018f5a7eSEwan Crawford     }
4279018f5a7eSEwan Crawford 
42801f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
428170602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
42821f0f5b5bSZachary Turner     }
4283018f5a7eSEwan Crawford 
428400f56eebSLuke Drummond     RSCoordinate m_coord;
428500f56eebSLuke Drummond     bool m_have_coord;
4286018f5a7eSEwan Crawford   };
4287018f5a7eSEwan Crawford 
4288b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
42894640cde1SColin Riley     const size_t argc = command.GetArgumentCount();
4290b9c1b51eSKate Stone     if (argc < 1) {
4291b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4292b9c1b51eSKate Stone           "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4293b3f7f69dSAidan Dodds           m_cmd_name.c_str());
4294018f5a7eSEwan Crawford       result.SetStatus(eReturnStatusFailed);
4295018f5a7eSEwan Crawford       return false;
4296018f5a7eSEwan Crawford     }
4297018f5a7eSEwan Crawford 
4298056f6f18SAlex Langford     RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4299056f6f18SAlex Langford         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4300056f6f18SAlex Langford             eLanguageTypeExtRenderScript));
43014640cde1SColin Riley 
430200f56eebSLuke Drummond     auto &outstream = result.GetOutputStream();
430300f56eebSLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
430400f56eebSLuke Drummond     auto name = command.GetArgumentAtIndex(0);
430500f56eebSLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
430600f56eebSLuke Drummond     if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
430700f56eebSLuke Drummond       result.SetStatus(eReturnStatusFailed);
430800f56eebSLuke Drummond       result.AppendErrorWithFormat(
430900f56eebSLuke Drummond           "Error: unable to set breakpoint on kernel '%s'", name);
431000f56eebSLuke Drummond       return false;
431100f56eebSLuke Drummond     }
43124640cde1SColin Riley 
43134640cde1SColin Riley     result.AppendMessage("Breakpoint(s) created");
43144640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
43154640cde1SColin Riley     return true;
43164640cde1SColin Riley   }
43174640cde1SColin Riley 
4318018f5a7eSEwan Crawford private:
4319018f5a7eSEwan Crawford   CommandOptions m_options;
43204640cde1SColin Riley };
43214640cde1SColin Riley 
4322b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4323b9c1b51eSKate Stone     : public CommandObjectParsed {
43247dc7771cSEwan Crawford public:
4325b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4326b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4327b3f7f69dSAidan Dodds       : CommandObjectParsed(
4328b3f7f69dSAidan Dodds             interpreter, "renderscript kernel breakpoint all",
4329b9c1b51eSKate Stone             "Automatically sets a breakpoint on all renderscript kernels that "
4330b9c1b51eSKate Stone             "are or will be loaded.\n"
4331b9c1b51eSKate Stone             "Disabling option means breakpoints will no longer be set on any "
4332b9c1b51eSKate Stone             "kernels loaded in the future, "
43337dc7771cSEwan Crawford             "but does not remove currently set breakpoints.",
43347dc7771cSEwan Crawford             "renderscript kernel breakpoint all <enable/disable>",
4335b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4336b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
43377dc7771cSEwan Crawford 
4338222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
43397dc7771cSEwan Crawford 
4340b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
43417dc7771cSEwan Crawford     const size_t argc = command.GetArgumentCount();
4342b9c1b51eSKate Stone     if (argc != 1) {
4343b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4344b9c1b51eSKate Stone           "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
43457dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
43467dc7771cSEwan Crawford       return false;
43477dc7771cSEwan Crawford     }
43487dc7771cSEwan Crawford 
4349b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4350b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4351b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
43527dc7771cSEwan Crawford 
43537dc7771cSEwan Crawford     bool do_break = false;
43547dc7771cSEwan Crawford     const char *argument = command.GetArgumentAtIndex(0);
4355b9c1b51eSKate Stone     if (strcmp(argument, "enable") == 0) {
43567dc7771cSEwan Crawford       do_break = true;
43577dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will be set on all kernels.");
4358b9c1b51eSKate Stone     } else if (strcmp(argument, "disable") == 0) {
43597dc7771cSEwan Crawford       do_break = false;
43607dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will not be set on any new kernels.");
4361b9c1b51eSKate Stone     } else {
4362b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4363b9c1b51eSKate Stone           "Argument must be either 'enable' or 'disable'");
43647dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
43657dc7771cSEwan Crawford       return false;
43667dc7771cSEwan Crawford     }
43677dc7771cSEwan Crawford 
43687dc7771cSEwan Crawford     runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
43697dc7771cSEwan Crawford 
43707dc7771cSEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
43717dc7771cSEwan Crawford     return true;
43727dc7771cSEwan Crawford   }
43737dc7771cSEwan Crawford };
43747dc7771cSEwan Crawford 
4375b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReductionBreakpoint
4376b3bbcb12SLuke Drummond     : public CommandObjectMultiword {
4377b3bbcb12SLuke Drummond public:
4378b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReductionBreakpoint(
4379b3bbcb12SLuke Drummond       CommandInterpreter &interpreter)
4380b3bbcb12SLuke Drummond       : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4381b3bbcb12SLuke Drummond                                "Commands that manipulate breakpoints on "
4382b3bbcb12SLuke Drummond                                "renderscript general reductions.",
4383b3bbcb12SLuke Drummond                                nullptr) {
4384b3bbcb12SLuke Drummond     LoadSubCommand(
4385b3bbcb12SLuke Drummond         "set", CommandObjectSP(
4386b3bbcb12SLuke Drummond                    new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4387b3bbcb12SLuke Drummond                        interpreter)));
4388b3bbcb12SLuke Drummond   }
4389b3bbcb12SLuke Drummond 
4390b3bbcb12SLuke Drummond   ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4391b3bbcb12SLuke Drummond };
4392b3bbcb12SLuke Drummond 
4393b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelCoordinate
4394b9c1b51eSKate Stone     : public CommandObjectParsed {
43954f8817c2SEwan Crawford public:
4396b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelCoordinate(
4397b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4398b9c1b51eSKate Stone       : CommandObjectParsed(
4399b9c1b51eSKate Stone             interpreter, "renderscript kernel coordinate",
44004f8817c2SEwan Crawford             "Shows the (x,y,z) coordinate of the current kernel invocation.",
44014f8817c2SEwan Crawford             "renderscript kernel coordinate",
4402b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4403b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
44044f8817c2SEwan Crawford 
44054f8817c2SEwan Crawford   ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
44064f8817c2SEwan Crawford 
4407b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
440800f56eebSLuke Drummond     RSCoordinate coord{};
4409b9c1b51eSKate Stone     bool success = RenderScriptRuntime::GetKernelCoordinate(
4410b9c1b51eSKate Stone         coord, m_exe_ctx.GetThreadPtr());
44114f8817c2SEwan Crawford     Stream &stream = result.GetOutputStream();
44124f8817c2SEwan Crawford 
4413b9c1b51eSKate Stone     if (success) {
441400f56eebSLuke Drummond       stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
44154f8817c2SEwan Crawford       stream.EOL();
44164f8817c2SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4417b9c1b51eSKate Stone     } else {
44184f8817c2SEwan Crawford       stream.Printf("Error: Coordinate could not be found.");
44194f8817c2SEwan Crawford       stream.EOL();
44204f8817c2SEwan Crawford       result.SetStatus(eReturnStatusFailed);
44214f8817c2SEwan Crawford     }
44224f8817c2SEwan Crawford     return true;
44234f8817c2SEwan Crawford   }
44244f8817c2SEwan Crawford };
44254f8817c2SEwan Crawford 
4426b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpoint
4427b9c1b51eSKate Stone     : public CommandObjectMultiword {
44287dc7771cSEwan Crawford public:
4429b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpoint(
4430b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4431b9c1b51eSKate Stone       : CommandObjectMultiword(
4432b9c1b51eSKate Stone             interpreter, "renderscript kernel",
4433b9c1b51eSKate Stone             "Commands that generate breakpoints on renderscript kernels.",
4434b9c1b51eSKate Stone             nullptr) {
4435b9c1b51eSKate Stone     LoadSubCommand(
4436b9c1b51eSKate Stone         "set",
4437b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4438b9c1b51eSKate Stone             interpreter)));
4439b9c1b51eSKate Stone     LoadSubCommand(
4440b9c1b51eSKate Stone         "all",
4441b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4442b9c1b51eSKate Stone             interpreter)));
44437dc7771cSEwan Crawford   }
44447dc7771cSEwan Crawford 
4445222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
44467dc7771cSEwan Crawford };
44477dc7771cSEwan Crawford 
4448b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
44494640cde1SColin Riley public:
44504640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4451b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript kernel",
4452b9c1b51eSKate Stone                                "Commands that deal with RenderScript kernels.",
4453b9c1b51eSKate Stone                                nullptr) {
4454b9c1b51eSKate Stone     LoadSubCommand(
4455b9c1b51eSKate Stone         "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4456b9c1b51eSKate Stone                     interpreter)));
4457b9c1b51eSKate Stone     LoadSubCommand(
4458b9c1b51eSKate Stone         "coordinate",
4459b9c1b51eSKate Stone         CommandObjectSP(
4460b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4461b9c1b51eSKate Stone     LoadSubCommand(
4462b9c1b51eSKate Stone         "breakpoint",
4463b9c1b51eSKate Stone         CommandObjectSP(
4464b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
44654640cde1SColin Riley   }
44664640cde1SColin Riley 
4467222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernel() override = default;
44684640cde1SColin Riley };
44694640cde1SColin Riley 
4470b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
44714640cde1SColin Riley public:
44724640cde1SColin Riley   CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4473b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript context dump",
4474b9c1b51eSKate Stone                             "Dumps renderscript context information.",
4475b9c1b51eSKate Stone                             "renderscript context dump",
4476b9c1b51eSKate Stone                             eCommandRequiresProcess |
4477b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
44784640cde1SColin Riley 
4479222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContextDump() override = default;
44804640cde1SColin Riley 
4481b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4482056f6f18SAlex Langford     RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4483056f6f18SAlex Langford         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4484056f6f18SAlex Langford             eLanguageTypeExtRenderScript));
44854640cde1SColin Riley     runtime->DumpContexts(result.GetOutputStream());
44864640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
44874640cde1SColin Riley     return true;
44884640cde1SColin Riley   }
44894640cde1SColin Riley };
44904640cde1SColin Riley 
44918fe53c49STatyana Krasnukha static constexpr OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
44921f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
44938fe53c49STatyana Krasnukha      nullptr, {}, 0, eArgTypeFilename,
44941f0f5b5bSZachary Turner      "Print results to specified file instead of command line."}};
44951f0f5b5bSZachary Turner 
4496b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
44974640cde1SColin Riley public:
44984640cde1SColin Riley   CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4499b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript context",
4500b9c1b51eSKate Stone                                "Commands that deal with RenderScript contexts.",
4501b9c1b51eSKate Stone                                nullptr) {
4502b9c1b51eSKate Stone     LoadSubCommand(
4503b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4504b9c1b51eSKate Stone                     interpreter)));
45054640cde1SColin Riley   }
45064640cde1SColin Riley 
4507222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContext() override = default;
45084640cde1SColin Riley };
45094640cde1SColin Riley 
4510b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationDump
4511b9c1b51eSKate Stone     : public CommandObjectParsed {
4512a0f08674SEwan Crawford public:
4513b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationDump(
4514b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4515a0f08674SEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation dump",
4516b9c1b51eSKate Stone                             "Displays the contents of a particular allocation",
4517b9c1b51eSKate Stone                             "renderscript allocation dump <ID>",
4518b9c1b51eSKate Stone                             eCommandRequiresProcess |
4519b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched),
4520b9c1b51eSKate Stone         m_options() {}
4521a0f08674SEwan Crawford 
4522222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4523222b937cSEugene Zelenko 
4524b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
4525a0f08674SEwan Crawford 
4526b9c1b51eSKate Stone   class CommandOptions : public Options {
4527a0f08674SEwan Crawford   public:
4528e1cfbc79STodd Fiala     CommandOptions() : Options() {}
4529a0f08674SEwan Crawford 
4530222b937cSEugene Zelenko     ~CommandOptions() override = default;
4531a0f08674SEwan Crawford 
453297206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4533b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
453497206d57SZachary Turner       Status err;
4535a0f08674SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
4536a0f08674SEwan Crawford 
4537b9c1b51eSKate Stone       switch (short_option) {
4538a0f08674SEwan Crawford       case 'f':
45398f3be7a3SJonas Devlieghere         m_outfile.SetFile(option_arg, FileSpec::Style::native);
45408f3be7a3SJonas Devlieghere         FileSystem::Instance().Resolve(m_outfile);
4541dbd7fabaSJonas Devlieghere         if (FileSystem::Instance().Exists(m_outfile)) {
4542a0f08674SEwan Crawford           m_outfile.Clear();
4543fe11483bSZachary Turner           err.SetErrorStringWithFormat("file already exists: '%s'",
4544fe11483bSZachary Turner                                        option_arg.str().c_str());
4545a0f08674SEwan Crawford         }
4546a0f08674SEwan Crawford         break;
4547a0f08674SEwan Crawford       default:
454880af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4549a0f08674SEwan Crawford         break;
4550a0f08674SEwan Crawford       }
455180af0b9eSLuke Drummond       return err;
4552a0f08674SEwan Crawford     }
4553a0f08674SEwan Crawford 
4554b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4555a0f08674SEwan Crawford       m_outfile.Clear();
4556a0f08674SEwan Crawford     }
4557a0f08674SEwan Crawford 
45581f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
455970602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
45601f0f5b5bSZachary Turner     }
4561a0f08674SEwan Crawford 
4562a0f08674SEwan Crawford     FileSpec m_outfile;
4563a0f08674SEwan Crawford   };
4564a0f08674SEwan Crawford 
4565b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4566a0f08674SEwan Crawford     const size_t argc = command.GetArgumentCount();
4567b9c1b51eSKate Stone     if (argc < 1) {
4568b9c1b51eSKate Stone       result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4569b9c1b51eSKate Stone                                    "As well as an optional -f argument",
4570a0f08674SEwan Crawford                                    m_cmd_name.c_str());
4571a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4572a0f08674SEwan Crawford       return false;
4573a0f08674SEwan Crawford     }
4574a0f08674SEwan Crawford 
4575b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4576b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4577b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4578a0f08674SEwan Crawford 
4579a0f08674SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
458080af0b9eSLuke Drummond     bool success = false;
4581b9c1b51eSKate Stone     const uint32_t id =
458280af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
458380af0b9eSLuke Drummond     if (!success) {
4584b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4585b9c1b51eSKate Stone                                    id_cstr);
4586a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4587a0f08674SEwan Crawford       return false;
4588a0f08674SEwan Crawford     }
4589a0f08674SEwan Crawford 
4590a0f08674SEwan Crawford     Stream *output_strm = nullptr;
4591a0f08674SEwan Crawford     StreamFile outfile_stream;
4592b9c1b51eSKate Stone     const FileSpec &outfile_spec =
4593b9c1b51eSKate Stone         m_options.m_outfile; // Dump allocation to file instead
4594b9c1b51eSKate Stone     if (outfile_spec) {
4595a0f08674SEwan Crawford       // Open output file
459650bc1ed2SJonas Devlieghere       std::string path = outfile_spec.GetPath();
459750bc1ed2SJonas Devlieghere       auto error = FileSystem::Instance().Open(
459850bc1ed2SJonas Devlieghere           outfile_stream.GetFile(), outfile_spec,
459950bc1ed2SJonas Devlieghere           File::eOpenOptionWrite | File::eOpenOptionCanCreate);
460050bc1ed2SJonas Devlieghere       if (error.Success()) {
4601a0f08674SEwan Crawford         output_strm = &outfile_stream;
460250bc1ed2SJonas Devlieghere         result.GetOutputStream().Printf("Results written to '%s'",
460350bc1ed2SJonas Devlieghere                                         path.c_str());
4604a0f08674SEwan Crawford         result.GetOutputStream().EOL();
4605b9c1b51eSKate Stone       } else {
460650bc1ed2SJonas Devlieghere         result.AppendErrorWithFormat("Couldn't open file '%s'", path.c_str());
4607a0f08674SEwan Crawford         result.SetStatus(eReturnStatusFailed);
4608a0f08674SEwan Crawford         return false;
4609a0f08674SEwan Crawford       }
4610b9c1b51eSKate Stone     } else
4611a0f08674SEwan Crawford       output_strm = &result.GetOutputStream();
4612a0f08674SEwan Crawford 
4613a0f08674SEwan Crawford     assert(output_strm != nullptr);
461480af0b9eSLuke Drummond     bool dumped =
4615b9c1b51eSKate Stone         runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4616a0f08674SEwan Crawford 
461780af0b9eSLuke Drummond     if (dumped)
4618a0f08674SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4619a0f08674SEwan Crawford     else
4620a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4621a0f08674SEwan Crawford 
4622a0f08674SEwan Crawford     return true;
4623a0f08674SEwan Crawford   }
4624a0f08674SEwan Crawford 
4625a0f08674SEwan Crawford private:
4626a0f08674SEwan Crawford   CommandOptions m_options;
4627a0f08674SEwan Crawford };
4628a0f08674SEwan Crawford 
46298fe53c49STatyana Krasnukha static constexpr OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
46301f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
46318fe53c49STatyana Krasnukha      {}, 0, eArgTypeIndex,
46321f0f5b5bSZachary Turner      "Only show details of a single allocation with specified id."}};
4633a0f08674SEwan Crawford 
4634b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationList
4635b9c1b51eSKate Stone     : public CommandObjectParsed {
463615f2bd95SEwan Crawford public:
4637b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationList(
4638b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4639b9c1b51eSKate Stone       : CommandObjectParsed(
4640b9c1b51eSKate Stone             interpreter, "renderscript allocation list",
4641b9c1b51eSKate Stone             "List renderscript allocations and their information.",
4642b9c1b51eSKate Stone             "renderscript allocation list",
4643b3f7f69dSAidan Dodds             eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4644b9c1b51eSKate Stone         m_options() {}
464515f2bd95SEwan Crawford 
4646222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4647222b937cSEugene Zelenko 
4648b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
464915f2bd95SEwan Crawford 
4650b9c1b51eSKate Stone   class CommandOptions : public Options {
465115f2bd95SEwan Crawford   public:
4652e1cfbc79STodd Fiala     CommandOptions() : Options(), m_id(0) {}
465315f2bd95SEwan Crawford 
4654222b937cSEugene Zelenko     ~CommandOptions() override = default;
465515f2bd95SEwan Crawford 
465697206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4657b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
465897206d57SZachary Turner       Status err;
465915f2bd95SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
466015f2bd95SEwan Crawford 
4661b9c1b51eSKate Stone       switch (short_option) {
4662b649b005SEwan Crawford       case 'i':
4663fe11483bSZachary Turner         if (option_arg.getAsInteger(0, m_id))
466480af0b9eSLuke Drummond           err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4665b9c1b51eSKate Stone                                        short_option);
466615f2bd95SEwan Crawford         break;
466780af0b9eSLuke Drummond       default:
466880af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
466980af0b9eSLuke Drummond         break;
467015f2bd95SEwan Crawford       }
467180af0b9eSLuke Drummond       return err;
467215f2bd95SEwan Crawford     }
467315f2bd95SEwan Crawford 
4674b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
467515f2bd95SEwan Crawford 
46761f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
467770602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
46781f0f5b5bSZachary Turner     }
467915f2bd95SEwan Crawford 
4680b649b005SEwan Crawford     uint32_t m_id;
468115f2bd95SEwan Crawford   };
468215f2bd95SEwan Crawford 
4683b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4684b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4685b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4686b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4687b9c1b51eSKate Stone     runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4688b9c1b51eSKate Stone                              m_options.m_id);
468915f2bd95SEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
469015f2bd95SEwan Crawford     return true;
469115f2bd95SEwan Crawford   }
469215f2bd95SEwan Crawford 
469315f2bd95SEwan Crawford private:
469415f2bd95SEwan Crawford   CommandOptions m_options;
469515f2bd95SEwan Crawford };
469615f2bd95SEwan Crawford 
4697b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationLoad
4698b9c1b51eSKate Stone     : public CommandObjectParsed {
469955232f09SEwan Crawford public:
4700b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationLoad(
4701b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4702b3f7f69dSAidan Dodds       : CommandObjectParsed(
4703b9c1b51eSKate Stone             interpreter, "renderscript allocation load",
4704b9c1b51eSKate Stone             "Loads renderscript allocation contents from a file.",
4705b9c1b51eSKate Stone             "renderscript allocation load <ID> <filename>",
4706b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
470755232f09SEwan Crawford 
4708222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
470955232f09SEwan Crawford 
4710b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
471155232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4712b9c1b51eSKate Stone     if (argc != 2) {
4713b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4714b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4715b3f7f69dSAidan Dodds           m_cmd_name.c_str());
471655232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
471755232f09SEwan Crawford       return false;
471855232f09SEwan Crawford     }
471955232f09SEwan Crawford 
4720b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4721b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4722b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
472355232f09SEwan Crawford 
472455232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
472580af0b9eSLuke Drummond     bool success = false;
4726b9c1b51eSKate Stone     const uint32_t id =
472780af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
472880af0b9eSLuke Drummond     if (!success) {
4729b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4730b9c1b51eSKate Stone                                    id_cstr);
473155232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
473255232f09SEwan Crawford       return false;
473355232f09SEwan Crawford     }
473455232f09SEwan Crawford 
473580af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
473680af0b9eSLuke Drummond     bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
473780af0b9eSLuke Drummond                                           m_exe_ctx.GetFramePtr());
473855232f09SEwan Crawford 
473980af0b9eSLuke Drummond     if (loaded)
474055232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
474155232f09SEwan Crawford     else
474255232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
474355232f09SEwan Crawford 
474455232f09SEwan Crawford     return true;
474555232f09SEwan Crawford   }
474655232f09SEwan Crawford };
474755232f09SEwan Crawford 
4748b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationSave
4749b9c1b51eSKate Stone     : public CommandObjectParsed {
475055232f09SEwan Crawford public:
4751b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationSave(
4752b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4753b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript allocation save",
4754b9c1b51eSKate Stone                             "Write renderscript allocation contents to a file.",
4755b9c1b51eSKate Stone                             "renderscript allocation save <ID> <filename>",
4756b9c1b51eSKate Stone                             eCommandRequiresProcess |
4757b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
475855232f09SEwan Crawford 
4759222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
476055232f09SEwan Crawford 
4761b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
476255232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4763b9c1b51eSKate Stone     if (argc != 2) {
4764b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4765b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4766b3f7f69dSAidan Dodds           m_cmd_name.c_str());
476755232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
476855232f09SEwan Crawford       return false;
476955232f09SEwan Crawford     }
477055232f09SEwan Crawford 
4771b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4772b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4773b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
477455232f09SEwan Crawford 
477555232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
477680af0b9eSLuke Drummond     bool success = false;
4777b9c1b51eSKate Stone     const uint32_t id =
477880af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
477980af0b9eSLuke Drummond     if (!success) {
4780b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4781b9c1b51eSKate Stone                                    id_cstr);
478255232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
478355232f09SEwan Crawford       return false;
478455232f09SEwan Crawford     }
478555232f09SEwan Crawford 
478680af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
478780af0b9eSLuke Drummond     bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
478880af0b9eSLuke Drummond                                          m_exe_ctx.GetFramePtr());
478955232f09SEwan Crawford 
479080af0b9eSLuke Drummond     if (saved)
479155232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
479255232f09SEwan Crawford     else
479355232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
479455232f09SEwan Crawford 
479555232f09SEwan Crawford     return true;
479655232f09SEwan Crawford   }
479755232f09SEwan Crawford };
479855232f09SEwan Crawford 
4799b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationRefresh
4800b9c1b51eSKate Stone     : public CommandObjectParsed {
48010d2bfcfbSEwan Crawford public:
4802b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationRefresh(
4803b9c1b51eSKate Stone       CommandInterpreter &interpreter)
48040d2bfcfbSEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4805b9c1b51eSKate Stone                             "Recomputes the details of all allocations.",
4806b9c1b51eSKate Stone                             "renderscript allocation refresh",
4807b9c1b51eSKate Stone                             eCommandRequiresProcess |
4808b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
48090d2bfcfbSEwan Crawford 
48100d2bfcfbSEwan Crawford   ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
48110d2bfcfbSEwan Crawford 
4812b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
48130d2bfcfbSEwan Crawford     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4814b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4815b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
48160d2bfcfbSEwan Crawford 
4817b9c1b51eSKate Stone     bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4818b9c1b51eSKate Stone                                                     m_exe_ctx.GetFramePtr());
48190d2bfcfbSEwan Crawford 
4820b9c1b51eSKate Stone     if (success) {
48210d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
48220d2bfcfbSEwan Crawford       return true;
4823b9c1b51eSKate Stone     } else {
48240d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusFailed);
48250d2bfcfbSEwan Crawford       return false;
48260d2bfcfbSEwan Crawford     }
48270d2bfcfbSEwan Crawford   }
48280d2bfcfbSEwan Crawford };
48290d2bfcfbSEwan Crawford 
4830b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocation
4831b9c1b51eSKate Stone     : public CommandObjectMultiword {
483215f2bd95SEwan Crawford public:
483315f2bd95SEwan Crawford   CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4834b9c1b51eSKate Stone       : CommandObjectMultiword(
4835b9c1b51eSKate Stone             interpreter, "renderscript allocation",
4836b9c1b51eSKate Stone             "Commands that deal with RenderScript allocations.", nullptr) {
4837b9c1b51eSKate Stone     LoadSubCommand(
4838b9c1b51eSKate Stone         "list",
4839b9c1b51eSKate Stone         CommandObjectSP(
4840b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4841b9c1b51eSKate Stone     LoadSubCommand(
4842b9c1b51eSKate Stone         "dump",
4843b9c1b51eSKate Stone         CommandObjectSP(
4844b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4845b9c1b51eSKate Stone     LoadSubCommand(
4846b9c1b51eSKate Stone         "save",
4847b9c1b51eSKate Stone         CommandObjectSP(
4848b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4849b9c1b51eSKate Stone     LoadSubCommand(
4850b9c1b51eSKate Stone         "load",
4851b9c1b51eSKate Stone         CommandObjectSP(
4852b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4853b9c1b51eSKate Stone     LoadSubCommand(
4854b9c1b51eSKate Stone         "refresh",
4855b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4856b9c1b51eSKate Stone             interpreter)));
485715f2bd95SEwan Crawford   }
485815f2bd95SEwan Crawford 
4859222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocation() override = default;
486015f2bd95SEwan Crawford };
486115f2bd95SEwan Crawford 
4862b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
48634640cde1SColin Riley public:
48644640cde1SColin Riley   CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4865b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript status",
4866b9c1b51eSKate Stone                             "Displays current RenderScript runtime status.",
4867b9c1b51eSKate Stone                             "renderscript status",
4868b9c1b51eSKate Stone                             eCommandRequiresProcess |
4869b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
48704640cde1SColin Riley 
4871222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeStatus() override = default;
48724640cde1SColin Riley 
4873b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4874056f6f18SAlex Langford     RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4875056f6f18SAlex Langford         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4876056f6f18SAlex Langford             eLanguageTypeExtRenderScript));
487797206d57SZachary Turner     runtime->DumpStatus(result.GetOutputStream());
48784640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
48794640cde1SColin Riley     return true;
48804640cde1SColin Riley   }
48814640cde1SColin Riley };
48824640cde1SColin Riley 
4883b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReduction
4884b3bbcb12SLuke Drummond     : public CommandObjectMultiword {
4885b3bbcb12SLuke Drummond public:
4886b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
4887b3bbcb12SLuke Drummond       : CommandObjectMultiword(interpreter, "renderscript reduction",
4888b3bbcb12SLuke Drummond                                "Commands that handle general reduction kernels",
4889b3bbcb12SLuke Drummond                                nullptr) {
4890b3bbcb12SLuke Drummond     LoadSubCommand(
4891b3bbcb12SLuke Drummond         "breakpoint",
4892b3bbcb12SLuke Drummond         CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
4893b3bbcb12SLuke Drummond             interpreter)));
4894b3bbcb12SLuke Drummond   }
4895b3bbcb12SLuke Drummond   ~CommandObjectRenderScriptRuntimeReduction() override = default;
4896b3bbcb12SLuke Drummond };
4897b3bbcb12SLuke Drummond 
4898b9c1b51eSKate Stone class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
48995ec532a9SColin Riley public:
49005ec532a9SColin Riley   CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
4901b9c1b51eSKate Stone       : CommandObjectMultiword(
4902b9c1b51eSKate Stone             interpreter, "renderscript",
4903b9c1b51eSKate Stone             "Commands for operating on the RenderScript runtime.",
4904b9c1b51eSKate Stone             "renderscript <subcommand> [<subcommand-options>]") {
4905b9c1b51eSKate Stone     LoadSubCommand(
4906b9c1b51eSKate Stone         "module", CommandObjectSP(
4907b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeModule(interpreter)));
4908b9c1b51eSKate Stone     LoadSubCommand(
4909b9c1b51eSKate Stone         "status", CommandObjectSP(
4910b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeStatus(interpreter)));
4911b9c1b51eSKate Stone     LoadSubCommand(
4912b9c1b51eSKate Stone         "kernel", CommandObjectSP(
4913b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeKernel(interpreter)));
4914b9c1b51eSKate Stone     LoadSubCommand("context",
4915b9c1b51eSKate Stone                    CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
4916b9c1b51eSKate Stone                        interpreter)));
4917b9c1b51eSKate Stone     LoadSubCommand(
4918b9c1b51eSKate Stone         "allocation",
4919b9c1b51eSKate Stone         CommandObjectSP(
4920b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
492121fed052SAidan Dodds     LoadSubCommand("scriptgroup",
492221fed052SAidan Dodds                    NewCommandObjectRenderScriptScriptGroup(interpreter));
4923b3bbcb12SLuke Drummond     LoadSubCommand(
4924b3bbcb12SLuke Drummond         "reduction",
4925b3bbcb12SLuke Drummond         CommandObjectSP(
4926b3bbcb12SLuke Drummond             new CommandObjectRenderScriptRuntimeReduction(interpreter)));
49275ec532a9SColin Riley   }
49285ec532a9SColin Riley 
4929222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntime() override = default;
49305ec532a9SColin Riley };
4931ef20b08fSColin Riley 
4932b9c1b51eSKate Stone void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
4933ef20b08fSColin Riley 
4934ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
4935b9c1b51eSKate Stone     : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
4936b9c1b51eSKate Stone       m_debuggerPresentFlagged(false), m_breakAllKernels(false),
4937b9c1b51eSKate Stone       m_ir_passes(nullptr) {
49384640cde1SColin Riley   ModulesDidLoad(process->GetTarget().GetImages());
4939ef20b08fSColin Riley }
49404640cde1SColin Riley 
4941b9c1b51eSKate Stone lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
4942b9c1b51eSKate Stone     lldb_private::CommandInterpreter &interpreter) {
49430a66e2f1SEnrico Granata   return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
49444640cde1SColin Riley }
49454640cde1SColin Riley 
494678f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
4947