15ec532a9SColin Riley //===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===//
25ec532a9SColin Riley //
35ec532a9SColin Riley //                     The LLVM Compiler Infrastructure
45ec532a9SColin Riley //
55ec532a9SColin Riley // This file is distributed under the University of Illinois Open Source
65ec532a9SColin Riley // License. See LICENSE.TXT for details.
75ec532a9SColin Riley //
85ec532a9SColin Riley //===----------------------------------------------------------------------===//
95ec532a9SColin Riley 
10222b937cSEugene Zelenko // C Includes
11222b937cSEugene Zelenko // C++ Includes
12222b937cSEugene Zelenko // Other libraries and framework includes
13b3bbcb12SLuke Drummond #include "llvm/ADT/StringSwitch.h"
147f193d69SLuke Drummond 
15222b937cSEugene Zelenko // Project includes
165ec532a9SColin Riley #include "RenderScriptRuntime.h"
1721fed052SAidan Dodds #include "RenderScriptScriptGroup.h"
185ec532a9SColin Riley 
19b3f7f69dSAidan Dodds #include "lldb/Breakpoint/StoppointCallbackContext.h"
205ec532a9SColin Riley #include "lldb/Core/Debugger.h"
2129cb868aSZachary Turner #include "lldb/Core/DumpDataExtractor.h"
225ec532a9SColin Riley #include "lldb/Core/PluginManager.h"
232f3df613SZachary Turner #include "lldb/Core/RegisterValue.h"
24b3f7f69dSAidan Dodds #include "lldb/Core/ValueObjectVariable.h"
258b244e21SEwan Crawford #include "lldb/DataFormatters/DumpValueObjectOptions.h"
26b3f7f69dSAidan Dodds #include "lldb/Expression/UserExpression.h"
273eb2b44dSZachary Turner #include "lldb/Host/OptionParser.h"
28a0f08674SEwan Crawford #include "lldb/Host/StringConvert.h"
29b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandInterpreter.h"
30b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandObjectMultiword.h"
31b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandReturnObject.h"
32b3f7f69dSAidan Dodds #include "lldb/Interpreter/Options.h"
3321fed052SAidan Dodds #include "lldb/Symbol/Function.h"
345ec532a9SColin Riley #include "lldb/Symbol/Symbol.h"
354640cde1SColin Riley #include "lldb/Symbol/Type.h"
36b3f7f69dSAidan Dodds #include "lldb/Symbol/VariableList.h"
375ec532a9SColin Riley #include "lldb/Target/Process.h"
38b3f7f69dSAidan Dodds #include "lldb/Target/RegisterContext.h"
3921fed052SAidan Dodds #include "lldb/Target/SectionLoadList.h"
405ec532a9SColin Riley #include "lldb/Target/Target.h"
41018f5a7eSEwan Crawford #include "lldb/Target/Thread.h"
42*145d95c9SPavel Labath #include "lldb/Utility/Args.h"
43bf9a7730SZachary Turner #include "lldb/Utility/ConstString.h"
447f6a7a37SZachary Turner #include "lldb/Utility/DataBufferLLVM.h"
456f9e6901SZachary Turner #include "lldb/Utility/Log.h"
46bf9a7730SZachary Turner #include "lldb/Utility/RegularExpression.h"
4797206d57SZachary Turner #include "lldb/Utility/Status.h"
485ec532a9SColin Riley 
495ec532a9SColin Riley using namespace lldb;
505ec532a9SColin Riley using namespace lldb_private;
5198156583SEwan Crawford using namespace lldb_renderscript;
525ec532a9SColin Riley 
5300f56eebSLuke Drummond #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")"
5400f56eebSLuke Drummond 
55b9c1b51eSKate Stone namespace {
5678f339d1SEwan Crawford 
5778f339d1SEwan Crawford // The empirical_type adds a basic level of validation to arbitrary data
5880af0b9eSLuke Drummond // allowing us to track if data has been discovered and stored or not. An
5980af0b9eSLuke Drummond // empirical_type will be marked as valid only if it has been explicitly
60b9c1b51eSKate Stone // assigned to.
61b9c1b51eSKate Stone template <typename type_t> class empirical_type {
6278f339d1SEwan Crawford public:
6378f339d1SEwan Crawford   // Ctor. Contents is invalid when constructed.
64b3f7f69dSAidan Dodds   empirical_type() : valid(false) {}
6578f339d1SEwan Crawford 
6678f339d1SEwan Crawford   // Return true and copy contents to out if valid, else return false.
67b9c1b51eSKate Stone   bool get(type_t &out) const {
6878f339d1SEwan Crawford     if (valid)
6978f339d1SEwan Crawford       out = data;
7078f339d1SEwan Crawford     return valid;
7178f339d1SEwan Crawford   }
7278f339d1SEwan Crawford 
7378f339d1SEwan Crawford   // Return a pointer to the contents or nullptr if it was not valid.
74b9c1b51eSKate Stone   const type_t *get() const { return valid ? &data : nullptr; }
7578f339d1SEwan Crawford 
7678f339d1SEwan Crawford   // Assign data explicitly.
77b9c1b51eSKate Stone   void set(const type_t in) {
7878f339d1SEwan Crawford     data = in;
7978f339d1SEwan Crawford     valid = true;
8078f339d1SEwan Crawford   }
8178f339d1SEwan Crawford 
8278f339d1SEwan Crawford   // Mark contents as invalid.
83b9c1b51eSKate Stone   void invalidate() { valid = false; }
8478f339d1SEwan Crawford 
8578f339d1SEwan Crawford   // Returns true if this type contains valid data.
86b9c1b51eSKate Stone   bool isValid() const { return valid; }
8778f339d1SEwan Crawford 
8878f339d1SEwan Crawford   // Assignment operator.
89b9c1b51eSKate Stone   empirical_type<type_t> &operator=(const type_t in) {
9078f339d1SEwan Crawford     set(in);
9178f339d1SEwan Crawford     return *this;
9278f339d1SEwan Crawford   }
9378f339d1SEwan Crawford 
9478f339d1SEwan Crawford   // Dereference operator returns contents.
9578f339d1SEwan Crawford   // Warning: Will assert if not valid so use only when you know data is valid.
96b9c1b51eSKate Stone   const type_t &operator*() const {
9778f339d1SEwan Crawford     assert(valid);
9878f339d1SEwan Crawford     return data;
9978f339d1SEwan Crawford   }
10078f339d1SEwan Crawford 
10178f339d1SEwan Crawford protected:
10278f339d1SEwan Crawford   bool valid;
10378f339d1SEwan Crawford   type_t data;
10478f339d1SEwan Crawford };
10578f339d1SEwan Crawford 
106b9c1b51eSKate Stone // ArgItem is used by the GetArgs() function when reading function arguments
107b9c1b51eSKate Stone // from the target.
108b9c1b51eSKate Stone struct ArgItem {
109b9c1b51eSKate Stone   enum { ePointer, eInt32, eInt64, eLong, eBool } type;
110f4786785SAidan Dodds 
111f4786785SAidan Dodds   uint64_t value;
112f4786785SAidan Dodds 
113f4786785SAidan Dodds   explicit operator uint64_t() const { return value; }
114f4786785SAidan Dodds };
115f4786785SAidan Dodds 
116b9c1b51eSKate Stone // Context structure to be passed into GetArgsXXX(), argument reading functions
117b9c1b51eSKate Stone // below.
118b9c1b51eSKate Stone struct GetArgsCtx {
119f4786785SAidan Dodds   RegisterContext *reg_ctx;
120f4786785SAidan Dodds   Process *process;
121f4786785SAidan Dodds };
122f4786785SAidan Dodds 
123b9c1b51eSKate Stone bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
124f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
125f4786785SAidan Dodds 
12697206d57SZachary Turner   Status err;
12767dc3e15SAidan Dodds 
128f4786785SAidan Dodds   // get the current stack pointer
129f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
130f4786785SAidan Dodds 
131b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
132f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
133f4786785SAidan Dodds     // advance up the stack by one argument
134f4786785SAidan Dodds     sp += sizeof(uint32_t);
135f4786785SAidan Dodds     // get the argument type size
136f4786785SAidan Dodds     size_t arg_size = sizeof(uint32_t);
137f4786785SAidan Dodds     // read the argument from memory
138f4786785SAidan Dodds     arg.value = 0;
13997206d57SZachary Turner     Status err;
140b9c1b51eSKate Stone     size_t read =
14180af0b9eSLuke Drummond         ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
14280af0b9eSLuke Drummond     if (read != arg_size || !err.Success()) {
143f4786785SAidan Dodds       if (log)
144b9c1b51eSKate Stone         log->Printf("%s - error reading argument: %" PRIu64 " '%s'",
14580af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString());
146f4786785SAidan Dodds       return false;
147f4786785SAidan Dodds     }
148f4786785SAidan Dodds   }
149f4786785SAidan Dodds   return true;
150f4786785SAidan Dodds }
151f4786785SAidan Dodds 
152b9c1b51eSKate Stone bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
153f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
154f4786785SAidan Dodds 
155f4786785SAidan Dodds   // number of arguments passed in registers
15680af0b9eSLuke Drummond   static const uint32_t args_in_reg = 6;
157f4786785SAidan Dodds   // register passing order
15880af0b9eSLuke Drummond   static const std::array<const char *, args_in_reg> reg_names{
159b9c1b51eSKate Stone       {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
160f4786785SAidan Dodds   // argument type to size mapping
1611ee07253SSaleem Abdulrasool   static const std::array<size_t, 5> arg_size{{
162f4786785SAidan Dodds       8, // ePointer,
163f4786785SAidan Dodds       4, // eInt32,
164f4786785SAidan Dodds       8, // eInt64,
165f4786785SAidan Dodds       8, // eLong,
166f4786785SAidan Dodds       4, // eBool,
1671ee07253SSaleem Abdulrasool   }};
168f4786785SAidan Dodds 
16997206d57SZachary Turner   Status err;
17017e07c0aSAidan Dodds 
171f4786785SAidan Dodds   // get the current stack pointer
172f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
173f4786785SAidan Dodds   // step over the return address
174f4786785SAidan Dodds   sp += sizeof(uint64_t);
175f4786785SAidan Dodds 
176f4786785SAidan Dodds   // check the stack alignment was correct (16 byte aligned)
177b9c1b51eSKate Stone   if ((sp & 0xf) != 0x0) {
178f4786785SAidan Dodds     if (log)
179f4786785SAidan Dodds       log->Printf("%s - stack misaligned", __FUNCTION__);
180f4786785SAidan Dodds     return false;
181f4786785SAidan Dodds   }
182f4786785SAidan Dodds 
183f4786785SAidan Dodds   // find the start of arguments on the stack
184f4786785SAidan Dodds   uint64_t sp_offset = 0;
18580af0b9eSLuke Drummond   for (uint32_t i = args_in_reg; i < num_args; ++i) {
186f4786785SAidan Dodds     sp_offset += arg_size[arg_list[i].type];
187f4786785SAidan Dodds   }
188f4786785SAidan Dodds   // round up to multiple of 16
189f4786785SAidan Dodds   sp_offset = (sp_offset + 0xf) & 0xf;
190f4786785SAidan Dodds   sp += sp_offset;
191f4786785SAidan Dodds 
192b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
193f4786785SAidan Dodds     bool success = false;
194f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
195f4786785SAidan Dodds     // arguments passed in registers
19680af0b9eSLuke Drummond     if (i < args_in_reg) {
19780af0b9eSLuke Drummond       const RegisterInfo *reg =
19880af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoByName(reg_names[i]);
19980af0b9eSLuke Drummond       RegisterValue reg_val;
20080af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
20180af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
202f4786785SAidan Dodds     }
203f4786785SAidan Dodds     // arguments passed on the stack
204b9c1b51eSKate Stone     else {
205f4786785SAidan Dodds       // get the argument type size
206f4786785SAidan Dodds       const size_t size = arg_size[arg_list[i].type];
207f4786785SAidan Dodds       // read the argument from memory
208f4786785SAidan Dodds       arg.value = 0;
209b9c1b51eSKate Stone       // note: due to little endian layout reading 4 or 8 bytes will give the
210b9c1b51eSKate Stone       // correct value.
21180af0b9eSLuke Drummond       size_t read = ctx.process->ReadMemory(sp, &arg.value, size, err);
21280af0b9eSLuke Drummond       success = (err.Success() && read == size);
213f4786785SAidan Dodds       // advance past this argument
214f4786785SAidan Dodds       sp -= size;
215f4786785SAidan Dodds     }
216f4786785SAidan Dodds     // fail if we couldn't read this argument
217b9c1b51eSKate Stone     if (!success) {
218f4786785SAidan Dodds       if (log)
21917e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
22080af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
221f4786785SAidan Dodds       return false;
222f4786785SAidan Dodds     }
223f4786785SAidan Dodds   }
224f4786785SAidan Dodds   return true;
225f4786785SAidan Dodds }
226f4786785SAidan Dodds 
227b9c1b51eSKate Stone bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
228f4786785SAidan Dodds   // number of arguments passed in registers
22980af0b9eSLuke Drummond   static const uint32_t args_in_reg = 4;
230f4786785SAidan Dodds 
231f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
232f4786785SAidan Dodds 
23397206d57SZachary Turner   Status err;
23417e07c0aSAidan Dodds 
235f4786785SAidan Dodds   // get the current stack pointer
236f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
237f4786785SAidan Dodds 
238b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
239f4786785SAidan Dodds     bool success = false;
240f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
241f4786785SAidan Dodds     // arguments passed in registers
24280af0b9eSLuke Drummond     if (i < args_in_reg) {
24380af0b9eSLuke Drummond       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
24480af0b9eSLuke Drummond       RegisterValue reg_val;
24580af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
24680af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt32(0, &success);
247f4786785SAidan Dodds     }
248f4786785SAidan Dodds     // arguments passed on the stack
249b9c1b51eSKate Stone     else {
250f4786785SAidan Dodds       // get the argument type size
251f4786785SAidan Dodds       const size_t arg_size = sizeof(uint32_t);
252f4786785SAidan Dodds       // clear all 64bits
253f4786785SAidan Dodds       arg.value = 0;
254f4786785SAidan Dodds       // read this argument from memory
255b9c1b51eSKate Stone       size_t bytes_read =
25680af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
25780af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
258f4786785SAidan Dodds       // advance the stack pointer
259f4786785SAidan Dodds       sp += sizeof(uint32_t);
260f4786785SAidan Dodds     }
261f4786785SAidan Dodds     // fail if we couldn't read this argument
262b9c1b51eSKate Stone     if (!success) {
263f4786785SAidan Dodds       if (log)
26417e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
26580af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
266f4786785SAidan Dodds       return false;
267f4786785SAidan Dodds     }
268f4786785SAidan Dodds   }
269f4786785SAidan Dodds   return true;
270f4786785SAidan Dodds }
271f4786785SAidan Dodds 
272b9c1b51eSKate Stone bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
273f4786785SAidan Dodds   // number of arguments passed in registers
27480af0b9eSLuke Drummond   static const uint32_t args_in_reg = 8;
275f4786785SAidan Dodds 
276f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
277f4786785SAidan Dodds 
278b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
279f4786785SAidan Dodds     bool success = false;
280f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
281f4786785SAidan Dodds     // arguments passed in registers
28280af0b9eSLuke Drummond     if (i < args_in_reg) {
28380af0b9eSLuke Drummond       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
28480af0b9eSLuke Drummond       RegisterValue reg_val;
28580af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
28680af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
287f4786785SAidan Dodds     }
288f4786785SAidan Dodds     // arguments passed on the stack
289b9c1b51eSKate Stone     else {
290f4786785SAidan Dodds       if (log)
291b9c1b51eSKate Stone         log->Printf("%s - reading arguments spilled to stack not implemented",
292b9c1b51eSKate Stone                     __FUNCTION__);
293f4786785SAidan Dodds     }
294f4786785SAidan Dodds     // fail if we couldn't read this argument
295b9c1b51eSKate Stone     if (!success) {
296f4786785SAidan Dodds       if (log)
297f4786785SAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__,
298f4786785SAidan Dodds                     uint64_t(i));
299f4786785SAidan Dodds       return false;
300f4786785SAidan Dodds     }
301f4786785SAidan Dodds   }
302f4786785SAidan Dodds   return true;
303f4786785SAidan Dodds }
304f4786785SAidan Dodds 
305b9c1b51eSKate Stone bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
306f4786785SAidan Dodds   // number of arguments passed in registers
30780af0b9eSLuke Drummond   static const uint32_t args_in_reg = 4;
308f4786785SAidan Dodds   // register file offset to first argument
30980af0b9eSLuke Drummond   static const uint32_t reg_offset = 4;
310f4786785SAidan Dodds 
311f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
312f4786785SAidan Dodds 
31397206d57SZachary Turner   Status err;
31417e07c0aSAidan Dodds 
31517e07c0aSAidan Dodds   // find offset to arguments on the stack (+16 to skip over a0-a3 shadow space)
31617e07c0aSAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP() + 16;
31717e07c0aSAidan Dodds 
318b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
319f4786785SAidan Dodds     bool success = false;
320f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
321f4786785SAidan Dodds     // arguments passed in registers
32280af0b9eSLuke Drummond     if (i < args_in_reg) {
32380af0b9eSLuke Drummond       const RegisterInfo *reg =
32480af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
32580af0b9eSLuke Drummond       RegisterValue reg_val;
32680af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
32780af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
328f4786785SAidan Dodds     }
329f4786785SAidan Dodds     // arguments passed on the stack
330b9c1b51eSKate Stone     else {
3316dd4b579SAidan Dodds       const size_t arg_size = sizeof(uint32_t);
3326dd4b579SAidan Dodds       arg.value = 0;
333b9c1b51eSKate Stone       size_t bytes_read =
33480af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
33580af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
33667dc3e15SAidan Dodds       // advance the stack pointer
33767dc3e15SAidan Dodds       sp += arg_size;
338f4786785SAidan Dodds     }
339f4786785SAidan Dodds     // fail if we couldn't read this argument
340b9c1b51eSKate Stone     if (!success) {
341f4786785SAidan Dodds       if (log)
34267dc3e15SAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
34380af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
344f4786785SAidan Dodds       return false;
345f4786785SAidan Dodds     }
346f4786785SAidan Dodds   }
347f4786785SAidan Dodds   return true;
348f4786785SAidan Dodds }
349f4786785SAidan Dodds 
350b9c1b51eSKate Stone bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
351f4786785SAidan Dodds   // number of arguments passed in registers
35280af0b9eSLuke Drummond   static const uint32_t args_in_reg = 8;
353f4786785SAidan Dodds   // register file offset to first argument
35480af0b9eSLuke Drummond   static const uint32_t reg_offset = 4;
355f4786785SAidan Dodds 
356f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
357f4786785SAidan Dodds 
35897206d57SZachary Turner   Status err;
35917e07c0aSAidan Dodds 
360f4786785SAidan Dodds   // get the current stack pointer
361f4786785SAidan Dodds   uint64_t sp = ctx.reg_ctx->GetSP();
362f4786785SAidan Dodds 
363b9c1b51eSKate Stone   for (size_t i = 0; i < num_args; ++i) {
364f4786785SAidan Dodds     bool success = false;
365f4786785SAidan Dodds     ArgItem &arg = arg_list[i];
366f4786785SAidan Dodds     // arguments passed in registers
36780af0b9eSLuke Drummond     if (i < args_in_reg) {
36880af0b9eSLuke Drummond       const RegisterInfo *reg =
36980af0b9eSLuke Drummond           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
37080af0b9eSLuke Drummond       RegisterValue reg_val;
37180af0b9eSLuke Drummond       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
37280af0b9eSLuke Drummond         arg.value = reg_val.GetAsUInt64(0, &success);
373f4786785SAidan Dodds     }
374f4786785SAidan Dodds     // arguments passed on the stack
375b9c1b51eSKate Stone     else {
376f4786785SAidan Dodds       // get the argument type size
377f4786785SAidan Dodds       const size_t arg_size = sizeof(uint64_t);
378f4786785SAidan Dodds       // clear all 64bits
379f4786785SAidan Dodds       arg.value = 0;
380f4786785SAidan Dodds       // read this argument from memory
381b9c1b51eSKate Stone       size_t bytes_read =
38280af0b9eSLuke Drummond           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
38380af0b9eSLuke Drummond       success = (err.Success() && bytes_read == arg_size);
384f4786785SAidan Dodds       // advance the stack pointer
385f4786785SAidan Dodds       sp += arg_size;
386f4786785SAidan Dodds     }
387f4786785SAidan Dodds     // fail if we couldn't read this argument
388b9c1b51eSKate Stone     if (!success) {
389f4786785SAidan Dodds       if (log)
39017e07c0aSAidan Dodds         log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
39180af0b9eSLuke Drummond                     __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
392f4786785SAidan Dodds       return false;
393f4786785SAidan Dodds     }
394f4786785SAidan Dodds   }
395f4786785SAidan Dodds   return true;
396f4786785SAidan Dodds }
397f4786785SAidan Dodds 
39880af0b9eSLuke Drummond bool GetArgs(ExecutionContext &exe_ctx, ArgItem *arg_list, size_t num_args) {
399f4786785SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
400f4786785SAidan Dodds 
401f4786785SAidan Dodds   // verify that we have a target
40280af0b9eSLuke Drummond   if (!exe_ctx.GetTargetPtr()) {
403f4786785SAidan Dodds     if (log)
404f4786785SAidan Dodds       log->Printf("%s - invalid target", __FUNCTION__);
405f4786785SAidan Dodds     return false;
406f4786785SAidan Dodds   }
407f4786785SAidan Dodds 
40880af0b9eSLuke Drummond   GetArgsCtx ctx = {exe_ctx.GetRegisterContext(), exe_ctx.GetProcessPtr()};
409f4786785SAidan Dodds   assert(ctx.reg_ctx && ctx.process);
410f4786785SAidan Dodds 
411f4786785SAidan Dodds   // dispatch based on architecture
41280af0b9eSLuke Drummond   switch (exe_ctx.GetTargetPtr()->GetArchitecture().GetMachine()) {
413f4786785SAidan Dodds   case llvm::Triple::ArchType::x86:
414f4786785SAidan Dodds     return GetArgsX86(ctx, arg_list, num_args);
415f4786785SAidan Dodds 
416f4786785SAidan Dodds   case llvm::Triple::ArchType::x86_64:
417f4786785SAidan Dodds     return GetArgsX86_64(ctx, arg_list, num_args);
418f4786785SAidan Dodds 
419f4786785SAidan Dodds   case llvm::Triple::ArchType::arm:
420f4786785SAidan Dodds     return GetArgsArm(ctx, arg_list, num_args);
421f4786785SAidan Dodds 
422f4786785SAidan Dodds   case llvm::Triple::ArchType::aarch64:
423f4786785SAidan Dodds     return GetArgsAarch64(ctx, arg_list, num_args);
424f4786785SAidan Dodds 
425f4786785SAidan Dodds   case llvm::Triple::ArchType::mipsel:
426f4786785SAidan Dodds     return GetArgsMipsel(ctx, arg_list, num_args);
427f4786785SAidan Dodds 
428f4786785SAidan Dodds   case llvm::Triple::ArchType::mips64el:
429f4786785SAidan Dodds     return GetArgsMips64el(ctx, arg_list, num_args);
430f4786785SAidan Dodds 
431f4786785SAidan Dodds   default:
432f4786785SAidan Dodds     // unsupported architecture
433b9c1b51eSKate Stone     if (log) {
434b9c1b51eSKate Stone       log->Printf(
435b9c1b51eSKate Stone           "%s - architecture not supported: '%s'", __FUNCTION__,
43680af0b9eSLuke Drummond           exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
437f4786785SAidan Dodds     }
438f4786785SAidan Dodds     return false;
439f4786785SAidan Dodds   }
440f4786785SAidan Dodds }
44100f56eebSLuke Drummond 
442b3bbcb12SLuke Drummond bool IsRenderScriptScriptModule(ModuleSP module) {
443b3bbcb12SLuke Drummond   if (!module)
444b3bbcb12SLuke Drummond     return false;
445b3bbcb12SLuke Drummond   return module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
446b3bbcb12SLuke Drummond                                                 eSymbolTypeData) != nullptr;
447b3bbcb12SLuke Drummond }
448b3bbcb12SLuke Drummond 
44900f56eebSLuke Drummond bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
45000f56eebSLuke Drummond   // takes an argument of the form 'num[,num][,num]'.
45100f56eebSLuke Drummond   // Where 'coord_s' is a comma separated 1,2 or 3-dimensional coordinate
45200f56eebSLuke Drummond   // with the whitespace trimmed.
45300f56eebSLuke Drummond   // Missing coordinates are defaulted to zero.
45400f56eebSLuke Drummond   // If parsing of any elements fails the contents of &coord are undefined
45500f56eebSLuke Drummond   // and `false` is returned, `true` otherwise
45600f56eebSLuke Drummond 
45700f56eebSLuke Drummond   RegularExpression regex;
45800f56eebSLuke Drummond   RegularExpression::Match regex_match(3);
45900f56eebSLuke Drummond 
46000f56eebSLuke Drummond   bool matched = false;
46100f56eebSLuke Drummond   if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+),([0-9]+)$")) &&
46200f56eebSLuke Drummond       regex.Execute(coord_s, &regex_match))
46300f56eebSLuke Drummond     matched = true;
46400f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+)$")) &&
46500f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
46600f56eebSLuke Drummond     matched = true;
46700f56eebSLuke Drummond   else if (regex.Compile(llvm::StringRef("^([0-9]+)$")) &&
46800f56eebSLuke Drummond            regex.Execute(coord_s, &regex_match))
46900f56eebSLuke Drummond     matched = true;
47000f56eebSLuke Drummond 
47100f56eebSLuke Drummond   if (!matched)
47200f56eebSLuke Drummond     return false;
47300f56eebSLuke Drummond 
47400f56eebSLuke Drummond   auto get_index = [&](int idx, uint32_t &i) -> bool {
47500f56eebSLuke Drummond     std::string group;
47600f56eebSLuke Drummond     errno = 0;
47700f56eebSLuke Drummond     if (regex_match.GetMatchAtIndex(coord_s.str().c_str(), idx + 1, group))
47800f56eebSLuke Drummond       return !llvm::StringRef(group).getAsInteger<uint32_t>(10, i);
47900f56eebSLuke Drummond     return true;
48000f56eebSLuke Drummond   };
48100f56eebSLuke Drummond 
48200f56eebSLuke Drummond   return get_index(0, coord.x) && get_index(1, coord.y) &&
48300f56eebSLuke Drummond          get_index(2, coord.z);
48400f56eebSLuke Drummond }
48521fed052SAidan Dodds 
48621fed052SAidan Dodds bool SkipPrologue(lldb::ModuleSP &module, Address &addr) {
48721fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
48821fed052SAidan Dodds   SymbolContext sc;
48921fed052SAidan Dodds   uint32_t resolved_flags =
49021fed052SAidan Dodds       module->ResolveSymbolContextForAddress(addr, eSymbolContextFunction, sc);
49121fed052SAidan Dodds   if (resolved_flags & eSymbolContextFunction) {
49221fed052SAidan Dodds     if (sc.function) {
49321fed052SAidan Dodds       const uint32_t offset = sc.function->GetPrologueByteSize();
49421fed052SAidan Dodds       ConstString name = sc.GetFunctionName();
49521fed052SAidan Dodds       if (offset)
49621fed052SAidan Dodds         addr.Slide(offset);
49721fed052SAidan Dodds       if (log)
49821fed052SAidan Dodds         log->Printf("%s: Prologue offset for %s is %" PRIu32, __FUNCTION__,
49921fed052SAidan Dodds                     name.AsCString(), offset);
50021fed052SAidan Dodds     }
50121fed052SAidan Dodds     return true;
50221fed052SAidan Dodds   } else
50321fed052SAidan Dodds     return false;
50421fed052SAidan Dodds }
505222b937cSEugene Zelenko } // anonymous namespace
50678f339d1SEwan Crawford 
507b9c1b51eSKate Stone // The ScriptDetails class collects data associated with a single script
508b9c1b51eSKate Stone // instance.
509b9c1b51eSKate Stone struct RenderScriptRuntime::ScriptDetails {
510222b937cSEugene Zelenko   ~ScriptDetails() = default;
51178f339d1SEwan Crawford 
512b9c1b51eSKate Stone   enum ScriptType { eScript, eScriptC };
51378f339d1SEwan Crawford 
51478f339d1SEwan Crawford   // The derived type of the script.
51578f339d1SEwan Crawford   empirical_type<ScriptType> type;
51678f339d1SEwan Crawford   // The name of the original source file.
51780af0b9eSLuke Drummond   empirical_type<std::string> res_name;
51878f339d1SEwan Crawford   // Path to script .so file on the device.
51980af0b9eSLuke Drummond   empirical_type<std::string> shared_lib;
52078f339d1SEwan Crawford   // Directory where kernel objects are cached on device.
52180af0b9eSLuke Drummond   empirical_type<std::string> cache_dir;
52278f339d1SEwan Crawford   // Pointer to the context which owns this script.
52378f339d1SEwan Crawford   empirical_type<lldb::addr_t> context;
52478f339d1SEwan Crawford   // Pointer to the script object itself.
52578f339d1SEwan Crawford   empirical_type<lldb::addr_t> script;
52678f339d1SEwan Crawford };
52778f339d1SEwan Crawford 
52880af0b9eSLuke Drummond // This Element class represents the Element object in RS, defining the type
52980af0b9eSLuke Drummond // associated with an Allocation.
530b9c1b51eSKate Stone struct RenderScriptRuntime::Element {
53115f2bd95SEwan Crawford   // Taken from rsDefines.h
532b9c1b51eSKate Stone   enum DataKind {
53315f2bd95SEwan Crawford     RS_KIND_USER,
53415f2bd95SEwan Crawford     RS_KIND_PIXEL_L = 7,
53515f2bd95SEwan Crawford     RS_KIND_PIXEL_A,
53615f2bd95SEwan Crawford     RS_KIND_PIXEL_LA,
53715f2bd95SEwan Crawford     RS_KIND_PIXEL_RGB,
53815f2bd95SEwan Crawford     RS_KIND_PIXEL_RGBA,
53915f2bd95SEwan Crawford     RS_KIND_PIXEL_DEPTH,
54015f2bd95SEwan Crawford     RS_KIND_PIXEL_YUV,
54115f2bd95SEwan Crawford     RS_KIND_INVALID = 100
54215f2bd95SEwan Crawford   };
54378f339d1SEwan Crawford 
54415f2bd95SEwan Crawford   // Taken from rsDefines.h
545b9c1b51eSKate Stone   enum DataType {
54615f2bd95SEwan Crawford     RS_TYPE_NONE = 0,
54715f2bd95SEwan Crawford     RS_TYPE_FLOAT_16,
54815f2bd95SEwan Crawford     RS_TYPE_FLOAT_32,
54915f2bd95SEwan Crawford     RS_TYPE_FLOAT_64,
55015f2bd95SEwan Crawford     RS_TYPE_SIGNED_8,
55115f2bd95SEwan Crawford     RS_TYPE_SIGNED_16,
55215f2bd95SEwan Crawford     RS_TYPE_SIGNED_32,
55315f2bd95SEwan Crawford     RS_TYPE_SIGNED_64,
55415f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_8,
55515f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_16,
55615f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_32,
55715f2bd95SEwan Crawford     RS_TYPE_UNSIGNED_64,
5582e920715SEwan Crawford     RS_TYPE_BOOLEAN,
5592e920715SEwan Crawford 
5602e920715SEwan Crawford     RS_TYPE_UNSIGNED_5_6_5,
5612e920715SEwan Crawford     RS_TYPE_UNSIGNED_5_5_5_1,
5622e920715SEwan Crawford     RS_TYPE_UNSIGNED_4_4_4_4,
5632e920715SEwan Crawford 
5642e920715SEwan Crawford     RS_TYPE_MATRIX_4X4,
5652e920715SEwan Crawford     RS_TYPE_MATRIX_3X3,
5662e920715SEwan Crawford     RS_TYPE_MATRIX_2X2,
5672e920715SEwan Crawford 
5682e920715SEwan Crawford     RS_TYPE_ELEMENT = 1000,
5692e920715SEwan Crawford     RS_TYPE_TYPE,
5702e920715SEwan Crawford     RS_TYPE_ALLOCATION,
5712e920715SEwan Crawford     RS_TYPE_SAMPLER,
5722e920715SEwan Crawford     RS_TYPE_SCRIPT,
5732e920715SEwan Crawford     RS_TYPE_MESH,
5742e920715SEwan Crawford     RS_TYPE_PROGRAM_FRAGMENT,
5752e920715SEwan Crawford     RS_TYPE_PROGRAM_VERTEX,
5762e920715SEwan Crawford     RS_TYPE_PROGRAM_RASTER,
5772e920715SEwan Crawford     RS_TYPE_PROGRAM_STORE,
5782e920715SEwan Crawford     RS_TYPE_FONT,
5792e920715SEwan Crawford 
5802e920715SEwan Crawford     RS_TYPE_INVALID = 10000
58178f339d1SEwan Crawford   };
58278f339d1SEwan Crawford 
5838b244e21SEwan Crawford   std::vector<Element> children; // Child Element fields for structs
584b9c1b51eSKate Stone   empirical_type<lldb::addr_t>
585b9c1b51eSKate Stone       element_ptr; // Pointer to the RS Element of the Type
586b9c1b51eSKate Stone   empirical_type<DataType>
587b9c1b51eSKate Stone       type; // Type of each data pointer stored by the allocation
588b9c1b51eSKate Stone   empirical_type<DataKind>
589b9c1b51eSKate Stone       type_kind; // Defines pixel type if Allocation is created from an image
590b9c1b51eSKate Stone   empirical_type<uint32_t>
591b9c1b51eSKate Stone       type_vec_size; // Vector size of each data point, e.g '4' for uchar4
5928b244e21SEwan Crawford   empirical_type<uint32_t> field_count; // Number of Subelements
5938b244e21SEwan Crawford   empirical_type<uint32_t> datum_size;  // Size of a single Element with padding
5948b244e21SEwan Crawford   empirical_type<uint32_t> padding;     // Number of padding bytes
595b9c1b51eSKate Stone   empirical_type<uint32_t>
596b9c1b51eSKate Stone       array_size;        // Number of items in array, only needed for strucrs
5978b244e21SEwan Crawford   ConstString type_name; // Name of type, only needed for structs
5988b244e21SEwan Crawford 
599b3f7f69dSAidan Dodds   static const ConstString &
600b3f7f69dSAidan Dodds   GetFallbackStructName(); // Print this as the type name of a struct Element
6018b244e21SEwan Crawford                            // If we can't resolve the actual struct name
6028b59062aSEwan Crawford 
60380af0b9eSLuke Drummond   bool ShouldRefresh() const {
6048b59062aSEwan Crawford     const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
605b9c1b51eSKate Stone     const bool valid_type =
606b9c1b51eSKate Stone         type.isValid() && type_vec_size.isValid() && type_kind.isValid();
6078b59062aSEwan Crawford     return !valid_ptr || !valid_type || !datum_size.isValid();
6088b59062aSEwan Crawford   }
6098b244e21SEwan Crawford };
6108b244e21SEwan Crawford 
6118b244e21SEwan Crawford // This AllocationDetails class collects data associated with a single
6128b244e21SEwan Crawford // allocation instance.
613b9c1b51eSKate Stone struct RenderScriptRuntime::AllocationDetails {
614b9c1b51eSKate Stone   struct Dimension {
61515f2bd95SEwan Crawford     uint32_t dim_1;
61615f2bd95SEwan Crawford     uint32_t dim_2;
61715f2bd95SEwan Crawford     uint32_t dim_3;
61880af0b9eSLuke Drummond     uint32_t cube_map;
61915f2bd95SEwan Crawford 
620b9c1b51eSKate Stone     Dimension() {
62115f2bd95SEwan Crawford       dim_1 = 0;
62215f2bd95SEwan Crawford       dim_2 = 0;
62315f2bd95SEwan Crawford       dim_3 = 0;
62480af0b9eSLuke Drummond       cube_map = 0;
62515f2bd95SEwan Crawford     }
62678f339d1SEwan Crawford   };
62778f339d1SEwan Crawford 
628b9c1b51eSKate Stone   // The FileHeader struct specifies the header we use for writing allocations
62980af0b9eSLuke Drummond   // to a binary file. Our format begins with the ASCII characters "RSAD",
63080af0b9eSLuke Drummond   // identifying the file as an allocation dump. Member variables dims and
63180af0b9eSLuke Drummond   // hdr_size are then written consecutively, immediately followed by an
63280af0b9eSLuke Drummond   // instance of the ElementHeader struct. Because Elements can contain
63380af0b9eSLuke Drummond   // subelements, there may be more than one instance of the ElementHeader
63480af0b9eSLuke Drummond   // struct. With this first instance being the root element, and the other
63580af0b9eSLuke Drummond   // instances being the root's descendants. To identify which instances are an
63680af0b9eSLuke Drummond   // ElementHeader's children, each struct is immediately followed by a sequence
63780af0b9eSLuke Drummond   // of consecutive offsets to the start of its child structs. These offsets are
63880af0b9eSLuke Drummond   // 4 bytes in size, and the 0 offset signifies no more children.
639b9c1b51eSKate Stone   struct FileHeader {
64055232f09SEwan Crawford     uint8_t ident[4];  // ASCII 'RSAD' identifying the file
64126e52a70SEwan Crawford     uint32_t dims[3];  // Dimensions
64226e52a70SEwan Crawford     uint16_t hdr_size; // Header size in bytes, including all element headers
64326e52a70SEwan Crawford   };
64426e52a70SEwan Crawford 
645b9c1b51eSKate Stone   struct ElementHeader {
64655232f09SEwan Crawford     uint16_t type;         // DataType enum
64755232f09SEwan Crawford     uint32_t kind;         // DataKind enum
64855232f09SEwan Crawford     uint32_t element_size; // Size of a single element, including padding
64926e52a70SEwan Crawford     uint16_t vector_size;  // Vector width
65026e52a70SEwan Crawford     uint32_t array_size;   // Number of elements in array
65155232f09SEwan Crawford   };
65255232f09SEwan Crawford 
65315f2bd95SEwan Crawford   // Monotonically increasing from 1
654b3f7f69dSAidan Dodds   static uint32_t ID;
65515f2bd95SEwan Crawford 
65615f2bd95SEwan Crawford   // Maps Allocation DataType enum and vector size to printable strings
65715f2bd95SEwan Crawford   // using mapping from RenderScript numerical types summary documentation
65815f2bd95SEwan Crawford   static const char *RsDataTypeToString[][4];
65915f2bd95SEwan Crawford 
66015f2bd95SEwan Crawford   // Maps Allocation DataKind enum to printable strings
66115f2bd95SEwan Crawford   static const char *RsDataKindToString[];
66215f2bd95SEwan Crawford 
663a0f08674SEwan Crawford   // Maps allocation types to format sizes for printing.
664b3f7f69dSAidan Dodds   static const uint32_t RSTypeToFormat[][3];
665a0f08674SEwan Crawford 
66615f2bd95SEwan Crawford   // Give each allocation an ID as a way
66715f2bd95SEwan Crawford   // for commands to reference it.
668b3f7f69dSAidan Dodds   const uint32_t id;
66915f2bd95SEwan Crawford 
67080af0b9eSLuke Drummond   // Allocation Element type
67180af0b9eSLuke Drummond   RenderScriptRuntime::Element element;
67280af0b9eSLuke Drummond   // Dimensions of the Allocation
67380af0b9eSLuke Drummond   empirical_type<Dimension> dimension;
67480af0b9eSLuke Drummond   // Pointer to address of the RS Allocation
67580af0b9eSLuke Drummond   empirical_type<lldb::addr_t> address;
67680af0b9eSLuke Drummond   // Pointer to the data held by the Allocation
67780af0b9eSLuke Drummond   empirical_type<lldb::addr_t> data_ptr;
67880af0b9eSLuke Drummond   // Pointer to the RS Type of the Allocation
67980af0b9eSLuke Drummond   empirical_type<lldb::addr_t> type_ptr;
68080af0b9eSLuke Drummond   // Pointer to the RS Context of the Allocation
68180af0b9eSLuke Drummond   empirical_type<lldb::addr_t> context;
68280af0b9eSLuke Drummond   // Size of the allocation
68380af0b9eSLuke Drummond   empirical_type<uint32_t> size;
68480af0b9eSLuke Drummond   // Stride between rows of the allocation
68580af0b9eSLuke Drummond   empirical_type<uint32_t> stride;
68615f2bd95SEwan Crawford 
68715f2bd95SEwan Crawford   // Give each allocation an id, so we can reference it in user commands.
688b3f7f69dSAidan Dodds   AllocationDetails() : id(ID++) {}
6898b59062aSEwan Crawford 
69080af0b9eSLuke Drummond   bool ShouldRefresh() const {
6918b59062aSEwan Crawford     bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
6928b59062aSEwan Crawford     valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
693b9c1b51eSKate Stone     return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
69480af0b9eSLuke Drummond            element.ShouldRefresh();
6958b59062aSEwan Crawford   }
69615f2bd95SEwan Crawford };
69715f2bd95SEwan Crawford 
698b9c1b51eSKate Stone const ConstString &RenderScriptRuntime::Element::GetFallbackStructName() {
699fe06b5adSAdrian McCarthy   static const ConstString FallbackStructName("struct");
700fe06b5adSAdrian McCarthy   return FallbackStructName;
701fe06b5adSAdrian McCarthy }
7028b244e21SEwan Crawford 
703b3f7f69dSAidan Dodds uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
70415f2bd95SEwan Crawford 
705b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
706b9c1b51eSKate Stone     "User",       "Undefined",   "Undefined", "Undefined",
707b9c1b51eSKate Stone     "Undefined",  "Undefined",   "Undefined", // Enum jumps from 0 to 7
708b3f7f69dSAidan Dodds     "L Pixel",    "A Pixel",     "LA Pixel",  "RGB Pixel",
709b3f7f69dSAidan Dodds     "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
71015f2bd95SEwan Crawford 
711b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
71215f2bd95SEwan Crawford     {"None", "None", "None", "None"},
71315f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
71415f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
71515f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
71615f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
71715f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
71815f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
71915f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
72015f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
72115f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
72215f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
72315f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
7242e920715SEwan Crawford     {"bool", "bool2", "bool3", "bool4"},
7252e920715SEwan Crawford     {"packed_565", "packed_565", "packed_565", "packed_565"},
7262e920715SEwan Crawford     {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
7272e920715SEwan Crawford     {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
7282e920715SEwan Crawford     {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
7292e920715SEwan Crawford     {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
7302e920715SEwan Crawford     {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
7312e920715SEwan Crawford 
7322e920715SEwan Crawford     // Handlers
7332e920715SEwan Crawford     {"RS Element", "RS Element", "RS Element", "RS Element"},
7342e920715SEwan Crawford     {"RS Type", "RS Type", "RS Type", "RS Type"},
7352e920715SEwan Crawford     {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
7362e920715SEwan Crawford     {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
7372e920715SEwan Crawford     {"RS Script", "RS Script", "RS Script", "RS Script"},
7382e920715SEwan Crawford 
7392e920715SEwan Crawford     // Deprecated
7402e920715SEwan Crawford     {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
741b9c1b51eSKate Stone     {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
742b9c1b51eSKate Stone      "RS Program Fragment"},
743b9c1b51eSKate Stone     {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
744b9c1b51eSKate Stone      "RS Program Vertex"},
745b9c1b51eSKate Stone     {"RS Program Raster", "RS Program Raster", "RS Program Raster",
746b9c1b51eSKate Stone      "RS Program Raster"},
747b9c1b51eSKate Stone     {"RS Program Store", "RS Program Store", "RS Program Store",
748b9c1b51eSKate Stone      "RS Program Store"},
749b3f7f69dSAidan Dodds     {"RS Font", "RS Font", "RS Font", "RS Font"}};
75078f339d1SEwan Crawford 
751a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
752b9c1b51eSKate Stone enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
753a0f08674SEwan Crawford 
754b9c1b51eSKate Stone // { format enum of single element, format enum of element vector, size of
755b9c1b51eSKate Stone // element}
756b3f7f69dSAidan Dodds const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
75780af0b9eSLuke Drummond     // RS_TYPE_NONE
75880af0b9eSLuke Drummond     {eFormatHex, eFormatHex, 1},
75980af0b9eSLuke Drummond     // RS_TYPE_FLOAT_16
76080af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat16, 2},
76180af0b9eSLuke Drummond     // RS_TYPE_FLOAT_32
76280af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
76380af0b9eSLuke Drummond     // RS_TYPE_FLOAT_64
76480af0b9eSLuke Drummond     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
76580af0b9eSLuke Drummond     // RS_TYPE_SIGNED_8
76680af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
76780af0b9eSLuke Drummond     // RS_TYPE_SIGNED_16
76880af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
76980af0b9eSLuke Drummond     // RS_TYPE_SIGNED_32
77080af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
77180af0b9eSLuke Drummond     // RS_TYPE_SIGNED_64
77280af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
77380af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_8
77480af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
77580af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_16
77680af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
77780af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_32
77880af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
77980af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_64
78080af0b9eSLuke Drummond     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
78180af0b9eSLuke Drummond     // RS_TYPE_BOOL
78280af0b9eSLuke Drummond     {eFormatBoolean, eFormatBoolean, 1},
78380af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_5_6_5
78480af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
78580af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_5_5_5_1
78680af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
78780af0b9eSLuke Drummond     // RS_TYPE_UNSIGNED_4_4_4_4
78880af0b9eSLuke Drummond     {eFormatHex, eFormatHex, sizeof(uint16_t)},
78980af0b9eSLuke Drummond     // RS_TYPE_MATRIX_4X4
79080af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
79180af0b9eSLuke Drummond     // RS_TYPE_MATRIX_3X3
79280af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
79380af0b9eSLuke Drummond     // RS_TYPE_MATRIX_2X2
79480af0b9eSLuke Drummond     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
795a0f08674SEwan Crawford 
7965ec532a9SColin Riley //------------------------------------------------------------------
7975ec532a9SColin Riley // Static Functions
7985ec532a9SColin Riley //------------------------------------------------------------------
7995ec532a9SColin Riley LanguageRuntime *
800b9c1b51eSKate Stone RenderScriptRuntime::CreateInstance(Process *process,
801b9c1b51eSKate Stone                                     lldb::LanguageType language) {
8025ec532a9SColin Riley 
8035ec532a9SColin Riley   if (language == eLanguageTypeExtRenderScript)
8045ec532a9SColin Riley     return new RenderScriptRuntime(process);
8055ec532a9SColin Riley   else
806b3f7f69dSAidan Dodds     return nullptr;
8075ec532a9SColin Riley }
8085ec532a9SColin Riley 
80980af0b9eSLuke Drummond // Callback with a module to search for matching symbols. We first check that
81080af0b9eSLuke Drummond // the module contains RS kernels. Then look for a symbol which matches our
81180af0b9eSLuke Drummond // kernel name. The breakpoint address is finally set using the address of this
81280af0b9eSLuke Drummond // symbol.
81398156583SEwan Crawford Searcher::CallbackReturn
814b9c1b51eSKate Stone RSBreakpointResolver::SearchCallback(SearchFilter &filter,
815b9c1b51eSKate Stone                                      SymbolContext &context, Address *, bool) {
81698156583SEwan Crawford   ModuleSP module = context.module_sp;
81798156583SEwan Crawford 
818b3bbcb12SLuke Drummond   if (!module || !IsRenderScriptScriptModule(module))
81998156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
82098156583SEwan Crawford 
821b9c1b51eSKate Stone   // Attempt to set a breakpoint on the kernel name symbol within the module
82280af0b9eSLuke Drummond   // library. If it's not found, it's likely debug info is unavailable - try to
82380af0b9eSLuke Drummond   // set a breakpoint on <name>.expand.
824b9c1b51eSKate Stone   const Symbol *kernel_sym =
825b9c1b51eSKate Stone       module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
826b9c1b51eSKate Stone   if (!kernel_sym) {
82798156583SEwan Crawford     std::string kernel_name_expanded(m_kernel_name.AsCString());
82898156583SEwan Crawford     kernel_name_expanded.append(".expand");
829b9c1b51eSKate Stone     kernel_sym = module->FindFirstSymbolWithNameAndType(
830b9c1b51eSKate Stone         ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
83198156583SEwan Crawford   }
83298156583SEwan Crawford 
833b9c1b51eSKate Stone   if (kernel_sym) {
83498156583SEwan Crawford     Address bp_addr = kernel_sym->GetAddress();
83598156583SEwan Crawford     if (filter.AddressPasses(bp_addr))
83698156583SEwan Crawford       m_breakpoint->AddLocation(bp_addr);
83798156583SEwan Crawford   }
83898156583SEwan Crawford 
83998156583SEwan Crawford   return Searcher::eCallbackReturnContinue;
84098156583SEwan Crawford }
84198156583SEwan Crawford 
842b3bbcb12SLuke Drummond Searcher::CallbackReturn
843b3bbcb12SLuke Drummond RSReduceBreakpointResolver::SearchCallback(lldb_private::SearchFilter &filter,
844b3bbcb12SLuke Drummond                                            lldb_private::SymbolContext &context,
845b3bbcb12SLuke Drummond                                            Address *, bool) {
846b3bbcb12SLuke Drummond   // We need to have access to the list of reductions currently parsed, as
847b3bbcb12SLuke Drummond   // reduce names don't actually exist as
848b3bbcb12SLuke Drummond   // symbols in a module. They are only identifiable by parsing the .rs.info
849b3bbcb12SLuke Drummond   // packet, or finding the expand symbol. We
850b3bbcb12SLuke Drummond   // therefore need access to the list of parsed rs modules to properly resolve
851b3bbcb12SLuke Drummond   // reduction names.
852b3bbcb12SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
853b3bbcb12SLuke Drummond   ModuleSP module = context.module_sp;
854b3bbcb12SLuke Drummond 
855b3bbcb12SLuke Drummond   if (!module || !IsRenderScriptScriptModule(module))
856b3bbcb12SLuke Drummond     return Searcher::eCallbackReturnContinue;
857b3bbcb12SLuke Drummond 
858b3bbcb12SLuke Drummond   if (!m_rsmodules)
859b3bbcb12SLuke Drummond     return Searcher::eCallbackReturnContinue;
860b3bbcb12SLuke Drummond 
861b3bbcb12SLuke Drummond   for (const auto &module_desc : *m_rsmodules) {
862b3bbcb12SLuke Drummond     if (module_desc->m_module != module)
863b3bbcb12SLuke Drummond       continue;
864b3bbcb12SLuke Drummond 
865b3bbcb12SLuke Drummond     for (const auto &reduction : module_desc->m_reductions) {
866b3bbcb12SLuke Drummond       if (reduction.m_reduce_name != m_reduce_name)
867b3bbcb12SLuke Drummond         continue;
868b3bbcb12SLuke Drummond 
869b3bbcb12SLuke Drummond       std::array<std::pair<ConstString, int>, 5> funcs{
870b3bbcb12SLuke Drummond           {{reduction.m_init_name, eKernelTypeInit},
871b3bbcb12SLuke Drummond            {reduction.m_accum_name, eKernelTypeAccum},
872b3bbcb12SLuke Drummond            {reduction.m_comb_name, eKernelTypeComb},
873b3bbcb12SLuke Drummond            {reduction.m_outc_name, eKernelTypeOutC},
874b3bbcb12SLuke Drummond            {reduction.m_halter_name, eKernelTypeHalter}}};
875b3bbcb12SLuke Drummond 
876b3bbcb12SLuke Drummond       for (const auto &kernel : funcs) {
877b3bbcb12SLuke Drummond         // Skip constituent functions that don't match our spec
878b3bbcb12SLuke Drummond         if (!(m_kernel_types & kernel.second))
879b3bbcb12SLuke Drummond           continue;
880b3bbcb12SLuke Drummond 
881b3bbcb12SLuke Drummond         const auto kernel_name = kernel.first;
882b3bbcb12SLuke Drummond         const auto symbol = module->FindFirstSymbolWithNameAndType(
883b3bbcb12SLuke Drummond             kernel_name, eSymbolTypeCode);
884b3bbcb12SLuke Drummond         if (!symbol)
885b3bbcb12SLuke Drummond           continue;
886b3bbcb12SLuke Drummond 
887b3bbcb12SLuke Drummond         auto address = symbol->GetAddress();
888b3bbcb12SLuke Drummond         if (filter.AddressPasses(address)) {
889b3bbcb12SLuke Drummond           bool new_bp;
89081fc84faSLuke Drummond           if (!SkipPrologue(module, address)) {
89181fc84faSLuke Drummond             if (log)
89281fc84faSLuke Drummond               log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
89381fc84faSLuke Drummond           }
894b3bbcb12SLuke Drummond           m_breakpoint->AddLocation(address, &new_bp);
895b3bbcb12SLuke Drummond           if (log)
896b3bbcb12SLuke Drummond             log->Printf("%s: %s reduction breakpoint on %s in %s", __FUNCTION__,
897b3bbcb12SLuke Drummond                         new_bp ? "new" : "existing", kernel_name.GetCString(),
898b3bbcb12SLuke Drummond                         address.GetModule()->GetFileSpec().GetCString());
899b3bbcb12SLuke Drummond         }
900b3bbcb12SLuke Drummond       }
901b3bbcb12SLuke Drummond     }
902b3bbcb12SLuke Drummond   }
903b3bbcb12SLuke Drummond   return eCallbackReturnContinue;
904b3bbcb12SLuke Drummond }
905b3bbcb12SLuke Drummond 
90621fed052SAidan Dodds Searcher::CallbackReturn RSScriptGroupBreakpointResolver::SearchCallback(
90721fed052SAidan Dodds     SearchFilter &filter, SymbolContext &context, Address *addr,
90821fed052SAidan Dodds     bool containing) {
90921fed052SAidan Dodds 
91021fed052SAidan Dodds   if (!m_breakpoint)
91121fed052SAidan Dodds     return eCallbackReturnContinue;
91221fed052SAidan Dodds 
91321fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
91421fed052SAidan Dodds   ModuleSP &module = context.module_sp;
91521fed052SAidan Dodds 
91621fed052SAidan Dodds   if (!module || !IsRenderScriptScriptModule(module))
91721fed052SAidan Dodds     return Searcher::eCallbackReturnContinue;
91821fed052SAidan Dodds 
91921fed052SAidan Dodds   std::vector<std::string> names;
92021fed052SAidan Dodds   m_breakpoint->GetNames(names);
92121fed052SAidan Dodds   if (names.empty())
92221fed052SAidan Dodds     return eCallbackReturnContinue;
92321fed052SAidan Dodds 
92421fed052SAidan Dodds   for (auto &name : names) {
92521fed052SAidan Dodds     const RSScriptGroupDescriptorSP sg = FindScriptGroup(ConstString(name));
92621fed052SAidan Dodds     if (!sg) {
92721fed052SAidan Dodds       if (log)
92821fed052SAidan Dodds         log->Printf("%s: could not find script group for %s", __FUNCTION__,
92921fed052SAidan Dodds                     name.c_str());
93021fed052SAidan Dodds       continue;
93121fed052SAidan Dodds     }
93221fed052SAidan Dodds 
93321fed052SAidan Dodds     if (log)
93421fed052SAidan Dodds       log->Printf("%s: Found ScriptGroup for %s", __FUNCTION__, name.c_str());
93521fed052SAidan Dodds 
93621fed052SAidan Dodds     for (const RSScriptGroupDescriptor::Kernel &k : sg->m_kernels) {
93721fed052SAidan Dodds       if (log) {
93821fed052SAidan Dodds         log->Printf("%s: Adding breakpoint for %s", __FUNCTION__,
93921fed052SAidan Dodds                     k.m_name.AsCString());
94021fed052SAidan Dodds         log->Printf("%s: Kernel address 0x%" PRIx64, __FUNCTION__, k.m_addr);
94121fed052SAidan Dodds       }
94221fed052SAidan Dodds 
94321fed052SAidan Dodds       const lldb_private::Symbol *sym =
94421fed052SAidan Dodds           module->FindFirstSymbolWithNameAndType(k.m_name, eSymbolTypeCode);
94521fed052SAidan Dodds       if (!sym) {
94621fed052SAidan Dodds         if (log)
94721fed052SAidan Dodds           log->Printf("%s: Unable to find symbol for %s", __FUNCTION__,
94821fed052SAidan Dodds                       k.m_name.AsCString());
94921fed052SAidan Dodds         continue;
95021fed052SAidan Dodds       }
95121fed052SAidan Dodds 
95221fed052SAidan Dodds       if (log) {
95321fed052SAidan Dodds         log->Printf("%s: Found symbol name is %s", __FUNCTION__,
95421fed052SAidan Dodds                     sym->GetName().AsCString());
95521fed052SAidan Dodds       }
95621fed052SAidan Dodds 
95721fed052SAidan Dodds       auto address = sym->GetAddress();
95821fed052SAidan Dodds       if (!SkipPrologue(module, address)) {
95921fed052SAidan Dodds         if (log)
96021fed052SAidan Dodds           log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
96121fed052SAidan Dodds       }
96221fed052SAidan Dodds 
96321fed052SAidan Dodds       bool new_bp;
96421fed052SAidan Dodds       m_breakpoint->AddLocation(address, &new_bp);
96521fed052SAidan Dodds 
96621fed052SAidan Dodds       if (log)
96721fed052SAidan Dodds         log->Printf("%s: Placed %sbreakpoint on %s", __FUNCTION__,
96821fed052SAidan Dodds                     new_bp ? "new " : "", k.m_name.AsCString());
96921fed052SAidan Dodds 
97021fed052SAidan Dodds       // exit after placing the first breakpoint if we do not intend to stop
97121fed052SAidan Dodds       // on all kernels making up this script group
97221fed052SAidan Dodds       if (!m_stop_on_all)
97321fed052SAidan Dodds         break;
97421fed052SAidan Dodds     }
97521fed052SAidan Dodds   }
97621fed052SAidan Dodds 
97721fed052SAidan Dodds   return eCallbackReturnContinue;
97821fed052SAidan Dodds }
97921fed052SAidan Dodds 
980b9c1b51eSKate Stone void RenderScriptRuntime::Initialize() {
981b9c1b51eSKate Stone   PluginManager::RegisterPlugin(GetPluginNameStatic(),
982b9c1b51eSKate Stone                                 "RenderScript language support", CreateInstance,
983b3f7f69dSAidan Dodds                                 GetCommandObject);
9845ec532a9SColin Riley }
9855ec532a9SColin Riley 
986b9c1b51eSKate Stone void RenderScriptRuntime::Terminate() {
9875ec532a9SColin Riley   PluginManager::UnregisterPlugin(CreateInstance);
9885ec532a9SColin Riley }
9895ec532a9SColin Riley 
990b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginNameStatic() {
99180af0b9eSLuke Drummond   static ConstString plugin_name("renderscript");
99280af0b9eSLuke Drummond   return plugin_name;
9935ec532a9SColin Riley }
9945ec532a9SColin Riley 
995ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
996b9c1b51eSKate Stone RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
997b9c1b51eSKate Stone   if (module_sp) {
998b3bbcb12SLuke Drummond     if (IsRenderScriptScriptModule(module_sp))
999ef20b08fSColin Riley       return eModuleKindKernelObj;
10004640cde1SColin Riley 
10014640cde1SColin Riley     // Is this the main RS runtime library
10024640cde1SColin Riley     const ConstString rs_lib("libRS.so");
1003b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
10044640cde1SColin Riley       return eModuleKindLibRS;
10054640cde1SColin Riley     }
10064640cde1SColin Riley 
10074640cde1SColin Riley     const ConstString rs_driverlib("libRSDriver.so");
1008b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
10094640cde1SColin Riley       return eModuleKindDriver;
10104640cde1SColin Riley     }
10114640cde1SColin Riley 
101215f2bd95SEwan Crawford     const ConstString rs_cpureflib("libRSCpuRef.so");
1013b9c1b51eSKate Stone     if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
10144640cde1SColin Riley       return eModuleKindImpl;
10154640cde1SColin Riley     }
1016ef20b08fSColin Riley   }
1017ef20b08fSColin Riley   return eModuleKindIgnored;
1018ef20b08fSColin Riley }
1019ef20b08fSColin Riley 
1020b9c1b51eSKate Stone bool RenderScriptRuntime::IsRenderScriptModule(
1021b9c1b51eSKate Stone     const lldb::ModuleSP &module_sp) {
1022ef20b08fSColin Riley   return GetModuleKind(module_sp) != eModuleKindIgnored;
1023ef20b08fSColin Riley }
1024ef20b08fSColin Riley 
1025b9c1b51eSKate Stone void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
1026bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1027ef20b08fSColin Riley 
1028ef20b08fSColin Riley   size_t num_modules = module_list.GetSize();
1029b9c1b51eSKate Stone   for (size_t i = 0; i < num_modules; i++) {
1030ef20b08fSColin Riley     auto mod = module_list.GetModuleAtIndex(i);
1031b9c1b51eSKate Stone     if (IsRenderScriptModule(mod)) {
1032ef20b08fSColin Riley       LoadModule(mod);
1033ef20b08fSColin Riley     }
1034ef20b08fSColin Riley   }
1035ef20b08fSColin Riley }
1036ef20b08fSColin Riley 
10375ec532a9SColin Riley //------------------------------------------------------------------
10385ec532a9SColin Riley // PluginInterface protocol
10395ec532a9SColin Riley //------------------------------------------------------------------
1040b9c1b51eSKate Stone lldb_private::ConstString RenderScriptRuntime::GetPluginName() {
10415ec532a9SColin Riley   return GetPluginNameStatic();
10425ec532a9SColin Riley }
10435ec532a9SColin Riley 
1044b9c1b51eSKate Stone uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; }
10455ec532a9SColin Riley 
1046b9c1b51eSKate Stone bool RenderScriptRuntime::IsVTableName(const char *name) { return false; }
10475ec532a9SColin Riley 
1048b9c1b51eSKate Stone bool RenderScriptRuntime::GetDynamicTypeAndAddress(
1049b9c1b51eSKate Stone     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
10505f57b6eeSEnrico Granata     TypeAndOrName &class_type_or_name, Address &address,
1051b9c1b51eSKate Stone     Value::ValueType &value_type) {
10525ec532a9SColin Riley   return false;
10535ec532a9SColin Riley }
10545ec532a9SColin Riley 
1055c74275bcSEnrico Granata TypeAndOrName
1056b9c1b51eSKate Stone RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
1057b9c1b51eSKate Stone                                       ValueObject &static_value) {
1058c74275bcSEnrico Granata   return type_and_or_name;
1059c74275bcSEnrico Granata }
1060c74275bcSEnrico Granata 
1061b9c1b51eSKate Stone bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
10625ec532a9SColin Riley   return false;
10635ec532a9SColin Riley }
10645ec532a9SColin Riley 
10655ec532a9SColin Riley lldb::BreakpointResolverSP
106680af0b9eSLuke Drummond RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bp, bool catch_bp,
1067b9c1b51eSKate Stone                                              bool throw_bp) {
10685ec532a9SColin Riley   BreakpointResolverSP resolver_sp;
10695ec532a9SColin Riley   return resolver_sp;
10705ec532a9SColin Riley }
10715ec532a9SColin Riley 
1072b9c1b51eSKate Stone const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
1073b9c1b51eSKate Stone     {
10744640cde1SColin Riley         // rsdScript
1075b9c1b51eSKate Stone         {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
1076b9c1b51eSKate Stone                           "NS0_7ScriptCEPKcS7_PKhjj",
1077b9c1b51eSKate Stone          "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
1078b9c1b51eSKate Stone          "7ScriptCEPKcS7_PKhmj",
1079b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1080b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInit},
1081b9c1b51eSKate Stone         {"rsdScriptInvokeForEachMulti",
1082b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1083b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
1084b9c1b51eSKate Stone          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1085b9c1b51eSKate Stone          "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
1086b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1087b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
1088b9c1b51eSKate Stone         {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
1089b9c1b51eSKate Stone                                   "script7ContextEPKNS0_6ScriptEjPvj",
1090b9c1b51eSKate Stone          "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
1091b9c1b51eSKate Stone          "6ScriptEjPvm",
1092b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1093b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
10944640cde1SColin Riley 
10954640cde1SColin Riley         // rsdAllocation
1096b9c1b51eSKate Stone         {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
1097b9c1b51eSKate Stone                               "ontextEPNS0_10AllocationEb",
1098b9c1b51eSKate Stone          "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
1099b9c1b51eSKate Stone          "10AllocationEb",
1100b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1101b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
1102b9c1b51eSKate Stone         {"rsdAllocationRead2D",
1103b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1104b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1105b9c1b51eSKate Stone          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1106b9c1b51eSKate Stone          "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1107b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1108b9c1b51eSKate Stone         {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1109b9c1b51eSKate Stone                                  "ript7ContextEPNS0_10AllocationE",
1110b9c1b51eSKate Stone          "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1111b9c1b51eSKate Stone          "10AllocationE",
1112b9c1b51eSKate Stone          0, RenderScriptRuntime::eModuleKindDriver,
1113b9c1b51eSKate Stone          &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
111421fed052SAidan Dodds 
111521fed052SAidan Dodds         // renderscript script groups
111621fed052SAidan Dodds         {"rsdDebugHintScriptGroup2", "_ZN7android12renderscript21debugHintScrip"
111721fed052SAidan Dodds                                      "tGroup2EPKcjPKPFvPK24RsExpandKernelDriver"
111821fed052SAidan Dodds                                      "InfojjjEj",
111921fed052SAidan Dodds          "_ZN7android12renderscript21debugHintScriptGroup2EPKcjPKPFvPK24RsExpan"
112021fed052SAidan Dodds          "dKernelDriverInfojjjEj",
112121fed052SAidan Dodds          0, RenderScriptRuntime::eModuleKindImpl,
112221fed052SAidan Dodds          &lldb_private::RenderScriptRuntime::CaptureDebugHintScriptGroup2}};
11234640cde1SColin Riley 
1124b9c1b51eSKate Stone const size_t RenderScriptRuntime::s_runtimeHookCount =
1125b9c1b51eSKate Stone     sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
11264640cde1SColin Riley 
1127b9c1b51eSKate Stone bool RenderScriptRuntime::HookCallback(void *baton,
1128b9c1b51eSKate Stone                                        StoppointCallbackContext *ctx,
1129b9c1b51eSKate Stone                                        lldb::user_id_t break_id,
1130b9c1b51eSKate Stone                                        lldb::user_id_t break_loc_id) {
113180af0b9eSLuke Drummond   RuntimeHook *hook = (RuntimeHook *)baton;
113280af0b9eSLuke Drummond   ExecutionContext exe_ctx(ctx->exe_ctx_ref);
11334640cde1SColin Riley 
1134b3f7f69dSAidan Dodds   RenderScriptRuntime *lang_rt =
113580af0b9eSLuke Drummond       (RenderScriptRuntime *)exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1136b9c1b51eSKate Stone           eLanguageTypeExtRenderScript);
11374640cde1SColin Riley 
113880af0b9eSLuke Drummond   lang_rt->HookCallback(hook, exe_ctx);
11394640cde1SColin Riley 
11404640cde1SColin Riley   return false;
11414640cde1SColin Riley }
11424640cde1SColin Riley 
114380af0b9eSLuke Drummond void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
114480af0b9eSLuke Drummond                                        ExecutionContext &exe_ctx) {
11454640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11464640cde1SColin Riley 
11474640cde1SColin Riley   if (log)
114880af0b9eSLuke Drummond     log->Printf("%s - '%s'", __FUNCTION__, hook->defn->name);
11494640cde1SColin Riley 
115080af0b9eSLuke Drummond   if (hook->defn->grabber) {
115180af0b9eSLuke Drummond     (this->*(hook->defn->grabber))(hook, exe_ctx);
11524640cde1SColin Riley   }
11534640cde1SColin Riley }
11544640cde1SColin Riley 
115521fed052SAidan Dodds void RenderScriptRuntime::CaptureDebugHintScriptGroup2(
115621fed052SAidan Dodds     RuntimeHook *hook_info, ExecutionContext &context) {
115721fed052SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
115821fed052SAidan Dodds 
115921fed052SAidan Dodds   enum {
116021fed052SAidan Dodds     eGroupName = 0,
116121fed052SAidan Dodds     eGroupNameSize,
116221fed052SAidan Dodds     eKernel,
116321fed052SAidan Dodds     eKernelCount,
116421fed052SAidan Dodds   };
116521fed052SAidan Dodds 
116621fed052SAidan Dodds   std::array<ArgItem, 4> args{{
116721fed052SAidan Dodds       {ArgItem::ePointer, 0}, // const char         *groupName
116821fed052SAidan Dodds       {ArgItem::eInt32, 0},   // const uint32_t      groupNameSize
116921fed052SAidan Dodds       {ArgItem::ePointer, 0}, // const ExpandFuncTy *kernel
117021fed052SAidan Dodds       {ArgItem::eInt32, 0},   // const uint32_t      kernelCount
117121fed052SAidan Dodds   }};
117221fed052SAidan Dodds 
117321fed052SAidan Dodds   if (!GetArgs(context, args.data(), args.size())) {
117421fed052SAidan Dodds     if (log)
117521fed052SAidan Dodds       log->Printf("%s - Error while reading the function parameters",
117621fed052SAidan Dodds                   __FUNCTION__);
117721fed052SAidan Dodds     return;
117821fed052SAidan Dodds   } else if (log) {
117921fed052SAidan Dodds     log->Printf("%s - groupName    : 0x%" PRIx64, __FUNCTION__,
118021fed052SAidan Dodds                 addr_t(args[eGroupName]));
118121fed052SAidan Dodds     log->Printf("%s - groupNameSize: %" PRIu64, __FUNCTION__,
118221fed052SAidan Dodds                 uint64_t(args[eGroupNameSize]));
118321fed052SAidan Dodds     log->Printf("%s - kernel       : 0x%" PRIx64, __FUNCTION__,
118421fed052SAidan Dodds                 addr_t(args[eKernel]));
118521fed052SAidan Dodds     log->Printf("%s - kernelCount  : %" PRIu64, __FUNCTION__,
118621fed052SAidan Dodds                 uint64_t(args[eKernelCount]));
118721fed052SAidan Dodds   }
118821fed052SAidan Dodds 
118921fed052SAidan Dodds   // parse script group name
119021fed052SAidan Dodds   ConstString group_name;
119121fed052SAidan Dodds   {
119297206d57SZachary Turner     Status err;
119321fed052SAidan Dodds     const uint64_t len = uint64_t(args[eGroupNameSize]);
119421fed052SAidan Dodds     std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]);
119521fed052SAidan Dodds     m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err);
119621fed052SAidan Dodds     buffer.get()[len] = '\0';
119721fed052SAidan Dodds     if (!err.Success()) {
119821fed052SAidan Dodds       if (log)
119921fed052SAidan Dodds         log->Printf("Error reading scriptgroup name from target");
120021fed052SAidan Dodds       return;
120121fed052SAidan Dodds     } else {
120221fed052SAidan Dodds       if (log)
120321fed052SAidan Dodds         log->Printf("Extracted scriptgroup name %s", buffer.get());
120421fed052SAidan Dodds     }
120521fed052SAidan Dodds     // write back the script group name
120621fed052SAidan Dodds     group_name.SetCString(buffer.get());
120721fed052SAidan Dodds   }
120821fed052SAidan Dodds 
120921fed052SAidan Dodds   // create or access existing script group
121021fed052SAidan Dodds   RSScriptGroupDescriptorSP group;
121121fed052SAidan Dodds   {
121221fed052SAidan Dodds     // search for existing script group
121321fed052SAidan Dodds     for (auto sg : m_scriptGroups) {
121421fed052SAidan Dodds       if (sg->m_name == group_name) {
121521fed052SAidan Dodds         group = sg;
121621fed052SAidan Dodds         break;
121721fed052SAidan Dodds       }
121821fed052SAidan Dodds     }
121921fed052SAidan Dodds     if (!group) {
122021fed052SAidan Dodds       group.reset(new RSScriptGroupDescriptor);
122121fed052SAidan Dodds       group->m_name = group_name;
122221fed052SAidan Dodds       m_scriptGroups.push_back(group);
122321fed052SAidan Dodds     } else {
122421fed052SAidan Dodds       // already have this script group
122521fed052SAidan Dodds       if (log)
122621fed052SAidan Dodds         log->Printf("Attempt to add duplicate script group %s",
122721fed052SAidan Dodds                     group_name.AsCString());
122821fed052SAidan Dodds       return;
122921fed052SAidan Dodds     }
123021fed052SAidan Dodds   }
123121fed052SAidan Dodds   assert(group);
123221fed052SAidan Dodds 
123321fed052SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
123421fed052SAidan Dodds   std::vector<addr_t> kernels;
123521fed052SAidan Dodds   // parse kernel addresses in script group
123621fed052SAidan Dodds   for (uint64_t i = 0; i < uint64_t(args[eKernelCount]); ++i) {
123721fed052SAidan Dodds     RSScriptGroupDescriptor::Kernel kernel;
123821fed052SAidan Dodds     // extract script group kernel addresses from the target
123921fed052SAidan Dodds     const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size;
124021fed052SAidan Dodds     uint64_t kernel_addr = 0;
124197206d57SZachary Turner     Status err;
124221fed052SAidan Dodds     size_t read =
124321fed052SAidan Dodds         m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err);
124421fed052SAidan Dodds     if (!err.Success() || read != target_ptr_size) {
124521fed052SAidan Dodds       if (log)
124621fed052SAidan Dodds         log->Printf("Error parsing kernel address %" PRIu64 " in script group",
124721fed052SAidan Dodds                     i);
124821fed052SAidan Dodds       return;
124921fed052SAidan Dodds     }
125021fed052SAidan Dodds     if (log)
125121fed052SAidan Dodds       log->Printf("Extracted scriptgroup kernel address - 0x%" PRIx64,
125221fed052SAidan Dodds                   kernel_addr);
125321fed052SAidan Dodds     kernel.m_addr = kernel_addr;
125421fed052SAidan Dodds 
125521fed052SAidan Dodds     // try to resolve the associated kernel name
125621fed052SAidan Dodds     if (!ResolveKernelName(kernel.m_addr, kernel.m_name)) {
125721fed052SAidan Dodds       if (log)
125821fed052SAidan Dodds         log->Printf("Parsed scriptgroup kernel %" PRIu64 " - 0x%" PRIx64, i,
125921fed052SAidan Dodds                     kernel_addr);
126021fed052SAidan Dodds       return;
126121fed052SAidan Dodds     }
126221fed052SAidan Dodds 
126321fed052SAidan Dodds     // try to find the non '.expand' function
126421fed052SAidan Dodds     {
126521fed052SAidan Dodds       const llvm::StringRef expand(".expand");
126621fed052SAidan Dodds       const llvm::StringRef name_ref = kernel.m_name.GetStringRef();
126721fed052SAidan Dodds       if (name_ref.endswith(expand)) {
126821fed052SAidan Dodds         const ConstString base_kernel(name_ref.drop_back(expand.size()));
126921fed052SAidan Dodds         // verify this function is a valid kernel
127021fed052SAidan Dodds         if (IsKnownKernel(base_kernel)) {
127121fed052SAidan Dodds           kernel.m_name = base_kernel;
127221fed052SAidan Dodds           if (log)
127321fed052SAidan Dodds             log->Printf("%s - found non expand version '%s'", __FUNCTION__,
127421fed052SAidan Dodds                         base_kernel.GetCString());
127521fed052SAidan Dodds         }
127621fed052SAidan Dodds       }
127721fed052SAidan Dodds     }
127821fed052SAidan Dodds     // add to a list of script group kernels we know about
127921fed052SAidan Dodds     group->m_kernels.push_back(kernel);
128021fed052SAidan Dodds   }
128121fed052SAidan Dodds 
128221fed052SAidan Dodds   // Resolve any pending scriptgroup breakpoints
128321fed052SAidan Dodds   {
128421fed052SAidan Dodds     Target &target = m_process->GetTarget();
128521fed052SAidan Dodds     const BreakpointList &list = target.GetBreakpointList();
128621fed052SAidan Dodds     const size_t num_breakpoints = list.GetSize();
128721fed052SAidan Dodds     if (log)
128821fed052SAidan Dodds       log->Printf("Resolving %zu breakpoints", num_breakpoints);
128921fed052SAidan Dodds     for (size_t i = 0; i < num_breakpoints; ++i) {
129021fed052SAidan Dodds       const BreakpointSP bp = list.GetBreakpointAtIndex(i);
129121fed052SAidan Dodds       if (bp) {
129221fed052SAidan Dodds         if (bp->MatchesName(group_name.AsCString())) {
129321fed052SAidan Dodds           if (log)
129421fed052SAidan Dodds             log->Printf("Found breakpoint with name %s",
129521fed052SAidan Dodds                         group_name.AsCString());
129621fed052SAidan Dodds           bp->ResolveBreakpoint();
129721fed052SAidan Dodds         }
129821fed052SAidan Dodds       }
129921fed052SAidan Dodds     }
130021fed052SAidan Dodds   }
130121fed052SAidan Dodds }
130221fed052SAidan Dodds 
1303b9c1b51eSKate Stone void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
130480af0b9eSLuke Drummond     RuntimeHook *hook, ExecutionContext &exe_ctx) {
1305e09c44b6SAidan Dodds   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1306e09c44b6SAidan Dodds 
1307b9c1b51eSKate Stone   enum {
1308f4786785SAidan Dodds     eRsContext = 0,
1309f4786785SAidan Dodds     eRsScript,
1310f4786785SAidan Dodds     eRsSlot,
1311f4786785SAidan Dodds     eRsAIns,
1312f4786785SAidan Dodds     eRsInLen,
1313f4786785SAidan Dodds     eRsAOut,
1314f4786785SAidan Dodds     eRsUsr,
1315f4786785SAidan Dodds     eRsUsrLen,
1316f4786785SAidan Dodds     eRsSc,
1317f4786785SAidan Dodds   };
1318e09c44b6SAidan Dodds 
13191ee07253SSaleem Abdulrasool   std::array<ArgItem, 9> args{{
1320f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Context       *rsc
1321f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Script              *s
1322f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // uint32_t             slot
1323f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const Allocation   **aIns
1324f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               inLen
1325f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // Allocation          *aout
1326f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const void          *usr
1327f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // size_t               usrLen
1328f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall  *sc
13291ee07253SSaleem Abdulrasool   }};
1330e09c44b6SAidan Dodds 
133180af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1332b9c1b51eSKate Stone   if (!success) {
1333e09c44b6SAidan Dodds     if (log)
1334b9c1b51eSKate Stone       log->Printf("%s - Error while reading the function parameters",
1335b9c1b51eSKate Stone                   __FUNCTION__);
1336e09c44b6SAidan Dodds     return;
1337e09c44b6SAidan Dodds   }
1338e09c44b6SAidan Dodds 
1339e09c44b6SAidan Dodds   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
134097206d57SZachary Turner   Status err;
1341e09c44b6SAidan Dodds   std::vector<uint64_t> allocs;
1342e09c44b6SAidan Dodds 
1343e09c44b6SAidan Dodds   // traverse allocation list
1344b9c1b51eSKate Stone   for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1345e09c44b6SAidan Dodds     // calculate offest to allocation pointer
1346f4786785SAidan Dodds     const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1347e09c44b6SAidan Dodds 
134880af0b9eSLuke Drummond     // Note: due to little endian layout, reading 32bits or 64bits into res
134980af0b9eSLuke Drummond     // will give the correct results.
135080af0b9eSLuke Drummond     uint64_t result = 0;
135180af0b9eSLuke Drummond     size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
135280af0b9eSLuke Drummond     if (read != target_ptr_size || !err.Success()) {
1353e09c44b6SAidan Dodds       if (log)
1354b9c1b51eSKate Stone         log->Printf(
1355b9c1b51eSKate Stone             "%s - Error while reading allocation list argument %" PRIu64,
1356b9c1b51eSKate Stone             __FUNCTION__, i);
1357b9c1b51eSKate Stone     } else {
135880af0b9eSLuke Drummond       allocs.push_back(result);
1359e09c44b6SAidan Dodds     }
1360e09c44b6SAidan Dodds   }
1361e09c44b6SAidan Dodds 
1362e09c44b6SAidan Dodds   // if there is an output allocation track it
136380af0b9eSLuke Drummond   if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
136480af0b9eSLuke Drummond     allocs.push_back(alloc_out);
1365e09c44b6SAidan Dodds   }
1366e09c44b6SAidan Dodds 
1367e09c44b6SAidan Dodds   // for all allocations we have found
1368b9c1b51eSKate Stone   for (const uint64_t alloc_addr : allocs) {
13695d057637SLuke Drummond     AllocationDetails *alloc = LookUpAllocation(alloc_addr);
13705d057637SLuke Drummond     if (!alloc)
13715d057637SLuke Drummond       alloc = CreateAllocation(alloc_addr);
13725d057637SLuke Drummond 
1373b9c1b51eSKate Stone     if (alloc) {
1374e09c44b6SAidan Dodds       // save the allocation address
1375b9c1b51eSKate Stone       if (alloc->address.isValid()) {
1376e09c44b6SAidan Dodds         // check the allocation address we already have matches
1377e09c44b6SAidan Dodds         assert(*alloc->address.get() == alloc_addr);
1378b9c1b51eSKate Stone       } else {
1379e09c44b6SAidan Dodds         alloc->address = alloc_addr;
1380e09c44b6SAidan Dodds       }
1381e09c44b6SAidan Dodds 
1382e09c44b6SAidan Dodds       // save the context
1383b9c1b51eSKate Stone       if (log) {
1384b9c1b51eSKate Stone         if (alloc->context.isValid() &&
1385b9c1b51eSKate Stone             *alloc->context.get() != addr_t(args[eRsContext]))
1386b9c1b51eSKate Stone           log->Printf("%s - Allocation used by multiple contexts",
1387b9c1b51eSKate Stone                       __FUNCTION__);
1388e09c44b6SAidan Dodds       }
1389f4786785SAidan Dodds       alloc->context = addr_t(args[eRsContext]);
1390e09c44b6SAidan Dodds     }
1391e09c44b6SAidan Dodds   }
1392e09c44b6SAidan Dodds 
1393e09c44b6SAidan Dodds   // make sure we track this script object
1394b9c1b51eSKate Stone   if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1395b9c1b51eSKate Stone           LookUpScript(addr_t(args[eRsScript]), true)) {
1396b9c1b51eSKate Stone     if (log) {
1397b9c1b51eSKate Stone       if (script->context.isValid() &&
1398b9c1b51eSKate Stone           *script->context.get() != addr_t(args[eRsContext]))
1399b3f7f69dSAidan Dodds         log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1400e09c44b6SAidan Dodds     }
1401f4786785SAidan Dodds     script->context = addr_t(args[eRsContext]);
1402e09c44b6SAidan Dodds   }
1403e09c44b6SAidan Dodds }
1404e09c44b6SAidan Dodds 
140580af0b9eSLuke Drummond void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1406b9c1b51eSKate Stone                                               ExecutionContext &context) {
14074640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14084640cde1SColin Riley 
1409b9c1b51eSKate Stone   enum {
1410f4786785SAidan Dodds     eRsContext,
1411f4786785SAidan Dodds     eRsScript,
1412f4786785SAidan Dodds     eRsId,
1413f4786785SAidan Dodds     eRsData,
1414f4786785SAidan Dodds     eRsLength,
1415f4786785SAidan Dodds   };
14164640cde1SColin Riley 
14171ee07253SSaleem Abdulrasool   std::array<ArgItem, 5> args{{
1418f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1419f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsScript
1420f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsId
1421f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsData
1422f4786785SAidan Dodds       ArgItem{ArgItem::eInt32, 0},   // eRsLength
14231ee07253SSaleem Abdulrasool   }};
14244640cde1SColin Riley 
1425f4786785SAidan Dodds   bool success = GetArgs(context, &args[0], args.size());
1426b9c1b51eSKate Stone   if (!success) {
142782780287SAidan Dodds     if (log)
1428b3f7f69dSAidan Dodds       log->Printf("%s - error reading the function parameters.", __FUNCTION__);
142982780287SAidan Dodds     return;
143082780287SAidan Dodds   }
14314640cde1SColin Riley 
1432b9c1b51eSKate Stone   if (log) {
1433b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1434b9c1b51eSKate Stone                 ":%" PRIu64 "bytes.",
1435b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1436b9c1b51eSKate Stone                 uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1437f4786785SAidan Dodds                 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
14384640cde1SColin Riley 
1439f4786785SAidan Dodds     addr_t script_addr = addr_t(args[eRsScript]);
1440b9c1b51eSKate Stone     if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
14414640cde1SColin Riley       auto rsm = m_scriptMappings[script_addr];
1442b9c1b51eSKate Stone       if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1443f4786785SAidan Dodds         auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1444b9c1b51eSKate Stone         log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__,
1445b9c1b51eSKate Stone                     rsg.m_name.AsCString(),
1446f4786785SAidan Dodds                     rsm->m_module->GetFileSpec().GetFilename().AsCString());
14474640cde1SColin Riley       }
14484640cde1SColin Riley     }
14494640cde1SColin Riley   }
14504640cde1SColin Riley }
14514640cde1SColin Riley 
145280af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
145380af0b9eSLuke Drummond                                                 ExecutionContext &exe_ctx) {
14544640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14554640cde1SColin Riley 
1456b9c1b51eSKate Stone   enum { eRsContext, eRsAlloc, eRsForceZero };
14574640cde1SColin Riley 
14581ee07253SSaleem Abdulrasool   std::array<ArgItem, 3> args{{
1459f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1460f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1461f4786785SAidan Dodds       ArgItem{ArgItem::eBool, 0},    // eRsForceZero
14621ee07253SSaleem Abdulrasool   }};
14634640cde1SColin Riley 
146480af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
146580af0b9eSLuke Drummond   if (!success) {
146682780287SAidan Dodds     if (log)
1467b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters",
1468b9c1b51eSKate Stone                   __FUNCTION__);
146980af0b9eSLuke Drummond     return;
147082780287SAidan Dodds   }
14714640cde1SColin Riley 
14724640cde1SColin Riley   if (log)
1473b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1474b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
1475f4786785SAidan Dodds                 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
147678f339d1SEwan Crawford 
14775d057637SLuke Drummond   AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
147878f339d1SEwan Crawford   if (alloc)
1479f4786785SAidan Dodds     alloc->context = uint64_t(args[eRsContext]);
14804640cde1SColin Riley }
14814640cde1SColin Riley 
148280af0b9eSLuke Drummond void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
148380af0b9eSLuke Drummond                                                    ExecutionContext &exe_ctx) {
1484e69df382SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1485e69df382SEwan Crawford 
1486b9c1b51eSKate Stone   enum {
1487f4786785SAidan Dodds     eRsContext,
1488f4786785SAidan Dodds     eRsAlloc,
1489f4786785SAidan Dodds   };
1490e69df382SEwan Crawford 
14911ee07253SSaleem Abdulrasool   std::array<ArgItem, 2> args{{
1492f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1493f4786785SAidan Dodds       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
14941ee07253SSaleem Abdulrasool   }};
1495f4786785SAidan Dodds 
149680af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1497b9c1b51eSKate Stone   if (!success) {
1498e69df382SEwan Crawford     if (log)
1499b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1500b9c1b51eSKate Stone                   __FUNCTION__);
1501b3f7f69dSAidan Dodds     return;
1502e69df382SEwan Crawford   }
1503e69df382SEwan Crawford 
1504e69df382SEwan Crawford   if (log)
1505b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1506b9c1b51eSKate Stone                 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1507e69df382SEwan Crawford 
1508b9c1b51eSKate Stone   for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1509e69df382SEwan Crawford     auto &allocation_ap = *iter; // get the unique pointer
1510b9c1b51eSKate Stone     if (allocation_ap->address.isValid() &&
1511b9c1b51eSKate Stone         *allocation_ap->address.get() == addr_t(args[eRsAlloc])) {
1512e69df382SEwan Crawford       m_allocations.erase(iter);
1513e69df382SEwan Crawford       if (log)
1514b3f7f69dSAidan Dodds         log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1515e69df382SEwan Crawford       return;
1516e69df382SEwan Crawford     }
1517e69df382SEwan Crawford   }
1518e69df382SEwan Crawford 
1519e69df382SEwan Crawford   if (log)
1520b3f7f69dSAidan Dodds     log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1521e69df382SEwan Crawford }
1522e69df382SEwan Crawford 
152380af0b9eSLuke Drummond void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
152480af0b9eSLuke Drummond                                             ExecutionContext &exe_ctx) {
15254640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
15264640cde1SColin Riley 
152797206d57SZachary Turner   Status err;
152880af0b9eSLuke Drummond   Process *process = exe_ctx.GetProcessPtr();
15294640cde1SColin Riley 
1530b9c1b51eSKate Stone   enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
15314640cde1SColin Riley 
1532b9c1b51eSKate Stone   std::array<ArgItem, 4> args{
1533b9c1b51eSKate Stone       {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
15341ee07253SSaleem Abdulrasool        ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
153580af0b9eSLuke Drummond   bool success = GetArgs(exe_ctx, &args[0], args.size());
1536b9c1b51eSKate Stone   if (!success) {
153782780287SAidan Dodds     if (log)
1538b9c1b51eSKate Stone       log->Printf("%s - error while reading the function parameters.",
1539b9c1b51eSKate Stone                   __FUNCTION__);
154082780287SAidan Dodds     return;
154182780287SAidan Dodds   }
154282780287SAidan Dodds 
154380af0b9eSLuke Drummond   std::string res_name;
154480af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
154580af0b9eSLuke Drummond   if (err.Fail()) {
15464640cde1SColin Riley     if (log)
154780af0b9eSLuke Drummond       log->Printf("%s - error reading res_name: %s.", __FUNCTION__,
154880af0b9eSLuke Drummond                   err.AsCString());
15494640cde1SColin Riley   }
15504640cde1SColin Riley 
155180af0b9eSLuke Drummond   std::string cache_dir;
155280af0b9eSLuke Drummond   process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
155380af0b9eSLuke Drummond   if (err.Fail()) {
15544640cde1SColin Riley     if (log)
155580af0b9eSLuke Drummond       log->Printf("%s - error reading cache_dir: %s.", __FUNCTION__,
155680af0b9eSLuke Drummond                   err.AsCString());
15574640cde1SColin Riley   }
15584640cde1SColin Riley 
15594640cde1SColin Riley   if (log)
1560b9c1b51eSKate Stone     log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1561b9c1b51eSKate Stone                 __FUNCTION__, uint64_t(args[eRsContext]),
156280af0b9eSLuke Drummond                 uint64_t(args[eRsScript]), res_name.c_str(), cache_dir.c_str());
15634640cde1SColin Riley 
156480af0b9eSLuke Drummond   if (res_name.size() > 0) {
15654640cde1SColin Riley     StreamString strm;
156680af0b9eSLuke Drummond     strm.Printf("librs.%s.so", res_name.c_str());
15674640cde1SColin Riley 
1568f4786785SAidan Dodds     ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1569b9c1b51eSKate Stone     if (script) {
157078f339d1SEwan Crawford       script->type = ScriptDetails::eScriptC;
157180af0b9eSLuke Drummond       script->cache_dir = cache_dir;
157280af0b9eSLuke Drummond       script->res_name = res_name;
1573c156427dSZachary Turner       script->shared_lib = strm.GetString();
1574f4786785SAidan Dodds       script->context = addr_t(args[eRsContext]);
157578f339d1SEwan Crawford     }
15764640cde1SColin Riley 
15774640cde1SColin Riley     if (log)
1578b9c1b51eSKate Stone       log->Printf("%s - '%s' tagged with context 0x%" PRIx64
1579b9c1b51eSKate Stone                   " and script 0x%" PRIx64 ".",
1580b9c1b51eSKate Stone                   __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1581b9c1b51eSKate Stone                   uint64_t(args[eRsScript]));
1582b9c1b51eSKate Stone   } else if (log) {
1583b3f7f69dSAidan Dodds     log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
15844640cde1SColin Riley   }
15854640cde1SColin Riley }
15864640cde1SColin Riley 
1587b9c1b51eSKate Stone void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1588b9c1b51eSKate Stone                                            ModuleKind kind) {
15894640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
15904640cde1SColin Riley 
1591b9c1b51eSKate Stone   if (!module) {
15924640cde1SColin Riley     return;
15934640cde1SColin Riley   }
15944640cde1SColin Riley 
159582780287SAidan Dodds   Target &target = GetProcess()->GetTarget();
159621fed052SAidan Dodds   const llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
159782780287SAidan Dodds 
159880af0b9eSLuke Drummond   if (machine != llvm::Triple::ArchType::x86 &&
159980af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::arm &&
160080af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::aarch64 &&
160180af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mipsel &&
160280af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::mips64el &&
160380af0b9eSLuke Drummond       machine != llvm::Triple::ArchType::x86_64) {
16044640cde1SColin Riley     if (log)
1605b3f7f69dSAidan Dodds       log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
16064640cde1SColin Riley     return;
16074640cde1SColin Riley   }
16084640cde1SColin Riley 
160921fed052SAidan Dodds   const uint32_t target_ptr_size =
161021fed052SAidan Dodds       target.GetArchitecture().GetAddressByteSize();
161121fed052SAidan Dodds 
161221fed052SAidan Dodds   std::array<bool, s_runtimeHookCount> hook_placed;
161321fed052SAidan Dodds   hook_placed.fill(false);
16144640cde1SColin Riley 
1615b9c1b51eSKate Stone   for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
16164640cde1SColin Riley     const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1617b9c1b51eSKate Stone     if (hook_defn->kind != kind) {
16184640cde1SColin Riley       continue;
16194640cde1SColin Riley     }
16204640cde1SColin Riley 
162180af0b9eSLuke Drummond     const char *symbol_name = (target_ptr_size == 4)
162280af0b9eSLuke Drummond                                   ? hook_defn->symbol_name_m32
1623b9c1b51eSKate Stone                                   : hook_defn->symbol_name_m64;
162482780287SAidan Dodds 
1625b9c1b51eSKate Stone     const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1626b9c1b51eSKate Stone         ConstString(symbol_name), eSymbolTypeCode);
1627b9c1b51eSKate Stone     if (!sym) {
1628b9c1b51eSKate Stone       if (log) {
1629b3f7f69dSAidan Dodds         log->Printf("%s - symbol '%s' related to the function %s not found",
1630b3f7f69dSAidan Dodds                     __FUNCTION__, symbol_name, hook_defn->name);
163182780287SAidan Dodds       }
163282780287SAidan Dodds       continue;
163382780287SAidan Dodds     }
16344640cde1SColin Riley 
1635358cf1eaSGreg Clayton     addr_t addr = sym->GetLoadAddress(&target);
1636b9c1b51eSKate Stone     if (addr == LLDB_INVALID_ADDRESS) {
16374640cde1SColin Riley       if (log)
1638b9c1b51eSKate Stone         log->Printf("%s - unable to resolve the address of hook function '%s' "
1639b9c1b51eSKate Stone                     "with symbol '%s'.",
1640b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, symbol_name);
16414640cde1SColin Riley       continue;
1642b9c1b51eSKate Stone     } else {
164382780287SAidan Dodds       if (log)
1644b3f7f69dSAidan Dodds         log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1645b3f7f69dSAidan Dodds                     __FUNCTION__, hook_defn->name, addr);
164682780287SAidan Dodds     }
16474640cde1SColin Riley 
16484640cde1SColin Riley     RuntimeHookSP hook(new RuntimeHook());
16494640cde1SColin Riley     hook->address = addr;
16504640cde1SColin Riley     hook->defn = hook_defn;
16514640cde1SColin Riley     hook->bp_sp = target.CreateBreakpoint(addr, true, false);
16524640cde1SColin Riley     hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
16534640cde1SColin Riley     m_runtimeHooks[addr] = hook;
1654b9c1b51eSKate Stone     if (log) {
1655b9c1b51eSKate Stone       log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64
1656b9c1b51eSKate Stone                   " at 0x%" PRIx64 ".",
1657b9c1b51eSKate Stone                   __FUNCTION__, hook_defn->name,
1658b9c1b51eSKate Stone                   module->GetFileSpec().GetFilename().AsCString(),
1659b3f7f69dSAidan Dodds                   (uint64_t)hook_defn->version, (uint64_t)addr);
16604640cde1SColin Riley     }
166121fed052SAidan Dodds     hook_placed[idx] = true;
166221fed052SAidan Dodds   }
166321fed052SAidan Dodds 
166421fed052SAidan Dodds   // log any unhooked function
166521fed052SAidan Dodds   if (log) {
166621fed052SAidan Dodds     for (size_t i = 0; i < hook_placed.size(); ++i) {
166721fed052SAidan Dodds       if (hook_placed[i])
166821fed052SAidan Dodds         continue;
166921fed052SAidan Dodds       const HookDefn &hook_defn = s_runtimeHookDefns[i];
167021fed052SAidan Dodds       if (hook_defn.kind != kind)
167121fed052SAidan Dodds         continue;
167221fed052SAidan Dodds       log->Printf("%s - function %s was not hooked", __FUNCTION__,
167321fed052SAidan Dodds                   hook_defn.name);
167421fed052SAidan Dodds     }
16754640cde1SColin Riley   }
16764640cde1SColin Riley }
16774640cde1SColin Riley 
1678b9c1b51eSKate Stone void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
16794640cde1SColin Riley   if (!rsmodule_sp)
16804640cde1SColin Riley     return;
16814640cde1SColin Riley 
16824640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
16834640cde1SColin Riley 
16844640cde1SColin Riley   const ModuleSP module = rsmodule_sp->m_module;
16854640cde1SColin Riley   const FileSpec &file = module->GetPlatformFileSpec();
16864640cde1SColin Riley 
168778f339d1SEwan Crawford   // Iterate over all of the scripts that we currently know of.
168878f339d1SEwan Crawford   // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
1689b9c1b51eSKate Stone   for (const auto &rs_script : m_scripts) {
169078f339d1SEwan Crawford     // Extract the expected .so file path for this script.
169180af0b9eSLuke Drummond     std::string shared_lib;
169280af0b9eSLuke Drummond     if (!rs_script->shared_lib.get(shared_lib))
169378f339d1SEwan Crawford       continue;
169478f339d1SEwan Crawford 
169578f339d1SEwan Crawford     // Only proceed if the module that has loaded corresponds to this script.
169680af0b9eSLuke Drummond     if (file.GetFilename() != ConstString(shared_lib.c_str()))
169778f339d1SEwan Crawford       continue;
169878f339d1SEwan Crawford 
169978f339d1SEwan Crawford     // Obtain the script address which we use as a key.
170078f339d1SEwan Crawford     lldb::addr_t script;
170178f339d1SEwan Crawford     if (!rs_script->script.get(script))
170278f339d1SEwan Crawford       continue;
170378f339d1SEwan Crawford 
170478f339d1SEwan Crawford     // If we have a script mapping for the current script.
1705b9c1b51eSKate Stone     if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
170678f339d1SEwan Crawford       // if the module we have stored is different to the one we just received.
1707b9c1b51eSKate Stone       if (m_scriptMappings[script] != rsmodule_sp) {
17084640cde1SColin Riley         if (log)
1709b9c1b51eSKate Stone           log->Printf(
1710b9c1b51eSKate Stone               "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1711b9c1b51eSKate Stone               __FUNCTION__, (uint64_t)script,
1712b9c1b51eSKate Stone               rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
17134640cde1SColin Riley       }
17144640cde1SColin Riley     }
171578f339d1SEwan Crawford     // We don't have a script mapping for the current script.
1716b9c1b51eSKate Stone     else {
171778f339d1SEwan Crawford       // Obtain the script resource name.
171880af0b9eSLuke Drummond       std::string res_name;
171980af0b9eSLuke Drummond       if (rs_script->res_name.get(res_name))
172078f339d1SEwan Crawford         // Set the modules resource name.
172180af0b9eSLuke Drummond         rsmodule_sp->m_resname = res_name;
172278f339d1SEwan Crawford       // Add Script/Module pair to map.
172378f339d1SEwan Crawford       m_scriptMappings[script] = rsmodule_sp;
17244640cde1SColin Riley       if (log)
1725b9c1b51eSKate Stone         log->Printf(
1726b9c1b51eSKate Stone             "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1727b9c1b51eSKate Stone             __FUNCTION__, (uint64_t)script,
1728b9c1b51eSKate Stone             rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
17294640cde1SColin Riley     }
17304640cde1SColin Riley   }
17314640cde1SColin Riley }
17324640cde1SColin Riley 
1733b9c1b51eSKate Stone // Uses the Target API to evaluate the expression passed as a parameter to the
173480af0b9eSLuke Drummond // function The result of that expression is returned an unsigned 64 bit int,
173580af0b9eSLuke Drummond // via the result* parameter. Function returns true on success, and false on
173680af0b9eSLuke Drummond // failure
173780af0b9eSLuke Drummond bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1738b9c1b51eSKate Stone                                            StackFrame *frame_ptr,
1739b9c1b51eSKate Stone                                            uint64_t *result) {
174015f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
174115f2bd95SEwan Crawford   if (log)
174280af0b9eSLuke Drummond     log->Printf("%s(%s)", __FUNCTION__, expr);
174315f2bd95SEwan Crawford 
174415f2bd95SEwan Crawford   ValueObjectSP expr_result;
17458433fdbeSAidan Dodds   EvaluateExpressionOptions options;
17468433fdbeSAidan Dodds   options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
174715f2bd95SEwan Crawford   // Perform the actual expression evaluation
174880af0b9eSLuke Drummond   auto &target = GetProcess()->GetTarget();
174980af0b9eSLuke Drummond   target.EvaluateExpression(expr, frame_ptr, expr_result, options);
175015f2bd95SEwan Crawford 
1751b9c1b51eSKate Stone   if (!expr_result) {
175215f2bd95SEwan Crawford     if (log)
1753b3f7f69dSAidan Dodds       log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
175415f2bd95SEwan Crawford     return false;
175515f2bd95SEwan Crawford   }
175615f2bd95SEwan Crawford 
175715f2bd95SEwan Crawford   // The result of the expression is invalid
1758b9c1b51eSKate Stone   if (!expr_result->GetError().Success()) {
175997206d57SZachary Turner     Status err = expr_result->GetError();
176080af0b9eSLuke Drummond     // Expression returned is void, so this is actually a success
176180af0b9eSLuke Drummond     if (err.GetError() == UserExpression::kNoResult) {
176215f2bd95SEwan Crawford       if (log)
1763b3f7f69dSAidan Dodds         log->Printf("%s - expression returned void.", __FUNCTION__);
176415f2bd95SEwan Crawford 
176515f2bd95SEwan Crawford       result = nullptr;
176615f2bd95SEwan Crawford       return true;
176715f2bd95SEwan Crawford     }
176815f2bd95SEwan Crawford 
176915f2bd95SEwan Crawford     if (log)
1770b3f7f69dSAidan Dodds       log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1771b3f7f69dSAidan Dodds                   err.AsCString());
177215f2bd95SEwan Crawford     return false;
177315f2bd95SEwan Crawford   }
177415f2bd95SEwan Crawford 
177515f2bd95SEwan Crawford   bool success = false;
177680af0b9eSLuke Drummond   // We only read the result as an uint32_t.
177780af0b9eSLuke Drummond   *result = expr_result->GetValueAsUnsigned(0, &success);
177815f2bd95SEwan Crawford 
1779b9c1b51eSKate Stone   if (!success) {
178015f2bd95SEwan Crawford     if (log)
1781b9c1b51eSKate Stone       log->Printf("%s - couldn't convert expression result to uint32_t",
1782b9c1b51eSKate Stone                   __FUNCTION__);
178315f2bd95SEwan Crawford     return false;
178415f2bd95SEwan Crawford   }
178515f2bd95SEwan Crawford 
178615f2bd95SEwan Crawford   return true;
178715f2bd95SEwan Crawford }
178815f2bd95SEwan Crawford 
1789b9c1b51eSKate Stone namespace {
1790836d9651SEwan Crawford // Used to index expression format strings
1791b9c1b51eSKate Stone enum ExpressionStrings {
1792836d9651SEwan Crawford   eExprGetOffsetPtr = 0,
1793836d9651SEwan Crawford   eExprAllocGetType,
1794836d9651SEwan Crawford   eExprTypeDimX,
1795836d9651SEwan Crawford   eExprTypeDimY,
1796836d9651SEwan Crawford   eExprTypeDimZ,
1797836d9651SEwan Crawford   eExprTypeElemPtr,
1798836d9651SEwan Crawford   eExprElementType,
1799836d9651SEwan Crawford   eExprElementKind,
1800836d9651SEwan Crawford   eExprElementVec,
1801836d9651SEwan Crawford   eExprElementFieldCount,
1802836d9651SEwan Crawford   eExprSubelementsId,
1803836d9651SEwan Crawford   eExprSubelementsName,
1804ea0636b5SEwan Crawford   eExprSubelementsArrSize,
1805ea0636b5SEwan Crawford 
180680af0b9eSLuke Drummond   _eExprLast // keep at the end, implicit size of the array runtime_expressions
1807836d9651SEwan Crawford };
180815f2bd95SEwan Crawford 
1809ea0636b5SEwan Crawford // max length of an expanded expression
1810ea0636b5SEwan Crawford const int jit_max_expr_size = 512;
1811ea0636b5SEwan Crawford 
1812ea0636b5SEwan Crawford // Retrieve the string to JIT for the given expression
181336d783ebSDavid Gross #define JIT_TEMPLATE_CONTEXT "void* ctxt = (void*)rsDebugGetContextWrapper(0x%" PRIx64 "); "
1814b9c1b51eSKate Stone const char *JITTemplate(ExpressionStrings e) {
1815ea0636b5SEwan Crawford   // Format strings containing the expressions we may need to evaluate.
181680af0b9eSLuke Drummond   static std::array<const char *, _eExprLast> runtime_expressions = {
1817b9c1b51eSKate Stone       {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1818b9c1b51eSKate Stone        "(int*)_"
1819b9c1b51eSKate Stone        "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1820b9c1b51eSKate Stone        "CubemapFace"
182136d783ebSDavid Gross        "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)", // eExprGetOffsetPtr
182215f2bd95SEwan Crawford 
182315f2bd95SEwan Crawford        // Type* rsaAllocationGetType(Context*, Allocation*)
182436d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "(void*)rsaAllocationGetType(ctxt, 0x%" PRIx64 ")", // eExprAllocGetType
182515f2bd95SEwan Crawford 
182680af0b9eSLuke Drummond        // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
182780af0b9eSLuke Drummond        // data in the following way mHal.state.dimX; mHal.state.dimY;
182880af0b9eSLuke Drummond        // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement; into
182980af0b9eSLuke Drummond        // typeData Need to specify 32 or 64 bit for uint_t since this differs
183080af0b9eSLuke Drummond        // between devices
183136d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
183236d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
183336d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[0]", // eExprTypeDimX
183436d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
183536d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
183636d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[1]", // eExprTypeDimY
183736d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
183836d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
183936d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[2]", // eExprTypeDimZ
184036d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
184136d783ebSDavid Gross        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
184236d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 6); data[5]", // eExprTypeElemPtr
184315f2bd95SEwan Crawford 
184415f2bd95SEwan Crawford        // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1845b9c1b51eSKate Stone        // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1846b9c1b51eSKate Stone        // elemData
184736d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
184836d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
184936d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[0]", // eExprElementType
185036d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
185136d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
185236d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[1]", // eExprElementKind
185336d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
185436d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
185536d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[3]", // eExprElementVec
185636d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT
185736d783ebSDavid Gross        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
185836d783ebSDavid Gross        ", 0x%" PRIx64 ", data, 5); data[4]", // eExprElementFieldCount
18598b244e21SEwan Crawford 
1860b9c1b51eSKate Stone        // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
186180af0b9eSLuke Drummond        // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1862b9c1b51eSKate Stone        // Needed for Allocations of structs to gather details about
186380af0b9eSLuke Drummond        // fields/Subelements Element* of field
186436d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1865b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
186636d783ebSDavid Gross        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
186736d783ebSDavid Gross        ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]", // eExprSubelementsId
18688b244e21SEwan Crawford 
1869577570b4SAidan Dodds        // Name of field
187036d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1871b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
187236d783ebSDavid Gross        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
187336d783ebSDavid Gross        ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]", // eExprSubelementsName
18748b244e21SEwan Crawford 
1875577570b4SAidan Dodds        // Array size of field
187636d783ebSDavid Gross        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1877b9c1b51eSKate Stone        "]; size_t arr_size[%" PRIu32 "];"
187836d783ebSDavid Gross        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
187936d783ebSDavid Gross        ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}}; // eExprSubelementsArrSize
1880ea0636b5SEwan Crawford 
188180af0b9eSLuke Drummond   return runtime_expressions[e];
1882ea0636b5SEwan Crawford }
1883ea0636b5SEwan Crawford } // end of the anonymous namespace
1884ea0636b5SEwan Crawford 
188580af0b9eSLuke Drummond // JITs the RS runtime for the internal data pointer of an allocation. Is passed
188680af0b9eSLuke Drummond // x,y,z coordinates for the pointer to a specific element. Then sets the
188780af0b9eSLuke Drummond // data_ptr member in Allocation with the result. Returns true on success, false
188880af0b9eSLuke Drummond // otherwise
188980af0b9eSLuke Drummond bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1890b9c1b51eSKate Stone                                          StackFrame *frame_ptr, uint32_t x,
1891b9c1b51eSKate Stone                                          uint32_t y, uint32_t z) {
189215f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
189315f2bd95SEwan Crawford 
189480af0b9eSLuke Drummond   if (!alloc->address.isValid()) {
189515f2bd95SEwan Crawford     if (log)
1896b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
189715f2bd95SEwan Crawford     return false;
189815f2bd95SEwan Crawford   }
189915f2bd95SEwan Crawford 
190080af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
190180af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
190215f2bd95SEwan Crawford 
190380af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
190480af0b9eSLuke Drummond                          *alloc->address.get(), x, y, z);
190580af0b9eSLuke Drummond   if (written < 0) {
190615f2bd95SEwan Crawford     if (log)
1907b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
190815f2bd95SEwan Crawford     return false;
190980af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
191015f2bd95SEwan Crawford     if (log)
1911b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
191215f2bd95SEwan Crawford     return false;
191315f2bd95SEwan Crawford   }
191415f2bd95SEwan Crawford 
191515f2bd95SEwan Crawford   uint64_t result = 0;
191680af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
191715f2bd95SEwan Crawford     return false;
191815f2bd95SEwan Crawford 
191980af0b9eSLuke Drummond   addr_t data_ptr = static_cast<lldb::addr_t>(result);
192080af0b9eSLuke Drummond   alloc->data_ptr = data_ptr;
192115f2bd95SEwan Crawford 
192215f2bd95SEwan Crawford   return true;
192315f2bd95SEwan Crawford }
192415f2bd95SEwan Crawford 
192515f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
192680af0b9eSLuke Drummond // Then sets the type_ptr member in Allocation with the result. Returns true on
192780af0b9eSLuke Drummond // success, false otherwise
192880af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1929b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
193015f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
193115f2bd95SEwan Crawford 
193280af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->context.isValid()) {
193315f2bd95SEwan Crawford     if (log)
1934b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
193515f2bd95SEwan Crawford     return false;
193615f2bd95SEwan Crawford   }
193715f2bd95SEwan Crawford 
193880af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprAllocGetType);
193980af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
194015f2bd95SEwan Crawford 
194180af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
194280af0b9eSLuke Drummond                          *alloc->context.get(), *alloc->address.get());
194380af0b9eSLuke Drummond   if (written < 0) {
194415f2bd95SEwan Crawford     if (log)
1945b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
194615f2bd95SEwan Crawford     return false;
194780af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
194815f2bd95SEwan Crawford     if (log)
1949b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
195015f2bd95SEwan Crawford     return false;
195115f2bd95SEwan Crawford   }
195215f2bd95SEwan Crawford 
195315f2bd95SEwan Crawford   uint64_t result = 0;
195480af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
195515f2bd95SEwan Crawford     return false;
195615f2bd95SEwan Crawford 
195715f2bd95SEwan Crawford   addr_t type_ptr = static_cast<lldb::addr_t>(result);
195880af0b9eSLuke Drummond   alloc->type_ptr = type_ptr;
195915f2bd95SEwan Crawford 
196015f2bd95SEwan Crawford   return true;
196115f2bd95SEwan Crawford }
196215f2bd95SEwan Crawford 
1963b9c1b51eSKate Stone // JITs the RS runtime for information about the dimensions and type of an
196480af0b9eSLuke Drummond // allocation Then sets dimension and element_ptr members in Allocation with the
196580af0b9eSLuke Drummond // result. Returns true on success, false otherwise
196680af0b9eSLuke Drummond bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1967b9c1b51eSKate Stone                                         StackFrame *frame_ptr) {
196815f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
196915f2bd95SEwan Crawford 
197080af0b9eSLuke Drummond   if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
197115f2bd95SEwan Crawford     if (log)
1972b3f7f69dSAidan Dodds       log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
197315f2bd95SEwan Crawford     return false;
197415f2bd95SEwan Crawford   }
197515f2bd95SEwan Crawford 
197615f2bd95SEwan Crawford   // Expression is different depending on if device is 32 or 64 bit
197780af0b9eSLuke Drummond   uint32_t target_ptr_size =
1978b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
197980af0b9eSLuke Drummond   const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
198015f2bd95SEwan Crawford 
198115f2bd95SEwan Crawford   // We want 4 elements from packed data
1982b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
1983b9c1b51eSKate Stone   assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) &&
1984b9c1b51eSKate Stone          "Invalid number of expressions");
198515f2bd95SEwan Crawford 
198680af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
198715f2bd95SEwan Crawford   uint64_t results[num_exprs];
198815f2bd95SEwan Crawford 
1989b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; ++i) {
199080af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
199136d783ebSDavid Gross     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str,
199236d783ebSDavid Gross                            *alloc->context.get(), bits, *alloc->type_ptr.get());
199380af0b9eSLuke Drummond     if (written < 0) {
199415f2bd95SEwan Crawford       if (log)
1995b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
199615f2bd95SEwan Crawford       return false;
199780af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
199815f2bd95SEwan Crawford       if (log)
1999b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
200015f2bd95SEwan Crawford       return false;
200115f2bd95SEwan Crawford     }
200215f2bd95SEwan Crawford 
200315f2bd95SEwan Crawford     // Perform expression evaluation
200480af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
200515f2bd95SEwan Crawford       return false;
200615f2bd95SEwan Crawford   }
200715f2bd95SEwan Crawford 
200815f2bd95SEwan Crawford   // Assign results to allocation members
200915f2bd95SEwan Crawford   AllocationDetails::Dimension dims;
201015f2bd95SEwan Crawford   dims.dim_1 = static_cast<uint32_t>(results[0]);
201115f2bd95SEwan Crawford   dims.dim_2 = static_cast<uint32_t>(results[1]);
201215f2bd95SEwan Crawford   dims.dim_3 = static_cast<uint32_t>(results[2]);
201380af0b9eSLuke Drummond   alloc->dimension = dims;
201415f2bd95SEwan Crawford 
201580af0b9eSLuke Drummond   addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
201680af0b9eSLuke Drummond   alloc->element.element_ptr = element_ptr;
201715f2bd95SEwan Crawford 
201815f2bd95SEwan Crawford   if (log)
2019b9c1b51eSKate Stone     log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
2020b9c1b51eSKate Stone                 ") Element*: 0x%" PRIx64 ".",
202180af0b9eSLuke Drummond                 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
202215f2bd95SEwan Crawford 
202315f2bd95SEwan Crawford   return true;
202415f2bd95SEwan Crawford }
202515f2bd95SEwan Crawford 
202680af0b9eSLuke Drummond // JITs the RS runtime for information about the Element of an allocation Then
202780af0b9eSLuke Drummond // sets type, type_vec_size, field_count and type_kind members in Element with
202880af0b9eSLuke Drummond // the result. Returns true on success, false otherwise
2029b9c1b51eSKate Stone bool RenderScriptRuntime::JITElementPacked(Element &elem,
2030b9c1b51eSKate Stone                                            const lldb::addr_t context,
2031b9c1b51eSKate Stone                                            StackFrame *frame_ptr) {
203215f2bd95SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
203315f2bd95SEwan Crawford 
2034b9c1b51eSKate Stone   if (!elem.element_ptr.isValid()) {
203515f2bd95SEwan Crawford     if (log)
2036b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
203715f2bd95SEwan Crawford     return false;
203815f2bd95SEwan Crawford   }
203915f2bd95SEwan Crawford 
20408b244e21SEwan Crawford   // We want 4 elements from packed data
2041b3f7f69dSAidan Dodds   const uint32_t num_exprs = 4;
2042b9c1b51eSKate Stone   assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) &&
2043b9c1b51eSKate Stone          "Invalid number of expressions");
204415f2bd95SEwan Crawford 
204580af0b9eSLuke Drummond   char expr_bufs[num_exprs][jit_max_expr_size];
204615f2bd95SEwan Crawford   uint64_t results[num_exprs];
204715f2bd95SEwan Crawford 
2048b9c1b51eSKate Stone   for (uint32_t i = 0; i < num_exprs; i++) {
204980af0b9eSLuke Drummond     const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
205080af0b9eSLuke Drummond     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
205180af0b9eSLuke Drummond                            *elem.element_ptr.get());
205280af0b9eSLuke Drummond     if (written < 0) {
205315f2bd95SEwan Crawford       if (log)
2054b3f7f69dSAidan Dodds         log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
205515f2bd95SEwan Crawford       return false;
205680af0b9eSLuke Drummond     } else if (written >= jit_max_expr_size) {
205715f2bd95SEwan Crawford       if (log)
2058b3f7f69dSAidan Dodds         log->Printf("%s - expression too long.", __FUNCTION__);
205915f2bd95SEwan Crawford       return false;
206015f2bd95SEwan Crawford     }
206115f2bd95SEwan Crawford 
206215f2bd95SEwan Crawford     // Perform expression evaluation
206380af0b9eSLuke Drummond     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
206415f2bd95SEwan Crawford       return false;
206515f2bd95SEwan Crawford   }
206615f2bd95SEwan Crawford 
206715f2bd95SEwan Crawford   // Assign results to allocation members
20688b244e21SEwan Crawford   elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
2069b9c1b51eSKate Stone   elem.type_kind =
2070b9c1b51eSKate Stone       static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
20718b244e21SEwan Crawford   elem.type_vec_size = static_cast<uint32_t>(results[2]);
20728b244e21SEwan Crawford   elem.field_count = static_cast<uint32_t>(results[3]);
207315f2bd95SEwan Crawford 
207415f2bd95SEwan Crawford   if (log)
2075b9c1b51eSKate Stone     log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32
2076b9c1b51eSKate Stone                 ", vector size %" PRIu32 ", field count %" PRIu32,
2077b9c1b51eSKate Stone                 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
2078b9c1b51eSKate Stone                 *elem.type_vec_size.get(), *elem.field_count.get());
20798b244e21SEwan Crawford 
2080b9c1b51eSKate Stone   // If this Element has subelements then JIT rsaElementGetSubElements() for
2081b9c1b51eSKate Stone   // details about its fields
20828b244e21SEwan Crawford   if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
20838b244e21SEwan Crawford     return false;
20848b244e21SEwan Crawford 
20858b244e21SEwan Crawford   return true;
20868b244e21SEwan Crawford }
20878b244e21SEwan Crawford 
2088b9c1b51eSKate Stone // JITs the RS runtime for information about the subelements/fields of a struct
208980af0b9eSLuke Drummond // allocation This is necessary for infering the struct type so we can pretty
209080af0b9eSLuke Drummond // print the allocation's contents. Returns true on success, false otherwise
2091b9c1b51eSKate Stone bool RenderScriptRuntime::JITSubelements(Element &elem,
2092b9c1b51eSKate Stone                                          const lldb::addr_t context,
2093b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
20948b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
20958b244e21SEwan Crawford 
2096b9c1b51eSKate Stone   if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
20978b244e21SEwan Crawford     if (log)
2098b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
20998b244e21SEwan Crawford     return false;
21008b244e21SEwan Crawford   }
21018b244e21SEwan Crawford 
21028b244e21SEwan Crawford   const short num_exprs = 3;
2103b9c1b51eSKate Stone   assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) &&
2104b9c1b51eSKate Stone          "Invalid number of expressions");
21058b244e21SEwan Crawford 
2106ea0636b5SEwan Crawford   char expr_buffer[jit_max_expr_size];
21078b244e21SEwan Crawford   uint64_t results;
21088b244e21SEwan Crawford 
21098b244e21SEwan Crawford   // Iterate over struct fields.
21108b244e21SEwan Crawford   const uint32_t field_count = *elem.field_count.get();
2111b9c1b51eSKate Stone   for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
21128b244e21SEwan Crawford     Element child;
2113b9c1b51eSKate Stone     for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
211480af0b9eSLuke Drummond       const char *fmt_str =
2115b9c1b51eSKate Stone           JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
211680af0b9eSLuke Drummond       int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
211736d783ebSDavid Gross                              context, field_count, field_count, field_count,
211880af0b9eSLuke Drummond                              *elem.element_ptr.get(), field_count, field_index);
211980af0b9eSLuke Drummond       if (written < 0) {
21208b244e21SEwan Crawford         if (log)
2121b3f7f69dSAidan Dodds           log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
21228b244e21SEwan Crawford         return false;
212380af0b9eSLuke Drummond       } else if (written >= jit_max_expr_size) {
21248b244e21SEwan Crawford         if (log)
2125b3f7f69dSAidan Dodds           log->Printf("%s - expression too long.", __FUNCTION__);
21268b244e21SEwan Crawford         return false;
21278b244e21SEwan Crawford       }
21288b244e21SEwan Crawford 
21298b244e21SEwan Crawford       // Perform expression evaluation
21308b244e21SEwan Crawford       if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
21318b244e21SEwan Crawford         return false;
21328b244e21SEwan Crawford 
21338b244e21SEwan Crawford       if (log)
2134b3f7f69dSAidan Dodds         log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
21358b244e21SEwan Crawford 
2136b9c1b51eSKate Stone       switch (expr_index) {
21378b244e21SEwan Crawford       case 0: // Element* of child
21388b244e21SEwan Crawford         child.element_ptr = static_cast<addr_t>(results);
21398b244e21SEwan Crawford         break;
21408b244e21SEwan Crawford       case 1: // Name of child
21418b244e21SEwan Crawford       {
21428b244e21SEwan Crawford         lldb::addr_t address = static_cast<addr_t>(results);
214397206d57SZachary Turner         Status err;
21448b244e21SEwan Crawford         std::string name;
21458b244e21SEwan Crawford         GetProcess()->ReadCStringFromMemory(address, name, err);
21468b244e21SEwan Crawford         if (!err.Fail())
21478b244e21SEwan Crawford           child.type_name = ConstString(name);
2148b9c1b51eSKate Stone         else {
21498b244e21SEwan Crawford           if (log)
2150b9c1b51eSKate Stone             log->Printf("%s - warning: Couldn't read field name.",
2151b9c1b51eSKate Stone                         __FUNCTION__);
21528b244e21SEwan Crawford         }
21538b244e21SEwan Crawford         break;
21548b244e21SEwan Crawford       }
21558b244e21SEwan Crawford       case 2: // Array size of child
21568b244e21SEwan Crawford         child.array_size = static_cast<uint32_t>(results);
21578b244e21SEwan Crawford         break;
21588b244e21SEwan Crawford       }
21598b244e21SEwan Crawford     }
21608b244e21SEwan Crawford 
21618b244e21SEwan Crawford     // We need to recursively JIT each Element field of the struct since
21628b244e21SEwan Crawford     // structs can be nested inside structs.
21638b244e21SEwan Crawford     if (!JITElementPacked(child, context, frame_ptr))
21648b244e21SEwan Crawford       return false;
21658b244e21SEwan Crawford     elem.children.push_back(child);
21668b244e21SEwan Crawford   }
21678b244e21SEwan Crawford 
2168b9c1b51eSKate Stone   // Try to infer the name of the struct type so we can pretty print the
2169b9c1b51eSKate Stone   // allocation contents.
21708b244e21SEwan Crawford   FindStructTypeName(elem, frame_ptr);
217115f2bd95SEwan Crawford 
217215f2bd95SEwan Crawford   return true;
217315f2bd95SEwan Crawford }
217415f2bd95SEwan Crawford 
2175a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
2176b9c1b51eSKate Stone // The `elem_size` parameter represents the size of a single element, including
217780af0b9eSLuke Drummond // padding. Which is needed as an offset from the last element pointer. Using
217880af0b9eSLuke Drummond // this offset minus the starting address we can calculate the size of the
217980af0b9eSLuke Drummond // allocation. Returns true on success, false otherwise
218080af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
2181b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
2182a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2183a0f08674SEwan Crawford 
218480af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
218580af0b9eSLuke Drummond       !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
2186a0f08674SEwan Crawford     if (log)
2187b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2188a0f08674SEwan Crawford     return false;
2189a0f08674SEwan Crawford   }
2190a0f08674SEwan Crawford 
2191a0f08674SEwan Crawford   // Find dimensions
219280af0b9eSLuke Drummond   uint32_t dim_x = alloc->dimension.get()->dim_1;
219380af0b9eSLuke Drummond   uint32_t dim_y = alloc->dimension.get()->dim_2;
219480af0b9eSLuke Drummond   uint32_t dim_z = alloc->dimension.get()->dim_3;
2195a0f08674SEwan Crawford 
2196b9c1b51eSKate Stone   // Our plan of jitting the last element address doesn't seem to work for
219780af0b9eSLuke Drummond   // struct Allocations` Instead try to infer the size ourselves without any
219880af0b9eSLuke Drummond   // inter element padding.
219980af0b9eSLuke Drummond   if (alloc->element.children.size() > 0) {
2200b9c1b51eSKate Stone     if (dim_x == 0)
2201b9c1b51eSKate Stone       dim_x = 1;
2202b9c1b51eSKate Stone     if (dim_y == 0)
2203b9c1b51eSKate Stone       dim_y = 1;
2204b9c1b51eSKate Stone     if (dim_z == 0)
2205b9c1b51eSKate Stone       dim_z = 1;
22068b244e21SEwan Crawford 
220780af0b9eSLuke Drummond     alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
22088b244e21SEwan Crawford 
22098b244e21SEwan Crawford     if (log)
2210b9c1b51eSKate Stone       log->Printf("%s - inferred size of struct allocation %" PRIu32 ".",
221180af0b9eSLuke Drummond                   __FUNCTION__, *alloc->size.get());
22128b244e21SEwan Crawford     return true;
22138b244e21SEwan Crawford   }
22148b244e21SEwan Crawford 
221580af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
221680af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
22178b244e21SEwan Crawford 
2218a0f08674SEwan Crawford   // Calculate last element
2219a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 0 : dim_x - 1;
2220a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 0 : dim_y - 1;
2221a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 0 : dim_z - 1;
2222a0f08674SEwan Crawford 
222380af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
222480af0b9eSLuke Drummond                          *alloc->address.get(), dim_x, dim_y, dim_z);
222580af0b9eSLuke Drummond   if (written < 0) {
2226a0f08674SEwan Crawford     if (log)
2227b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2228a0f08674SEwan Crawford     return false;
222980af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
2230a0f08674SEwan Crawford     if (log)
2231b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
2232a0f08674SEwan Crawford     return false;
2233a0f08674SEwan Crawford   }
2234a0f08674SEwan Crawford 
2235a0f08674SEwan Crawford   uint64_t result = 0;
223680af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2237a0f08674SEwan Crawford     return false;
2238a0f08674SEwan Crawford 
2239a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2240a0f08674SEwan Crawford   // Find pointer to last element and add on size of an element
224180af0b9eSLuke Drummond   alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
224280af0b9eSLuke Drummond                 *alloc->element.datum_size.get();
2243a0f08674SEwan Crawford 
2244a0f08674SEwan Crawford   return true;
2245a0f08674SEwan Crawford }
2246a0f08674SEwan Crawford 
2247b9c1b51eSKate Stone // JITs the RS runtime for information about the stride between rows in the
224880af0b9eSLuke Drummond // allocation. This is done to detect padding, since allocated memory is 16-byte
224980af0b9eSLuke Drummond // aligned.
2250a0f08674SEwan Crawford // Returns true on success, false otherwise
225180af0b9eSLuke Drummond bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
2252b9c1b51eSKate Stone                                               StackFrame *frame_ptr) {
2253a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2254a0f08674SEwan Crawford 
225580af0b9eSLuke Drummond   if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
2256a0f08674SEwan Crawford     if (log)
2257b3f7f69dSAidan Dodds       log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2258a0f08674SEwan Crawford     return false;
2259a0f08674SEwan Crawford   }
2260a0f08674SEwan Crawford 
226180af0b9eSLuke Drummond   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
226280af0b9eSLuke Drummond   char expr_buf[jit_max_expr_size];
2263a0f08674SEwan Crawford 
226480af0b9eSLuke Drummond   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
226580af0b9eSLuke Drummond                          *alloc->address.get(), 0, 1, 0);
226680af0b9eSLuke Drummond   if (written < 0) {
2267a0f08674SEwan Crawford     if (log)
2268b3f7f69dSAidan Dodds       log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2269a0f08674SEwan Crawford     return false;
227080af0b9eSLuke Drummond   } else if (written >= jit_max_expr_size) {
2271a0f08674SEwan Crawford     if (log)
2272b3f7f69dSAidan Dodds       log->Printf("%s - expression too long.", __FUNCTION__);
2273a0f08674SEwan Crawford     return false;
2274a0f08674SEwan Crawford   }
2275a0f08674SEwan Crawford 
2276a0f08674SEwan Crawford   uint64_t result = 0;
227780af0b9eSLuke Drummond   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2278a0f08674SEwan Crawford     return false;
2279a0f08674SEwan Crawford 
2280a0f08674SEwan Crawford   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
228180af0b9eSLuke Drummond   alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
2282a0f08674SEwan Crawford 
2283a0f08674SEwan Crawford   return true;
2284a0f08674SEwan Crawford }
2285a0f08674SEwan Crawford 
228615f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
228780af0b9eSLuke Drummond bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2288b9c1b51eSKate Stone                                             StackFrame *frame_ptr) {
228915f2bd95SEwan Crawford   // GetOffsetPointer()
229080af0b9eSLuke Drummond   if (!JITDataPointer(alloc, frame_ptr))
229115f2bd95SEwan Crawford     return false;
229215f2bd95SEwan Crawford 
229315f2bd95SEwan Crawford   // rsaAllocationGetType()
229480af0b9eSLuke Drummond   if (!JITTypePointer(alloc, frame_ptr))
229515f2bd95SEwan Crawford     return false;
229615f2bd95SEwan Crawford 
229715f2bd95SEwan Crawford   // rsaTypeGetNativeData()
229880af0b9eSLuke Drummond   if (!JITTypePacked(alloc, frame_ptr))
229915f2bd95SEwan Crawford     return false;
230015f2bd95SEwan Crawford 
230115f2bd95SEwan Crawford   // rsaElementGetNativeData()
230280af0b9eSLuke Drummond   if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
230315f2bd95SEwan Crawford     return false;
230415f2bd95SEwan Crawford 
23058b244e21SEwan Crawford   // Sets the datum_size member in Element
230680af0b9eSLuke Drummond   SetElementSize(alloc->element);
23078b244e21SEwan Crawford 
230855232f09SEwan Crawford   // Use GetOffsetPointer() to infer size of the allocation
230980af0b9eSLuke Drummond   if (!JITAllocationSize(alloc, frame_ptr))
231055232f09SEwan Crawford     return false;
231155232f09SEwan Crawford 
231255232f09SEwan Crawford   return true;
231355232f09SEwan Crawford }
231455232f09SEwan Crawford 
2315b9c1b51eSKate Stone // Function attempts to set the type_name member of the paramaterised Element
2316b9c1b51eSKate Stone // object.
23178b244e21SEwan Crawford // This string should be the name of the struct type the Element represents.
23188b244e21SEwan Crawford // We need this string for pretty printing the Element to users.
2319b9c1b51eSKate Stone void RenderScriptRuntime::FindStructTypeName(Element &elem,
2320b9c1b51eSKate Stone                                              StackFrame *frame_ptr) {
23218b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
23228b244e21SEwan Crawford 
23238b244e21SEwan Crawford   if (!elem.type_name.IsEmpty()) // Name already set
23248b244e21SEwan Crawford     return;
23258b244e21SEwan Crawford   else
2326b9c1b51eSKate Stone     elem.type_name = Element::GetFallbackStructName(); // Default type name if
2327b9c1b51eSKate Stone                                                        // we don't succeed
23288b244e21SEwan Crawford 
23298b244e21SEwan Crawford   // Find all the global variables from the script rs modules
233080af0b9eSLuke Drummond   VariableList var_list;
23318b244e21SEwan Crawford   for (auto module_sp : m_rsmodules)
233295eae423SZachary Turner     module_sp->m_module->FindGlobalVariables(
233380af0b9eSLuke Drummond         RegularExpression(llvm::StringRef(".")), true, UINT32_MAX, var_list);
23348b244e21SEwan Crawford 
2335b9c1b51eSKate Stone   // Iterate over all the global variables looking for one with a matching type
2336b9c1b51eSKate Stone   // to the Element.
2337b9c1b51eSKate Stone   // We make the assumption a match exists since there needs to be a global
233880af0b9eSLuke Drummond   // variable to reflect the struct type back into java host code.
233980af0b9eSLuke Drummond   for (uint32_t i = 0; i < var_list.GetSize(); ++i) {
234080af0b9eSLuke Drummond     const VariableSP var_sp(var_list.GetVariableAtIndex(i));
23418b244e21SEwan Crawford     if (!var_sp)
23428b244e21SEwan Crawford       continue;
23438b244e21SEwan Crawford 
23448b244e21SEwan Crawford     ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
23458b244e21SEwan Crawford     if (!valobj_sp)
23468b244e21SEwan Crawford       continue;
23478b244e21SEwan Crawford 
23488b244e21SEwan Crawford     // Find the number of variable fields.
2349b9c1b51eSKate Stone     // If it has no fields, or more fields than our Element, then it can't be
2350b9c1b51eSKate Stone     // the struct we're looking for.
2351b9c1b51eSKate Stone     // Don't check for equality since RS can add extra struct members for
2352b9c1b51eSKate Stone     // padding.
23538b244e21SEwan Crawford     size_t num_children = valobj_sp->GetNumChildren();
23548b244e21SEwan Crawford     if (num_children > elem.children.size() || num_children == 0)
23558b244e21SEwan Crawford       continue;
23568b244e21SEwan Crawford 
23578b244e21SEwan Crawford     // Iterate over children looking for members with matching field names.
23588b244e21SEwan Crawford     // If all the field names match, this is likely the struct we want.
2359b9c1b51eSKate Stone     //   TODO: This could be made more robust by also checking children data
2360b9c1b51eSKate Stone     //   sizes, or array size
23618b244e21SEwan Crawford     bool found = true;
236280af0b9eSLuke Drummond     for (size_t i = 0; i < num_children; ++i) {
236380af0b9eSLuke Drummond       ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
236480af0b9eSLuke Drummond       if (!child || (child->GetName() != elem.children[i].type_name)) {
23658b244e21SEwan Crawford         found = false;
23668b244e21SEwan Crawford         break;
23678b244e21SEwan Crawford       }
23688b244e21SEwan Crawford     }
23698b244e21SEwan Crawford 
2370b9c1b51eSKate Stone     // RS can add extra struct members for padding in the format
2371b9c1b51eSKate Stone     // '#rs_padding_[0-9]+'
2372b9c1b51eSKate Stone     if (found && num_children < elem.children.size()) {
2373b3f7f69dSAidan Dodds       const uint32_t size_diff = elem.children.size() - num_children;
23748b244e21SEwan Crawford       if (log)
2375b9c1b51eSKate Stone         log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2376b9c1b51eSKate Stone                     size_diff);
23778b244e21SEwan Crawford 
237880af0b9eSLuke Drummond       for (uint32_t i = 0; i < size_diff; ++i) {
237980af0b9eSLuke Drummond         const ConstString &name = elem.children[num_children + i].type_name;
23808b244e21SEwan Crawford         if (strcmp(name.AsCString(), "#rs_padding") < 0)
23818b244e21SEwan Crawford           found = false;
23828b244e21SEwan Crawford       }
23838b244e21SEwan Crawford     }
23848b244e21SEwan Crawford 
238580af0b9eSLuke Drummond     // We've found a global variable with matching type
2386b9c1b51eSKate Stone     if (found) {
23878b244e21SEwan Crawford       // Dereference since our Element type isn't a pointer.
2388b9c1b51eSKate Stone       if (valobj_sp->IsPointerType()) {
238997206d57SZachary Turner         Status err;
23908b244e21SEwan Crawford         ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
23918b244e21SEwan Crawford         if (!err.Fail())
23928b244e21SEwan Crawford           valobj_sp = deref_valobj;
23938b244e21SEwan Crawford       }
23948b244e21SEwan Crawford 
23958b244e21SEwan Crawford       // Save name of variable in Element.
23968b244e21SEwan Crawford       elem.type_name = valobj_sp->GetTypeName();
23978b244e21SEwan Crawford       if (log)
2398b9c1b51eSKate Stone         log->Printf("%s - element name set to %s", __FUNCTION__,
2399b9c1b51eSKate Stone                     elem.type_name.AsCString());
24008b244e21SEwan Crawford 
24018b244e21SEwan Crawford       return;
24028b244e21SEwan Crawford     }
24038b244e21SEwan Crawford   }
24048b244e21SEwan Crawford }
24058b244e21SEwan Crawford 
2406b9c1b51eSKate Stone // Function sets the datum_size member of Element. Representing the size of a
2407b9c1b51eSKate Stone // single instance including padding.
24088b244e21SEwan Crawford // Assumes the relevant allocation information has already been jitted.
2409b9c1b51eSKate Stone void RenderScriptRuntime::SetElementSize(Element &elem) {
24108b244e21SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
24118b244e21SEwan Crawford   const Element::DataType type = *elem.type.get();
2412b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2413b9c1b51eSKate Stone          "Invalid allocation type");
241455232f09SEwan Crawford 
2415b3f7f69dSAidan Dodds   const uint32_t vec_size = *elem.type_vec_size.get();
2416b3f7f69dSAidan Dodds   uint32_t data_size = 0;
2417b3f7f69dSAidan Dodds   uint32_t padding = 0;
241855232f09SEwan Crawford 
24198b244e21SEwan Crawford   // Element is of a struct type, calculate size recursively.
2420b9c1b51eSKate Stone   if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2421b9c1b51eSKate Stone     for (Element &child : elem.children) {
24228b244e21SEwan Crawford       SetElementSize(child);
2423b9c1b51eSKate Stone       const uint32_t array_size =
2424b9c1b51eSKate Stone           child.array_size.isValid() ? *child.array_size.get() : 1;
24258b244e21SEwan Crawford       data_size += *child.datum_size.get() * array_size;
24268b244e21SEwan Crawford     }
24278b244e21SEwan Crawford   }
2428b3f7f69dSAidan Dodds   // These have been packed already
2429b3f7f69dSAidan Dodds   else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2430b3f7f69dSAidan Dodds            type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2431b9c1b51eSKate Stone            type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
24322e920715SEwan Crawford     data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2433b9c1b51eSKate Stone   } else if (type < Element::RS_TYPE_ELEMENT) {
2434b9c1b51eSKate Stone     data_size =
2435b9c1b51eSKate Stone         vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
24362e920715SEwan Crawford     if (vec_size == 3)
24372e920715SEwan Crawford       padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2438b9c1b51eSKate Stone   } else
2439b9c1b51eSKate Stone     data_size =
2440b9c1b51eSKate Stone         GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
24418b244e21SEwan Crawford 
24428b244e21SEwan Crawford   elem.padding = padding;
24438b244e21SEwan Crawford   elem.datum_size = data_size + padding;
24448b244e21SEwan Crawford   if (log)
2445b9c1b51eSKate Stone     log->Printf("%s - element size set to %" PRIu32, __FUNCTION__,
2446b9c1b51eSKate Stone                 data_size + padding);
244755232f09SEwan Crawford }
244855232f09SEwan Crawford 
2449b9c1b51eSKate Stone // Given an allocation, this function copies the allocation contents from device
2450b9c1b51eSKate Stone // into a buffer on the heap.
245155232f09SEwan Crawford // Returning a shared pointer to the buffer containing the data.
245255232f09SEwan Crawford std::shared_ptr<uint8_t>
245380af0b9eSLuke Drummond RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2454b9c1b51eSKate Stone                                        StackFrame *frame_ptr) {
245555232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
245655232f09SEwan Crawford 
245755232f09SEwan Crawford   // JIT all the allocation details
245880af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
245955232f09SEwan Crawford     if (log)
2460b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info",
2461b9c1b51eSKate Stone                   __FUNCTION__);
246255232f09SEwan Crawford 
246380af0b9eSLuke Drummond     if (!RefreshAllocation(alloc, frame_ptr)) {
246455232f09SEwan Crawford       if (log)
2465b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
246655232f09SEwan Crawford       return nullptr;
246755232f09SEwan Crawford     }
246855232f09SEwan Crawford   }
246955232f09SEwan Crawford 
247080af0b9eSLuke Drummond   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
247180af0b9eSLuke Drummond          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
247280af0b9eSLuke Drummond          "Allocation information not available");
247355232f09SEwan Crawford 
247455232f09SEwan Crawford   // Allocate a buffer to copy data into
247580af0b9eSLuke Drummond   const uint32_t size = *alloc->size.get();
247655232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2477b9c1b51eSKate Stone   if (!buffer) {
247855232f09SEwan Crawford     if (log)
2479b9c1b51eSKate Stone       log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer",
2480b9c1b51eSKate Stone                   __FUNCTION__, size);
248155232f09SEwan Crawford     return nullptr;
248255232f09SEwan Crawford   }
248355232f09SEwan Crawford 
248455232f09SEwan Crawford   // Read the inferior memory
248597206d57SZachary Turner   Status err;
248680af0b9eSLuke Drummond   lldb::addr_t data_ptr = *alloc->data_ptr.get();
248780af0b9eSLuke Drummond   GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
248880af0b9eSLuke Drummond   if (err.Fail()) {
248955232f09SEwan Crawford     if (log)
2490b9c1b51eSKate Stone       log->Printf("%s - '%s' Couldn't read %" PRIu32
2491b9c1b51eSKate Stone                   " bytes of allocation data from 0x%" PRIx64,
249280af0b9eSLuke Drummond                   __FUNCTION__, err.AsCString(), size, data_ptr);
249355232f09SEwan Crawford     return nullptr;
249455232f09SEwan Crawford   }
249555232f09SEwan Crawford 
249655232f09SEwan Crawford   return buffer;
249755232f09SEwan Crawford }
249855232f09SEwan Crawford 
249955232f09SEwan Crawford // Function copies data from a binary file into an allocation.
2500b9c1b51eSKate Stone // There is a header at the start of the file, FileHeader, before the data
2501b9c1b51eSKate Stone // content itself.
2502b9c1b51eSKate Stone // Information from this header is used to display warnings to the user about
2503b9c1b51eSKate Stone // incompatibilities
2504b9c1b51eSKate Stone bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
250580af0b9eSLuke Drummond                                          const char *path,
2506b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
250755232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
250855232f09SEwan Crawford 
250955232f09SEwan Crawford   // Find allocation with the given id
251055232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
251155232f09SEwan Crawford   if (!alloc)
251255232f09SEwan Crawford     return false;
251355232f09SEwan Crawford 
251455232f09SEwan Crawford   if (log)
2515b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2516b9c1b51eSKate Stone                 *alloc->address.get());
251755232f09SEwan Crawford 
251855232f09SEwan Crawford   // JIT all the allocation details
251980af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
252055232f09SEwan Crawford     if (log)
2521b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2522b9c1b51eSKate Stone                   __FUNCTION__);
252355232f09SEwan Crawford 
2524b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
252555232f09SEwan Crawford       if (log)
2526b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
25274cfc9198SSylvestre Ledru       return false;
252855232f09SEwan Crawford     }
252955232f09SEwan Crawford   }
253055232f09SEwan Crawford 
2531b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2532b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2533b9c1b51eSKate Stone          alloc->element.datum_size.isValid() &&
2534b9c1b51eSKate Stone          "Allocation information not available");
253555232f09SEwan Crawford 
253655232f09SEwan Crawford   // Check we can read from file
253780af0b9eSLuke Drummond   FileSpec file(path, true);
2538b9c1b51eSKate Stone   if (!file.Exists()) {
253980af0b9eSLuke Drummond     strm.Printf("Error: File %s does not exist", path);
254055232f09SEwan Crawford     strm.EOL();
254155232f09SEwan Crawford     return false;
254255232f09SEwan Crawford   }
254355232f09SEwan Crawford 
2544b9c1b51eSKate Stone   if (!file.Readable()) {
254580af0b9eSLuke Drummond     strm.Printf("Error: File %s does not have readable permissions", path);
254655232f09SEwan Crawford     strm.EOL();
254755232f09SEwan Crawford     return false;
254855232f09SEwan Crawford   }
254955232f09SEwan Crawford 
255055232f09SEwan Crawford   // Read file into data buffer
25517f6a7a37SZachary Turner   auto data_sp = DataBufferLLVM::CreateFromPath(file.GetPath());
255255232f09SEwan Crawford 
255355232f09SEwan Crawford   // Cast start of buffer to FileHeader and use pointer to read metadata
255480af0b9eSLuke Drummond   void *file_buf = data_sp->GetBytes();
255580af0b9eSLuke Drummond   if (file_buf == nullptr ||
2556b9c1b51eSKate Stone       data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2557b9c1b51eSKate Stone                                 sizeof(AllocationDetails::ElementHeader))) {
255880af0b9eSLuke Drummond     strm.Printf("Error: File %s does not contain enough data for header", path);
255926e52a70SEwan Crawford     strm.EOL();
256026e52a70SEwan Crawford     return false;
256126e52a70SEwan Crawford   }
2562b9c1b51eSKate Stone   const AllocationDetails::FileHeader *file_header =
256380af0b9eSLuke Drummond       static_cast<AllocationDetails::FileHeader *>(file_buf);
256455232f09SEwan Crawford 
256526e52a70SEwan Crawford   // Check file starts with ascii characters "RSAD"
2566b9c1b51eSKate Stone   if (memcmp(file_header->ident, "RSAD", 4)) {
2567b9c1b51eSKate Stone     strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2568b9c1b51eSKate Stone                 "dump. Are you sure this is the correct file?");
256926e52a70SEwan Crawford     strm.EOL();
257026e52a70SEwan Crawford     return false;
257126e52a70SEwan Crawford   }
257226e52a70SEwan Crawford 
257326e52a70SEwan Crawford   // Look at the type of the root element in the header
257480af0b9eSLuke Drummond   AllocationDetails::ElementHeader root_el_hdr;
257580af0b9eSLuke Drummond   memcpy(&root_el_hdr, static_cast<uint8_t *>(file_buf) +
2576b9c1b51eSKate Stone                            sizeof(AllocationDetails::FileHeader),
257726e52a70SEwan Crawford          sizeof(AllocationDetails::ElementHeader));
257855232f09SEwan Crawford 
257955232f09SEwan Crawford   if (log)
2580b9c1b51eSKate Stone     log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32,
258180af0b9eSLuke Drummond                 __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
258255232f09SEwan Crawford 
2583b9c1b51eSKate Stone   // Check if the target allocation and file both have the same number of bytes
2584b9c1b51eSKate Stone   // for an Element
258580af0b9eSLuke Drummond   if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2586b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2587b9c1b51eSKate Stone                 " bytes, allocation %" PRIu32 " bytes",
258880af0b9eSLuke Drummond                 root_el_hdr.element_size, *alloc->element.datum_size.get());
258955232f09SEwan Crawford     strm.EOL();
259055232f09SEwan Crawford   }
259155232f09SEwan Crawford 
259226e52a70SEwan Crawford   // Check if the target allocation and file both have the same type
2593b3f7f69dSAidan Dodds   const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
259480af0b9eSLuke Drummond   const uint32_t file_type = root_el_hdr.type;
259526e52a70SEwan Crawford 
2596b9c1b51eSKate Stone   if (file_type > Element::RS_TYPE_FONT) {
259726e52a70SEwan Crawford     strm.Printf("Warning: File has unknown allocation type");
259826e52a70SEwan Crawford     strm.EOL();
2599b9c1b51eSKate Stone   } else if (alloc_type != file_type) {
2600b9c1b51eSKate Stone     // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2601b9c1b51eSKate Stone     // array
260280af0b9eSLuke Drummond     uint32_t target_type_name_idx = alloc_type;
260380af0b9eSLuke Drummond     uint32_t head_type_name_idx = file_type;
2604b9c1b51eSKate Stone     if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2605b9c1b51eSKate Stone         alloc_type <= Element::RS_TYPE_FONT)
260680af0b9eSLuke Drummond       target_type_name_idx = static_cast<Element::DataType>(
2607b9c1b51eSKate Stone           (alloc_type - Element::RS_TYPE_ELEMENT) +
2608b3f7f69dSAidan Dodds           Element::RS_TYPE_MATRIX_2X2 + 1);
26092e920715SEwan Crawford 
2610b9c1b51eSKate Stone     if (file_type >= Element::RS_TYPE_ELEMENT &&
2611b9c1b51eSKate Stone         file_type <= Element::RS_TYPE_FONT)
261280af0b9eSLuke Drummond       head_type_name_idx = static_cast<Element::DataType>(
2613b9c1b51eSKate Stone           (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2614b9c1b51eSKate Stone           1);
26152e920715SEwan Crawford 
261680af0b9eSLuke Drummond     const char *head_type_name =
261780af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
261880af0b9eSLuke Drummond     const char *target_type_name =
261980af0b9eSLuke Drummond         AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
262055232f09SEwan Crawford 
2621b9c1b51eSKate Stone     strm.Printf(
2622b9c1b51eSKate Stone         "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
262380af0b9eSLuke Drummond         head_type_name, target_type_name);
262455232f09SEwan Crawford     strm.EOL();
262555232f09SEwan Crawford   }
262655232f09SEwan Crawford 
262726e52a70SEwan Crawford   // Advance buffer past header
262880af0b9eSLuke Drummond   file_buf = static_cast<uint8_t *>(file_buf) + file_header->hdr_size;
262926e52a70SEwan Crawford 
263055232f09SEwan Crawford   // Calculate size of allocation data in file
263180af0b9eSLuke Drummond   size_t size = data_sp->GetByteSize() - file_header->hdr_size;
263255232f09SEwan Crawford 
263355232f09SEwan Crawford   // Check if the target allocation and file both have the same total data size.
2634b3f7f69dSAidan Dodds   const uint32_t alloc_size = *alloc->size.get();
263580af0b9eSLuke Drummond   if (alloc_size != size) {
2636b9c1b51eSKate Stone     strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2637b9c1b51eSKate Stone                 " bytes, allocation 0x%" PRIx32 " bytes",
263880af0b9eSLuke Drummond                 (uint64_t)size, alloc_size);
263955232f09SEwan Crawford     strm.EOL();
264080af0b9eSLuke Drummond     // Set length to copy to minimum
264180af0b9eSLuke Drummond     size = alloc_size < size ? alloc_size : size;
264255232f09SEwan Crawford   }
264355232f09SEwan Crawford 
264455232f09SEwan Crawford   // Copy file data from our buffer into the target allocation.
264555232f09SEwan Crawford   lldb::addr_t alloc_data = *alloc->data_ptr.get();
264697206d57SZachary Turner   Status err;
264780af0b9eSLuke Drummond   size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
264880af0b9eSLuke Drummond   if (!err.Success() || written != size) {
264980af0b9eSLuke Drummond     strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
265055232f09SEwan Crawford     strm.EOL();
265155232f09SEwan Crawford     return false;
265255232f09SEwan Crawford   }
265355232f09SEwan Crawford 
265480af0b9eSLuke Drummond   strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2655b9c1b51eSKate Stone               alloc->id);
265655232f09SEwan Crawford   strm.EOL();
265755232f09SEwan Crawford 
265855232f09SEwan Crawford   return true;
265955232f09SEwan Crawford }
266055232f09SEwan Crawford 
2661b9c1b51eSKate Stone // Function takes as parameters a byte buffer, which will eventually be written
266280af0b9eSLuke Drummond // to file as the element header, an offset into that buffer, and an Element
266380af0b9eSLuke Drummond // that will be saved into the buffer at the parametrised offset.
266426e52a70SEwan Crawford // Return value is the new offset after writing the element into the buffer.
2665b9c1b51eSKate Stone // Elements are saved to the file as the ElementHeader struct followed by
266680af0b9eSLuke Drummond // offsets to the structs of all the element's children.
2667b9c1b51eSKate Stone size_t RenderScriptRuntime::PopulateElementHeaders(
2668b9c1b51eSKate Stone     const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2669b9c1b51eSKate Stone     const Element &elem) {
2670b9c1b51eSKate Stone   // File struct for an element header with all the relevant details copied from
267180af0b9eSLuke Drummond   // elem. We assume members are valid already.
267226e52a70SEwan Crawford   AllocationDetails::ElementHeader elem_header;
267326e52a70SEwan Crawford   elem_header.type = *elem.type.get();
267426e52a70SEwan Crawford   elem_header.kind = *elem.type_kind.get();
267526e52a70SEwan Crawford   elem_header.element_size = *elem.datum_size.get();
267626e52a70SEwan Crawford   elem_header.vector_size = *elem.type_vec_size.get();
2677b9c1b51eSKate Stone   elem_header.array_size =
2678b9c1b51eSKate Stone       elem.array_size.isValid() ? *elem.array_size.get() : 0;
267926e52a70SEwan Crawford   const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
268026e52a70SEwan Crawford 
268126e52a70SEwan Crawford   // Copy struct into buffer and advance offset
2682b9c1b51eSKate Stone   // We assume that header_buffer has been checked for nullptr before this
2683b9c1b51eSKate Stone   // method is called
268426e52a70SEwan Crawford   memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
268526e52a70SEwan Crawford   offset += elem_header_size;
268626e52a70SEwan Crawford 
268726e52a70SEwan Crawford   // Starting offset of child ElementHeader struct
2688b9c1b51eSKate Stone   size_t child_offset =
2689b9c1b51eSKate Stone       offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2690b9c1b51eSKate Stone   for (const RenderScriptRuntime::Element &child : elem.children) {
2691b9c1b51eSKate Stone     // Recursively populate the buffer with the element header structs of
269280af0b9eSLuke Drummond     // children. Then save the offsets where they were set after the parent
269380af0b9eSLuke Drummond     // element header.
269426e52a70SEwan Crawford     memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
269526e52a70SEwan Crawford     offset += sizeof(uint32_t);
269626e52a70SEwan Crawford 
269726e52a70SEwan Crawford     child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
269826e52a70SEwan Crawford   }
269926e52a70SEwan Crawford 
270026e52a70SEwan Crawford   // Zero indicates no more children
270126e52a70SEwan Crawford   memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
270226e52a70SEwan Crawford 
270326e52a70SEwan Crawford   return child_offset;
270426e52a70SEwan Crawford }
270526e52a70SEwan Crawford 
2706b9c1b51eSKate Stone // Given an Element object this function returns the total size needed in the
270780af0b9eSLuke Drummond // file header to store the element's details. Taking into account the size of
270880af0b9eSLuke Drummond // the element header struct, plus the offsets to all the element's children.
2709b9c1b51eSKate Stone // Function is recursive so that the size of all ancestors is taken into
2710b9c1b51eSKate Stone // account.
2711b9c1b51eSKate Stone size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
271280af0b9eSLuke Drummond   // Offsets to children plus zero terminator
271380af0b9eSLuke Drummond   size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
271480af0b9eSLuke Drummond   // Size of header struct with type details
271580af0b9eSLuke Drummond   size += sizeof(AllocationDetails::ElementHeader);
271626e52a70SEwan Crawford 
271726e52a70SEwan Crawford   // Calculate recursively for all descendants
271826e52a70SEwan Crawford   for (const Element &child : elem.children)
271926e52a70SEwan Crawford     size += CalculateElementHeaderSize(child);
272026e52a70SEwan Crawford 
272126e52a70SEwan Crawford   return size;
272226e52a70SEwan Crawford }
272326e52a70SEwan Crawford 
272480af0b9eSLuke Drummond // Function copies allocation contents into a binary file. This file can then be
272580af0b9eSLuke Drummond // loaded later into a different allocation. There is a header, FileHeader,
272680af0b9eSLuke Drummond // before the allocation data containing meta-data.
2727b9c1b51eSKate Stone bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
272880af0b9eSLuke Drummond                                          const char *path,
2729b9c1b51eSKate Stone                                          StackFrame *frame_ptr) {
273055232f09SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
273155232f09SEwan Crawford 
273255232f09SEwan Crawford   // Find allocation with the given id
273355232f09SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
273455232f09SEwan Crawford   if (!alloc)
273555232f09SEwan Crawford     return false;
273655232f09SEwan Crawford 
273755232f09SEwan Crawford   if (log)
2738b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2739b9c1b51eSKate Stone                 *alloc->address.get());
274055232f09SEwan Crawford 
274155232f09SEwan Crawford   // JIT all the allocation details
274280af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
274355232f09SEwan Crawford     if (log)
2744b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
2745b9c1b51eSKate Stone                   __FUNCTION__);
274655232f09SEwan Crawford 
2747b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
274855232f09SEwan Crawford       if (log)
2749b3f7f69dSAidan Dodds         log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
27504cfc9198SSylvestre Ledru       return false;
275155232f09SEwan Crawford     }
275255232f09SEwan Crawford   }
275355232f09SEwan Crawford 
2754b9c1b51eSKate Stone   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2755b9c1b51eSKate Stone          alloc->element.type_vec_size.isValid() &&
2756b9c1b51eSKate Stone          alloc->element.datum_size.get() &&
2757b9c1b51eSKate Stone          alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2758b3f7f69dSAidan Dodds          "Allocation information not available");
275955232f09SEwan Crawford 
276055232f09SEwan Crawford   // Check we can create writable file
276180af0b9eSLuke Drummond   FileSpec file_spec(path, true);
2762b9c1b51eSKate Stone   File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate |
2763b9c1b51eSKate Stone                            File::eOpenOptionTruncate);
2764b9c1b51eSKate Stone   if (!file) {
276580af0b9eSLuke Drummond     strm.Printf("Error: Failed to open '%s' for writing", path);
276655232f09SEwan Crawford     strm.EOL();
276755232f09SEwan Crawford     return false;
276855232f09SEwan Crawford   }
276955232f09SEwan Crawford 
277055232f09SEwan Crawford   // Read allocation into buffer of heap memory
277155232f09SEwan Crawford   const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2772b9c1b51eSKate Stone   if (!buffer) {
277355232f09SEwan Crawford     strm.Printf("Error: Couldn't read allocation data into buffer");
277455232f09SEwan Crawford     strm.EOL();
277555232f09SEwan Crawford     return false;
277655232f09SEwan Crawford   }
277755232f09SEwan Crawford 
277855232f09SEwan Crawford   // Create the file header
277955232f09SEwan Crawford   AllocationDetails::FileHeader head;
2780b3f7f69dSAidan Dodds   memcpy(head.ident, "RSAD", 4);
27812d62328aSEwan Crawford   head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
27822d62328aSEwan Crawford   head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
27832d62328aSEwan Crawford   head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
278426e52a70SEwan Crawford 
278526e52a70SEwan Crawford   const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2786b9c1b51eSKate Stone   assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2787b9c1b51eSKate Stone              UINT16_MAX &&
2788b9c1b51eSKate Stone          "Element header too large");
2789b9c1b51eSKate Stone   head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2790b9c1b51eSKate Stone                                         element_header_size);
279155232f09SEwan Crawford 
279255232f09SEwan Crawford   // Write the file header
279355232f09SEwan Crawford   size_t num_bytes = sizeof(AllocationDetails::FileHeader);
279426e52a70SEwan Crawford   if (log)
2795b9c1b51eSKate Stone     log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2796b9c1b51eSKate Stone                 (uint64_t)num_bytes);
279726e52a70SEwan Crawford 
279897206d57SZachary Turner   Status err = file.Write(&head, num_bytes);
2799b9c1b51eSKate Stone   if (!err.Success()) {
280080af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
280126e52a70SEwan Crawford     strm.EOL();
280226e52a70SEwan Crawford     return false;
280326e52a70SEwan Crawford   }
280426e52a70SEwan Crawford 
280526e52a70SEwan Crawford   // Create the headers describing the element type of the allocation.
2806b9c1b51eSKate Stone   std::shared_ptr<uint8_t> element_header_buffer(
2807b9c1b51eSKate Stone       new uint8_t[element_header_size]);
2808b9c1b51eSKate Stone   if (element_header_buffer == nullptr) {
2809b9c1b51eSKate Stone     strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2810b9c1b51eSKate Stone                 " bytes on the heap",
2811b9c1b51eSKate Stone                 (uint64_t)element_header_size);
281226e52a70SEwan Crawford     strm.EOL();
281326e52a70SEwan Crawford     return false;
281426e52a70SEwan Crawford   }
281526e52a70SEwan Crawford 
281626e52a70SEwan Crawford   PopulateElementHeaders(element_header_buffer, 0, alloc->element);
281726e52a70SEwan Crawford 
281826e52a70SEwan Crawford   // Write headers for allocation element type to file
281926e52a70SEwan Crawford   num_bytes = element_header_size;
282026e52a70SEwan Crawford   if (log)
2821b9c1b51eSKate Stone     log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.",
2822b9c1b51eSKate Stone                 __FUNCTION__, (uint64_t)num_bytes);
282326e52a70SEwan Crawford 
282426e52a70SEwan Crawford   err = file.Write(element_header_buffer.get(), num_bytes);
2825b9c1b51eSKate Stone   if (!err.Success()) {
282680af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
282755232f09SEwan Crawford     strm.EOL();
282855232f09SEwan Crawford     return false;
282955232f09SEwan Crawford   }
283055232f09SEwan Crawford 
283155232f09SEwan Crawford   // Write allocation data to file
283255232f09SEwan Crawford   num_bytes = static_cast<size_t>(*alloc->size.get());
283355232f09SEwan Crawford   if (log)
2834b9c1b51eSKate Stone     log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2835b9c1b51eSKate Stone                 (uint64_t)num_bytes);
283655232f09SEwan Crawford 
283755232f09SEwan Crawford   err = file.Write(buffer.get(), num_bytes);
2838b9c1b51eSKate Stone   if (!err.Success()) {
283980af0b9eSLuke Drummond     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
284055232f09SEwan Crawford     strm.EOL();
284155232f09SEwan Crawford     return false;
284255232f09SEwan Crawford   }
284355232f09SEwan Crawford 
284480af0b9eSLuke Drummond   strm.Printf("Allocation written to file '%s'", path);
284555232f09SEwan Crawford   strm.EOL();
284615f2bd95SEwan Crawford   return true;
284715f2bd95SEwan Crawford }
284815f2bd95SEwan Crawford 
2849b9c1b51eSKate Stone bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
28504640cde1SColin Riley   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
28514640cde1SColin Riley 
2852b9c1b51eSKate Stone   if (module_sp) {
2853b9c1b51eSKate Stone     for (const auto &rs_module : m_rsmodules) {
2854b9c1b51eSKate Stone       if (rs_module->m_module == module_sp) {
28557dc7771cSEwan Crawford         // Check if the user has enabled automatically breaking on
28567dc7771cSEwan Crawford         // all RS kernels.
28577dc7771cSEwan Crawford         if (m_breakAllKernels)
28587dc7771cSEwan Crawford           BreakOnModuleKernels(rs_module);
28597dc7771cSEwan Crawford 
28605ec532a9SColin Riley         return false;
28615ec532a9SColin Riley       }
28627dc7771cSEwan Crawford     }
2863ef20b08fSColin Riley     bool module_loaded = false;
2864b9c1b51eSKate Stone     switch (GetModuleKind(module_sp)) {
2865b9c1b51eSKate Stone     case eModuleKindKernelObj: {
28664640cde1SColin Riley       RSModuleDescriptorSP module_desc;
28674640cde1SColin Riley       module_desc.reset(new RSModuleDescriptor(module_sp));
2868b9c1b51eSKate Stone       if (module_desc->ParseRSInfo()) {
28695ec532a9SColin Riley         m_rsmodules.push_back(module_desc);
287047d64161SLuke Drummond         module_desc->WarnIfVersionMismatch(GetProcess()
287147d64161SLuke Drummond                                                ->GetTarget()
287247d64161SLuke Drummond                                                .GetDebugger()
287347d64161SLuke Drummond                                                .GetAsyncOutputStream()
287447d64161SLuke Drummond                                                .get());
2875ef20b08fSColin Riley         module_loaded = true;
28765ec532a9SColin Riley       }
2877b9c1b51eSKate Stone       if (module_loaded) {
28784640cde1SColin Riley         FixupScriptDetails(module_desc);
28794640cde1SColin Riley       }
2880ef20b08fSColin Riley       break;
2881ef20b08fSColin Riley     }
2882b9c1b51eSKate Stone     case eModuleKindDriver: {
2883b9c1b51eSKate Stone       if (!m_libRSDriver) {
28844640cde1SColin Riley         m_libRSDriver = module_sp;
28854640cde1SColin Riley         LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
28864640cde1SColin Riley       }
28874640cde1SColin Riley       break;
28884640cde1SColin Riley     }
2889b9c1b51eSKate Stone     case eModuleKindImpl: {
289021fed052SAidan Dodds       if (!m_libRSCpuRef) {
28914640cde1SColin Riley         m_libRSCpuRef = module_sp;
289221fed052SAidan Dodds         LoadRuntimeHooks(m_libRSCpuRef, RenderScriptRuntime::eModuleKindImpl);
289321fed052SAidan Dodds       }
28944640cde1SColin Riley       break;
28954640cde1SColin Riley     }
2896b9c1b51eSKate Stone     case eModuleKindLibRS: {
2897b9c1b51eSKate Stone       if (!m_libRS) {
28984640cde1SColin Riley         m_libRS = module_sp;
28994640cde1SColin Riley         static ConstString gDbgPresentStr("gDebuggerPresent");
2900b9c1b51eSKate Stone         const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2901b9c1b51eSKate Stone             gDbgPresentStr, eSymbolTypeData);
2902b9c1b51eSKate Stone         if (debug_present) {
290397206d57SZachary Turner           Status err;
29044640cde1SColin Riley           uint32_t flag = 0x00000001U;
29054640cde1SColin Riley           Target &target = GetProcess()->GetTarget();
2906358cf1eaSGreg Clayton           addr_t addr = debug_present->GetLoadAddress(&target);
290780af0b9eSLuke Drummond           GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
290880af0b9eSLuke Drummond           if (err.Success()) {
29094640cde1SColin Riley             if (log)
2910b9c1b51eSKate Stone               log->Printf("%s - debugger present flag set on debugee.",
2911b9c1b51eSKate Stone                           __FUNCTION__);
29124640cde1SColin Riley 
29134640cde1SColin Riley             m_debuggerPresentFlagged = true;
2914b9c1b51eSKate Stone           } else if (log) {
2915b9c1b51eSKate Stone             log->Printf("%s - error writing debugger present flags '%s' ",
291680af0b9eSLuke Drummond                         __FUNCTION__, err.AsCString());
29174640cde1SColin Riley           }
2918b9c1b51eSKate Stone         } else if (log) {
2919b9c1b51eSKate Stone           log->Printf(
2920b9c1b51eSKate Stone               "%s - error writing debugger present flags - symbol not found",
2921b9c1b51eSKate Stone               __FUNCTION__);
29224640cde1SColin Riley         }
29234640cde1SColin Riley       }
29244640cde1SColin Riley       break;
29254640cde1SColin Riley     }
2926ef20b08fSColin Riley     default:
2927ef20b08fSColin Riley       break;
2928ef20b08fSColin Riley     }
2929ef20b08fSColin Riley     if (module_loaded)
2930ef20b08fSColin Riley       Update();
2931ef20b08fSColin Riley     return module_loaded;
29325ec532a9SColin Riley   }
29335ec532a9SColin Riley   return false;
29345ec532a9SColin Riley }
29355ec532a9SColin Riley 
2936b9c1b51eSKate Stone void RenderScriptRuntime::Update() {
2937b9c1b51eSKate Stone   if (m_rsmodules.size() > 0) {
2938b9c1b51eSKate Stone     if (!m_initiated) {
2939ef20b08fSColin Riley       Initiate();
2940ef20b08fSColin Riley     }
2941ef20b08fSColin Riley   }
2942ef20b08fSColin Riley }
2943ef20b08fSColin Riley 
294447d64161SLuke Drummond void RSModuleDescriptor::WarnIfVersionMismatch(lldb_private::Stream *s) const {
294547d64161SLuke Drummond   if (!s)
294647d64161SLuke Drummond     return;
294747d64161SLuke Drummond 
294847d64161SLuke Drummond   if (m_slang_version.empty() || m_bcc_version.empty()) {
294947d64161SLuke Drummond     s->PutCString("WARNING: Unknown bcc or slang (llvm-rs-cc) version; debug "
295047d64161SLuke Drummond                   "experience may be unreliable");
295147d64161SLuke Drummond     s->EOL();
295247d64161SLuke Drummond   } else if (m_slang_version != m_bcc_version) {
295347d64161SLuke Drummond     s->Printf("WARNING: The debug info emitted by the slang frontend "
295447d64161SLuke Drummond               "(llvm-rs-cc) used to build this module (%s) does not match the "
295547d64161SLuke Drummond               "version of bcc used to generate the debug information (%s). "
295647d64161SLuke Drummond               "This is an unsupported configuration and may result in a poor "
295747d64161SLuke Drummond               "debugging experience; proceed with caution",
295847d64161SLuke Drummond               m_slang_version.c_str(), m_bcc_version.c_str());
295947d64161SLuke Drummond     s->EOL();
296047d64161SLuke Drummond   }
296147d64161SLuke Drummond }
296247d64161SLuke Drummond 
29637f193d69SLuke Drummond bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
29647f193d69SLuke Drummond                                           size_t n_lines) {
29657f193d69SLuke Drummond   // Skip the pragma prototype line
29667f193d69SLuke Drummond   ++lines;
29677f193d69SLuke Drummond   for (; n_lines--; ++lines) {
29687f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
29697f193d69SLuke Drummond     m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
29707f193d69SLuke Drummond   }
29717f193d69SLuke Drummond   return true;
29727f193d69SLuke Drummond }
29737f193d69SLuke Drummond 
29747f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
29757f193d69SLuke Drummond                                                 size_t n_lines) {
29767f193d69SLuke Drummond   // The list of reduction kernels in the `.rs.info` symbol is of the form
29777f193d69SLuke Drummond   // "signature - accumulatordatasize - reduction_name - initializer_name -
29787f193d69SLuke Drummond   // accumulator_name - combiner_name -
29797f193d69SLuke Drummond   // outconverter_name - halter_name"
29807f193d69SLuke Drummond   // Where a function is not explicitly named by the user, or is not generated
29817f193d69SLuke Drummond   // by the compiler, it is named "." so the
29827f193d69SLuke Drummond   // dash separated list should always be 8 items long
29837f193d69SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
29847f193d69SLuke Drummond   // Skip the exportReduceCount line
29857f193d69SLuke Drummond   ++lines;
29867f193d69SLuke Drummond   for (; n_lines--; ++lines) {
29877f193d69SLuke Drummond     llvm::SmallVector<llvm::StringRef, 8> spec;
29887f193d69SLuke Drummond     lines->split(spec, " - ");
29897f193d69SLuke Drummond     if (spec.size() != 8) {
29907f193d69SLuke Drummond       if (spec.size() < 8) {
29917f193d69SLuke Drummond         if (log)
29927f193d69SLuke Drummond           log->Error("Error parsing RenderScript reduction spec. wrong number "
29937f193d69SLuke Drummond                      "of fields");
29947f193d69SLuke Drummond         return false;
29957f193d69SLuke Drummond       } else if (log)
29967f193d69SLuke Drummond         log->Warning("Extraneous members in reduction spec: '%s'",
29977f193d69SLuke Drummond                      lines->str().c_str());
29987f193d69SLuke Drummond     }
29997f193d69SLuke Drummond 
30007f193d69SLuke Drummond     const auto sig_s = spec[0];
30017f193d69SLuke Drummond     uint32_t sig;
30027f193d69SLuke Drummond     if (sig_s.getAsInteger(10, sig)) {
30037f193d69SLuke Drummond       if (log)
30047f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid kernel "
30057f193d69SLuke Drummond                    "signature: '%s'",
30067f193d69SLuke Drummond                    sig_s.str().c_str());
30077f193d69SLuke Drummond       return false;
30087f193d69SLuke Drummond     }
30097f193d69SLuke Drummond 
30107f193d69SLuke Drummond     const auto accum_data_size_s = spec[1];
30117f193d69SLuke Drummond     uint32_t accum_data_size;
30127f193d69SLuke Drummond     if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
30137f193d69SLuke Drummond       if (log)
30147f193d69SLuke Drummond         log->Error("Error parsing Renderscript reduction spec: invalid "
30157f193d69SLuke Drummond                    "accumulator data size %s",
30167f193d69SLuke Drummond                    accum_data_size_s.str().c_str());
30177f193d69SLuke Drummond       return false;
30187f193d69SLuke Drummond     }
30197f193d69SLuke Drummond 
30207f193d69SLuke Drummond     if (log)
30217f193d69SLuke Drummond       log->Printf("Found RenderScript reduction '%s'", spec[2].str().c_str());
30227f193d69SLuke Drummond 
30237f193d69SLuke Drummond     m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
30247f193d69SLuke Drummond                                                  spec[2], spec[3], spec[4],
30257f193d69SLuke Drummond                                                  spec[5], spec[6], spec[7]));
30267f193d69SLuke Drummond   }
30277f193d69SLuke Drummond   return true;
30287f193d69SLuke Drummond }
30297f193d69SLuke Drummond 
303047d64161SLuke Drummond bool RSModuleDescriptor::ParseVersionInfo(llvm::StringRef *lines,
303147d64161SLuke Drummond                                           size_t n_lines) {
303247d64161SLuke Drummond   // Skip the versionInfo line
303347d64161SLuke Drummond   ++lines;
303447d64161SLuke Drummond   for (; n_lines--; ++lines) {
303547d64161SLuke Drummond     // We're only interested in bcc and slang versions, and ignore all other
303647d64161SLuke Drummond     // versionInfo lines
303747d64161SLuke Drummond     const auto kv_pair = lines->split(" - ");
303847d64161SLuke Drummond     if (kv_pair.first == "slang")
303947d64161SLuke Drummond       m_slang_version = kv_pair.second.str();
304047d64161SLuke Drummond     else if (kv_pair.first == "bcc")
304147d64161SLuke Drummond       m_bcc_version = kv_pair.second.str();
304247d64161SLuke Drummond   }
304347d64161SLuke Drummond   return true;
304447d64161SLuke Drummond }
304547d64161SLuke Drummond 
30467f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
30477f193d69SLuke Drummond                                                  size_t n_lines) {
30487f193d69SLuke Drummond   // Skip the exportForeachCount line
30497f193d69SLuke Drummond   ++lines;
30507f193d69SLuke Drummond   for (; n_lines--; ++lines) {
30517f193d69SLuke Drummond     uint32_t slot;
30527f193d69SLuke Drummond     // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
30537f193d69SLuke Drummond     // pair per line
30547f193d69SLuke Drummond     const auto kv_pair = lines->split(" - ");
30557f193d69SLuke Drummond     if (kv_pair.first.getAsInteger(10, slot))
30567f193d69SLuke Drummond       return false;
30577f193d69SLuke Drummond     m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
30587f193d69SLuke Drummond   }
30597f193d69SLuke Drummond   return true;
30607f193d69SLuke Drummond }
30617f193d69SLuke Drummond 
30627f193d69SLuke Drummond bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
30637f193d69SLuke Drummond                                              size_t n_lines) {
30647f193d69SLuke Drummond   // Skip the ExportVarCount line
30657f193d69SLuke Drummond   ++lines;
30667f193d69SLuke Drummond   for (; n_lines--; ++lines)
30677f193d69SLuke Drummond     m_globals.push_back(RSGlobalDescriptor(this, *lines));
30687f193d69SLuke Drummond   return true;
30697f193d69SLuke Drummond }
30705ec532a9SColin Riley 
3071b9c1b51eSKate Stone // The .rs.info symbol in renderscript modules contains a string which needs to
3072b9c1b51eSKate Stone // be parsed.
30735ec532a9SColin Riley // The string is basic and is parsed on a line by line basis.
3074b9c1b51eSKate Stone bool RSModuleDescriptor::ParseRSInfo() {
3075b0be30f7SAidan Dodds   assert(m_module);
30767f193d69SLuke Drummond   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3077b9c1b51eSKate Stone   const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
3078b9c1b51eSKate Stone       ConstString(".rs.info"), eSymbolTypeData);
3079b0be30f7SAidan Dodds   if (!info_sym)
3080b0be30f7SAidan Dodds     return false;
3081b0be30f7SAidan Dodds 
3082358cf1eaSGreg Clayton   const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
3083b0be30f7SAidan Dodds   if (addr == LLDB_INVALID_ADDRESS)
3084b0be30f7SAidan Dodds     return false;
3085b0be30f7SAidan Dodds 
30865ec532a9SColin Riley   const addr_t size = info_sym->GetByteSize();
30875ec532a9SColin Riley   const FileSpec fs = m_module->GetFileSpec();
30885ec532a9SColin Riley 
30897f6a7a37SZachary Turner   auto buffer = DataBufferLLVM::CreateSliceFromPath(fs.GetPath(), size, addr);
30905ec532a9SColin Riley   if (!buffer)
30915ec532a9SColin Riley     return false;
30925ec532a9SColin Riley 
3093b0be30f7SAidan Dodds   // split rs.info. contents into lines
30947f193d69SLuke Drummond   llvm::SmallVector<llvm::StringRef, 128> info_lines;
30955ec532a9SColin Riley   {
30967f193d69SLuke Drummond     const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
30977f193d69SLuke Drummond     raw_rs_info.split(info_lines, '\n');
30987f193d69SLuke Drummond     if (log)
30997f193d69SLuke Drummond       log->Printf("'.rs.info symbol for '%s':\n%s",
31007f193d69SLuke Drummond                   m_module->GetFileSpec().GetCString(),
31017f193d69SLuke Drummond                   raw_rs_info.str().c_str());
3102b0be30f7SAidan Dodds   }
3103b0be30f7SAidan Dodds 
31047f193d69SLuke Drummond   enum {
31057f193d69SLuke Drummond     eExportVar,
31067f193d69SLuke Drummond     eExportForEach,
31077f193d69SLuke Drummond     eExportReduce,
31087f193d69SLuke Drummond     ePragma,
31097f193d69SLuke Drummond     eBuildChecksum,
311047d64161SLuke Drummond     eObjectSlot,
311147d64161SLuke Drummond     eVersionInfo,
31127f193d69SLuke Drummond   };
31137f193d69SLuke Drummond 
3114b3bbcb12SLuke Drummond   const auto rs_info_handler = [](llvm::StringRef name) -> int {
3115b3bbcb12SLuke Drummond     return llvm::StringSwitch<int>(name)
3116b3bbcb12SLuke Drummond         // The number of visible global variables in the script
3117b3bbcb12SLuke Drummond         .Case("exportVarCount", eExportVar)
31187f193d69SLuke Drummond         // The number of RenderScrip `forEach` kernels __attribute__((kernel))
3119b3bbcb12SLuke Drummond         .Case("exportForEachCount", eExportForEach)
3120b3bbcb12SLuke Drummond         // The number of generalreductions: This marked in the script by
3121b3bbcb12SLuke Drummond         // `#pragma reduce()`
3122b3bbcb12SLuke Drummond         .Case("exportReduceCount", eExportReduce)
3123b3bbcb12SLuke Drummond         // Total count of all RenderScript specific `#pragmas` used in the
3124b3bbcb12SLuke Drummond         // script
3125b3bbcb12SLuke Drummond         .Case("pragmaCount", ePragma)
3126b3bbcb12SLuke Drummond         .Case("objectSlotCount", eObjectSlot)
312747d64161SLuke Drummond         .Case("versionInfo", eVersionInfo)
3128b3bbcb12SLuke Drummond         .Default(-1);
3129b3bbcb12SLuke Drummond   };
3130b0be30f7SAidan Dodds 
3131b0be30f7SAidan Dodds   // parse all text lines of .rs.info
3132b9c1b51eSKate Stone   for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
31337f193d69SLuke Drummond     const auto kv_pair = line->split(": ");
31347f193d69SLuke Drummond     const auto key = kv_pair.first;
31357f193d69SLuke Drummond     const auto val = kv_pair.second.trim();
31365ec532a9SColin Riley 
3137b3bbcb12SLuke Drummond     const auto handler = rs_info_handler(key);
3138b3bbcb12SLuke Drummond     if (handler == -1)
31397f193d69SLuke Drummond       continue;
31407f193d69SLuke Drummond     // getAsInteger returns `true` on an error condition - we're only interested
3141b3bbcb12SLuke Drummond     // in numeric fields at the moment
31427f193d69SLuke Drummond     uint64_t n_lines;
31437f193d69SLuke Drummond     if (val.getAsInteger(10, n_lines)) {
31446302bf6aSPavel Labath       LLDB_LOGV(log, "Failed to parse non-numeric '.rs.info' section {0}",
31456302bf6aSPavel Labath                 line->str());
31467f193d69SLuke Drummond       continue;
31477f193d69SLuke Drummond     }
31487f193d69SLuke Drummond     if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
31497f193d69SLuke Drummond       return false;
31507f193d69SLuke Drummond 
31517f193d69SLuke Drummond     bool success = false;
3152b3bbcb12SLuke Drummond     switch (handler) {
31537f193d69SLuke Drummond     case eExportVar:
31547f193d69SLuke Drummond       success = ParseExportVarCount(line, n_lines);
31557f193d69SLuke Drummond       break;
31567f193d69SLuke Drummond     case eExportForEach:
31577f193d69SLuke Drummond       success = ParseExportForeachCount(line, n_lines);
31587f193d69SLuke Drummond       break;
31597f193d69SLuke Drummond     case eExportReduce:
31607f193d69SLuke Drummond       success = ParseExportReduceCount(line, n_lines);
31617f193d69SLuke Drummond       break;
31627f193d69SLuke Drummond     case ePragma:
31637f193d69SLuke Drummond       success = ParsePragmaCount(line, n_lines);
31647f193d69SLuke Drummond       break;
316547d64161SLuke Drummond     case eVersionInfo:
316647d64161SLuke Drummond       success = ParseVersionInfo(line, n_lines);
316747d64161SLuke Drummond       break;
31687f193d69SLuke Drummond     default: {
31697f193d69SLuke Drummond       if (log)
31707f193d69SLuke Drummond         log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__,
31717f193d69SLuke Drummond                     line->str().c_str());
31727f193d69SLuke Drummond       continue;
31737f193d69SLuke Drummond     }
31747f193d69SLuke Drummond     }
31757f193d69SLuke Drummond     if (!success)
31767f193d69SLuke Drummond       return false;
31777f193d69SLuke Drummond     line += n_lines;
31787f193d69SLuke Drummond   }
31797f193d69SLuke Drummond   return info_lines.size() > 0;
31805ec532a9SColin Riley }
31815ec532a9SColin Riley 
318297206d57SZachary Turner void RenderScriptRuntime::DumpStatus(Stream &strm) const {
3183b9c1b51eSKate Stone   if (m_libRS) {
31844640cde1SColin Riley     strm.Printf("Runtime Library discovered.");
31854640cde1SColin Riley     strm.EOL();
31864640cde1SColin Riley   }
3187b9c1b51eSKate Stone   if (m_libRSDriver) {
31884640cde1SColin Riley     strm.Printf("Runtime Driver discovered.");
31894640cde1SColin Riley     strm.EOL();
31904640cde1SColin Riley   }
3191b9c1b51eSKate Stone   if (m_libRSCpuRef) {
31924640cde1SColin Riley     strm.Printf("CPU Reference Implementation discovered.");
31934640cde1SColin Riley     strm.EOL();
31944640cde1SColin Riley   }
31954640cde1SColin Riley 
3196b9c1b51eSKate Stone   if (m_runtimeHooks.size()) {
31974640cde1SColin Riley     strm.Printf("Runtime functions hooked:");
31984640cde1SColin Riley     strm.EOL();
3199b9c1b51eSKate Stone     for (auto b : m_runtimeHooks) {
32004640cde1SColin Riley       strm.Indent(b.second->defn->name);
32014640cde1SColin Riley       strm.EOL();
32024640cde1SColin Riley     }
3203b9c1b51eSKate Stone   } else {
32044640cde1SColin Riley     strm.Printf("Runtime is not hooked.");
32054640cde1SColin Riley     strm.EOL();
32064640cde1SColin Riley   }
32074640cde1SColin Riley }
32084640cde1SColin Riley 
3209b9c1b51eSKate Stone void RenderScriptRuntime::DumpContexts(Stream &strm) const {
32104640cde1SColin Riley   strm.Printf("Inferred RenderScript Contexts:");
32114640cde1SColin Riley   strm.EOL();
32124640cde1SColin Riley   strm.IndentMore();
32134640cde1SColin Riley 
32144640cde1SColin Riley   std::map<addr_t, uint64_t> contextReferences;
32154640cde1SColin Riley 
321678f339d1SEwan Crawford   // Iterate over all of the currently discovered scripts.
3217b9c1b51eSKate Stone   // Note: We cant push or pop from m_scripts inside this loop or it may
3218b9c1b51eSKate Stone   // invalidate script.
3219b9c1b51eSKate Stone   for (const auto &script : m_scripts) {
322078f339d1SEwan Crawford     if (!script->context.isValid())
322178f339d1SEwan Crawford       continue;
322278f339d1SEwan Crawford     lldb::addr_t context = *script->context;
322378f339d1SEwan Crawford 
3224b9c1b51eSKate Stone     if (contextReferences.find(context) != contextReferences.end()) {
322578f339d1SEwan Crawford       contextReferences[context]++;
3226b9c1b51eSKate Stone     } else {
322778f339d1SEwan Crawford       contextReferences[context] = 1;
32284640cde1SColin Riley     }
32294640cde1SColin Riley   }
32304640cde1SColin Riley 
3231b9c1b51eSKate Stone   for (const auto &cRef : contextReferences) {
3232b9c1b51eSKate Stone     strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
3233b9c1b51eSKate Stone                 cRef.first, cRef.second);
32344640cde1SColin Riley     strm.EOL();
32354640cde1SColin Riley   }
32364640cde1SColin Riley   strm.IndentLess();
32374640cde1SColin Riley }
32384640cde1SColin Riley 
3239b9c1b51eSKate Stone void RenderScriptRuntime::DumpKernels(Stream &strm) const {
32404640cde1SColin Riley   strm.Printf("RenderScript Kernels:");
32414640cde1SColin Riley   strm.EOL();
32424640cde1SColin Riley   strm.IndentMore();
3243b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
32444640cde1SColin Riley     strm.Printf("Resource '%s':", module->m_resname.c_str());
32454640cde1SColin Riley     strm.EOL();
3246b9c1b51eSKate Stone     for (const auto &kernel : module->m_kernels) {
32474640cde1SColin Riley       strm.Indent(kernel.m_name.AsCString());
32484640cde1SColin Riley       strm.EOL();
32494640cde1SColin Riley     }
32504640cde1SColin Riley   }
32514640cde1SColin Riley   strm.IndentLess();
32524640cde1SColin Riley }
32534640cde1SColin Riley 
3254a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails *
3255b9c1b51eSKate Stone RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
3256a0f08674SEwan Crawford   AllocationDetails *alloc = nullptr;
3257a0f08674SEwan Crawford 
3258a0f08674SEwan Crawford   // See if we can find allocation using id as an index;
3259b9c1b51eSKate Stone   if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
3260b9c1b51eSKate Stone       m_allocations[alloc_id - 1]->id == alloc_id) {
3261a0f08674SEwan Crawford     alloc = m_allocations[alloc_id - 1].get();
3262a0f08674SEwan Crawford     return alloc;
3263a0f08674SEwan Crawford   }
3264a0f08674SEwan Crawford 
3265a0f08674SEwan Crawford   // Fallback to searching
3266b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
3267b9c1b51eSKate Stone     if (a->id == alloc_id) {
3268a0f08674SEwan Crawford       alloc = a.get();
3269a0f08674SEwan Crawford       break;
3270a0f08674SEwan Crawford     }
3271a0f08674SEwan Crawford   }
3272a0f08674SEwan Crawford 
3273b9c1b51eSKate Stone   if (alloc == nullptr) {
3274b9c1b51eSKate Stone     strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
3275b9c1b51eSKate Stone                 alloc_id);
3276a0f08674SEwan Crawford     strm.EOL();
3277a0f08674SEwan Crawford   }
3278a0f08674SEwan Crawford 
3279a0f08674SEwan Crawford   return alloc;
3280a0f08674SEwan Crawford }
3281a0f08674SEwan Crawford 
3282b9c1b51eSKate Stone // Prints the contents of an allocation to the output stream, which may be a
3283b9c1b51eSKate Stone // file
3284b9c1b51eSKate Stone bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
3285b9c1b51eSKate Stone                                          const uint32_t id) {
3286a0f08674SEwan Crawford   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3287a0f08674SEwan Crawford 
3288a0f08674SEwan Crawford   // Check we can find the desired allocation
3289a0f08674SEwan Crawford   AllocationDetails *alloc = FindAllocByID(strm, id);
3290a0f08674SEwan Crawford   if (!alloc)
3291a0f08674SEwan Crawford     return false; // FindAllocByID() will print error message for us here
3292a0f08674SEwan Crawford 
3293a0f08674SEwan Crawford   if (log)
3294b9c1b51eSKate Stone     log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
3295b9c1b51eSKate Stone                 *alloc->address.get());
3296a0f08674SEwan Crawford 
3297a0f08674SEwan Crawford   // Check we have information about the allocation, if not calculate it
329880af0b9eSLuke Drummond   if (alloc->ShouldRefresh()) {
3299a0f08674SEwan Crawford     if (log)
3300b9c1b51eSKate Stone       log->Printf("%s - allocation details not calculated yet, jitting info.",
3301b9c1b51eSKate Stone                   __FUNCTION__);
3302a0f08674SEwan Crawford 
3303a0f08674SEwan Crawford     // JIT all the allocation information
3304b9c1b51eSKate Stone     if (!RefreshAllocation(alloc, frame_ptr)) {
3305a0f08674SEwan Crawford       strm.Printf("Error: Couldn't JIT allocation details");
3306a0f08674SEwan Crawford       strm.EOL();
3307a0f08674SEwan Crawford       return false;
3308a0f08674SEwan Crawford     }
3309a0f08674SEwan Crawford   }
3310a0f08674SEwan Crawford 
3311a0f08674SEwan Crawford   // Establish format and size of each data element
3312b3f7f69dSAidan Dodds   const uint32_t vec_size = *alloc->element.type_vec_size.get();
33138b244e21SEwan Crawford   const Element::DataType type = *alloc->element.type.get();
3314a0f08674SEwan Crawford 
3315b9c1b51eSKate Stone   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
3316b9c1b51eSKate Stone          "Invalid allocation type");
3317a0f08674SEwan Crawford 
33182e920715SEwan Crawford   lldb::Format format;
33192e920715SEwan Crawford   if (type >= Element::RS_TYPE_ELEMENT)
33202e920715SEwan Crawford     format = eFormatHex;
33212e920715SEwan Crawford   else
3322b9c1b51eSKate Stone     format = vec_size == 1
3323b9c1b51eSKate Stone                  ? static_cast<lldb::Format>(
3324b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatSingle])
3325b9c1b51eSKate Stone                  : static_cast<lldb::Format>(
3326b9c1b51eSKate Stone                        AllocationDetails::RSTypeToFormat[type][eFormatVector]);
3327a0f08674SEwan Crawford 
3328b3f7f69dSAidan Dodds   const uint32_t data_size = *alloc->element.datum_size.get();
3329a0f08674SEwan Crawford 
3330a0f08674SEwan Crawford   if (log)
3331b9c1b51eSKate Stone     log->Printf("%s - element size %" PRIu32 " bytes, including padding",
3332b9c1b51eSKate Stone                 __FUNCTION__, data_size);
3333a0f08674SEwan Crawford 
333455232f09SEwan Crawford   // Allocate a buffer to copy data into
333555232f09SEwan Crawford   std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3336b9c1b51eSKate Stone   if (!buffer) {
33372e920715SEwan Crawford     strm.Printf("Error: Couldn't read allocation data");
333855232f09SEwan Crawford     strm.EOL();
333955232f09SEwan Crawford     return false;
334055232f09SEwan Crawford   }
334155232f09SEwan Crawford 
3342a0f08674SEwan Crawford   // Calculate stride between rows as there may be padding at end of rows since
3343a0f08674SEwan Crawford   // allocated memory is 16-byte aligned
3344b9c1b51eSKate Stone   if (!alloc->stride.isValid()) {
3345a0f08674SEwan Crawford     if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
3346a0f08674SEwan Crawford       alloc->stride = 0;
3347b9c1b51eSKate Stone     else if (!JITAllocationStride(alloc, frame_ptr)) {
3348a0f08674SEwan Crawford       strm.Printf("Error: Couldn't calculate allocation row stride");
3349a0f08674SEwan Crawford       strm.EOL();
3350a0f08674SEwan Crawford       return false;
3351a0f08674SEwan Crawford     }
3352a0f08674SEwan Crawford   }
3353b3f7f69dSAidan Dodds   const uint32_t stride = *alloc->stride.get();
3354b3f7f69dSAidan Dodds   const uint32_t size = *alloc->size.get(); // Size of whole allocation
3355b9c1b51eSKate Stone   const uint32_t padding =
3356b9c1b51eSKate Stone       alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3357a0f08674SEwan Crawford   if (log)
3358b9c1b51eSKate Stone     log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32
3359b9c1b51eSKate Stone                 " bytes, padding %" PRIu32,
3360b3f7f69dSAidan Dodds                 __FUNCTION__, stride, size, padding);
3361a0f08674SEwan Crawford 
3362a0f08674SEwan Crawford   // Find dimensions used to index loops, so need to be non-zero
3363b3f7f69dSAidan Dodds   uint32_t dim_x = alloc->dimension.get()->dim_1;
3364a0f08674SEwan Crawford   dim_x = dim_x == 0 ? 1 : dim_x;
3365a0f08674SEwan Crawford 
3366b3f7f69dSAidan Dodds   uint32_t dim_y = alloc->dimension.get()->dim_2;
3367a0f08674SEwan Crawford   dim_y = dim_y == 0 ? 1 : dim_y;
3368a0f08674SEwan Crawford 
3369b3f7f69dSAidan Dodds   uint32_t dim_z = alloc->dimension.get()->dim_3;
3370a0f08674SEwan Crawford   dim_z = dim_z == 0 ? 1 : dim_z;
3371a0f08674SEwan Crawford 
337255232f09SEwan Crawford   // Use data extractor to format output
337380af0b9eSLuke Drummond   const uint32_t target_ptr_size =
3374b9c1b51eSKate Stone       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3375b9c1b51eSKate Stone   DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
337680af0b9eSLuke Drummond                            target_ptr_size);
337755232f09SEwan Crawford 
3378b3f7f69dSAidan Dodds   uint32_t offset = 0;   // Offset in buffer to next element to be printed
3379b3f7f69dSAidan Dodds   uint32_t prev_row = 0; // Offset to the start of the previous row
3380a0f08674SEwan Crawford 
3381a0f08674SEwan Crawford   // Iterate over allocation dimensions, printing results to user
3382a0f08674SEwan Crawford   strm.Printf("Data (X, Y, Z):");
3383b9c1b51eSKate Stone   for (uint32_t z = 0; z < dim_z; ++z) {
3384b9c1b51eSKate Stone     for (uint32_t y = 0; y < dim_y; ++y) {
3385a0f08674SEwan Crawford       // Use stride to index start of next row.
3386a0f08674SEwan Crawford       if (!(y == 0 && z == 0))
3387a0f08674SEwan Crawford         offset = prev_row + stride;
3388a0f08674SEwan Crawford       prev_row = offset;
3389a0f08674SEwan Crawford 
3390a0f08674SEwan Crawford       // Print each element in the row individually
3391b9c1b51eSKate Stone       for (uint32_t x = 0; x < dim_x; ++x) {
3392b3f7f69dSAidan Dodds         strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3393b9c1b51eSKate Stone         if ((type == Element::RS_TYPE_NONE) &&
3394b9c1b51eSKate Stone             (alloc->element.children.size() > 0) &&
3395b9c1b51eSKate Stone             (alloc->element.type_name != Element::GetFallbackStructName())) {
33968b244e21SEwan Crawford           // Here we are dumping an Element of struct type.
3397b9c1b51eSKate Stone           // This is done using expression evaluation with the name of the
3398b9c1b51eSKate Stone           // struct type and pointer to element.
3399b9c1b51eSKate Stone           // Don't print the name of the resulting expression, since this will
3400b9c1b51eSKate Stone           // be '$[0-9]+'
34018b244e21SEwan Crawford           DumpValueObjectOptions expr_options;
34028b244e21SEwan Crawford           expr_options.SetHideName(true);
34038b244e21SEwan Crawford 
34048b244e21SEwan Crawford           // Setup expression as derefrencing a pointer cast to element address.
3405ea0636b5SEwan Crawford           char expr_char_buffer[jit_max_expr_size];
340680af0b9eSLuke Drummond           int written =
3407b9c1b51eSKate Stone               snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3408b9c1b51eSKate Stone                        alloc->element.type_name.AsCString(),
3409b9c1b51eSKate Stone                        *alloc->data_ptr.get() + offset);
34108b244e21SEwan Crawford 
341180af0b9eSLuke Drummond           if (written < 0 || written >= jit_max_expr_size) {
34128b244e21SEwan Crawford             if (log)
3413b3f7f69dSAidan Dodds               log->Printf("%s - error in snprintf().", __FUNCTION__);
34148b244e21SEwan Crawford             continue;
34158b244e21SEwan Crawford           }
34168b244e21SEwan Crawford 
34178b244e21SEwan Crawford           // Evaluate expression
34188b244e21SEwan Crawford           ValueObjectSP expr_result;
3419b9c1b51eSKate Stone           GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3420b9c1b51eSKate Stone                                                        frame_ptr, expr_result);
34218b244e21SEwan Crawford 
34228b244e21SEwan Crawford           // Print the results to our stream.
34238b244e21SEwan Crawford           expr_result->Dump(strm, expr_options);
3424b9c1b51eSKate Stone         } else {
342529cb868aSZachary Turner           DumpDataExtractor(alloc_data, &strm, offset, format,
342629cb868aSZachary Turner                             data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0,
342729cb868aSZachary Turner                             0);
34288b244e21SEwan Crawford         }
34298b244e21SEwan Crawford         offset += data_size;
3430a0f08674SEwan Crawford       }
3431a0f08674SEwan Crawford     }
3432a0f08674SEwan Crawford   }
3433a0f08674SEwan Crawford   strm.EOL();
3434a0f08674SEwan Crawford 
3435a0f08674SEwan Crawford   return true;
3436a0f08674SEwan Crawford }
3437a0f08674SEwan Crawford 
3438b9c1b51eSKate Stone // Function recalculates all our cached information about allocations by jitting
343980af0b9eSLuke Drummond // the RS runtime regarding each allocation we know about. Returns true if all
344080af0b9eSLuke Drummond // allocations could be recomputed, false otherwise.
3441b9c1b51eSKate Stone bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3442b9c1b51eSKate Stone                                                   StackFrame *frame_ptr) {
34430d2bfcfbSEwan Crawford   bool success = true;
3444b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
34450d2bfcfbSEwan Crawford     // JIT current allocation information
3446b9c1b51eSKate Stone     if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3447b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3448b9c1b51eSKate Stone                   "\n",
3449b9c1b51eSKate Stone                   alloc->id);
34500d2bfcfbSEwan Crawford       success = false;
34510d2bfcfbSEwan Crawford     }
34520d2bfcfbSEwan Crawford   }
34530d2bfcfbSEwan Crawford 
34540d2bfcfbSEwan Crawford   if (success)
34550d2bfcfbSEwan Crawford     strm.Printf("All allocations successfully recomputed");
34560d2bfcfbSEwan Crawford   strm.EOL();
34570d2bfcfbSEwan Crawford 
34580d2bfcfbSEwan Crawford   return success;
34590d2bfcfbSEwan Crawford }
34600d2bfcfbSEwan Crawford 
346180af0b9eSLuke Drummond // Prints information regarding currently loaded allocations. These details are
346280af0b9eSLuke Drummond // gathered by jitting the runtime, which has as latency. Index parameter
346380af0b9eSLuke Drummond // specifies a single allocation ID to print, or a zero value to print them all
3464b9c1b51eSKate Stone void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3465b9c1b51eSKate Stone                                           const uint32_t index) {
346615f2bd95SEwan Crawford   strm.Printf("RenderScript Allocations:");
346715f2bd95SEwan Crawford   strm.EOL();
346815f2bd95SEwan Crawford   strm.IndentMore();
346915f2bd95SEwan Crawford 
3470b9c1b51eSKate Stone   for (auto &alloc : m_allocations) {
3471b649b005SEwan Crawford     // index will only be zero if we want to print all allocations
3472b649b005SEwan Crawford     if (index != 0 && index != alloc->id)
3473b649b005SEwan Crawford       continue;
347415f2bd95SEwan Crawford 
347515f2bd95SEwan Crawford     // JIT current allocation information
347680af0b9eSLuke Drummond     if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3477b9c1b51eSKate Stone       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3478b9c1b51eSKate Stone                   alloc->id);
3479b3f7f69dSAidan Dodds       strm.EOL();
348015f2bd95SEwan Crawford       continue;
348115f2bd95SEwan Crawford     }
348215f2bd95SEwan Crawford 
3483b3f7f69dSAidan Dodds     strm.Printf("%" PRIu32 ":", alloc->id);
3484b3f7f69dSAidan Dodds     strm.EOL();
348515f2bd95SEwan Crawford     strm.IndentMore();
348615f2bd95SEwan Crawford 
348715f2bd95SEwan Crawford     strm.Indent("Context: ");
348815f2bd95SEwan Crawford     if (!alloc->context.isValid())
348915f2bd95SEwan Crawford       strm.Printf("unknown\n");
349015f2bd95SEwan Crawford     else
349115f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
349215f2bd95SEwan Crawford 
349315f2bd95SEwan Crawford     strm.Indent("Address: ");
349415f2bd95SEwan Crawford     if (!alloc->address.isValid())
349515f2bd95SEwan Crawford       strm.Printf("unknown\n");
349615f2bd95SEwan Crawford     else
349715f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
349815f2bd95SEwan Crawford 
349915f2bd95SEwan Crawford     strm.Indent("Data pointer: ");
350015f2bd95SEwan Crawford     if (!alloc->data_ptr.isValid())
350115f2bd95SEwan Crawford       strm.Printf("unknown\n");
350215f2bd95SEwan Crawford     else
350315f2bd95SEwan Crawford       strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
350415f2bd95SEwan Crawford 
350515f2bd95SEwan Crawford     strm.Indent("Dimensions: ");
350615f2bd95SEwan Crawford     if (!alloc->dimension.isValid())
350715f2bd95SEwan Crawford       strm.Printf("unknown\n");
350815f2bd95SEwan Crawford     else
3509b3f7f69dSAidan Dodds       strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3510b9c1b51eSKate Stone                   alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3511b9c1b51eSKate Stone                   alloc->dimension.get()->dim_3);
351215f2bd95SEwan Crawford 
351315f2bd95SEwan Crawford     strm.Indent("Data Type: ");
3514b9c1b51eSKate Stone     if (!alloc->element.type.isValid() ||
3515b9c1b51eSKate Stone         !alloc->element.type_vec_size.isValid())
351615f2bd95SEwan Crawford       strm.Printf("unknown\n");
3517b9c1b51eSKate Stone     else {
35188b244e21SEwan Crawford       const int vector_size = *alloc->element.type_vec_size.get();
35192e920715SEwan Crawford       Element::DataType type = *alloc->element.type.get();
352015f2bd95SEwan Crawford 
35218b244e21SEwan Crawford       if (!alloc->element.type_name.IsEmpty())
35228b244e21SEwan Crawford         strm.Printf("%s\n", alloc->element.type_name.AsCString());
3523b9c1b51eSKate Stone       else {
3524b9c1b51eSKate Stone         // Enum value isn't monotonous, so doesn't always index
3525b9c1b51eSKate Stone         // RsDataTypeToString array
35262e920715SEwan Crawford         if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3527b9c1b51eSKate Stone           type =
3528b9c1b51eSKate Stone               static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3529b3f7f69dSAidan Dodds                                              Element::RS_TYPE_MATRIX_2X2 + 1);
35302e920715SEwan Crawford 
3531b3f7f69dSAidan Dodds         if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3532b3f7f69dSAidan Dodds                      sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3533b3f7f69dSAidan Dodds             vector_size > 4 || vector_size < 1)
353415f2bd95SEwan Crawford           strm.Printf("invalid type\n");
353515f2bd95SEwan Crawford         else
3536b9c1b51eSKate Stone           strm.Printf(
3537b9c1b51eSKate Stone               "%s\n",
3538b9c1b51eSKate Stone               AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3539b3f7f69dSAidan Dodds                                                    [vector_size - 1]);
354015f2bd95SEwan Crawford       }
35412e920715SEwan Crawford     }
354215f2bd95SEwan Crawford 
354315f2bd95SEwan Crawford     strm.Indent("Data Kind: ");
35448b244e21SEwan Crawford     if (!alloc->element.type_kind.isValid())
354515f2bd95SEwan Crawford       strm.Printf("unknown\n");
3546b9c1b51eSKate Stone     else {
35478b244e21SEwan Crawford       const Element::DataKind kind = *alloc->element.type_kind.get();
35488b244e21SEwan Crawford       if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
354915f2bd95SEwan Crawford         strm.Printf("invalid kind\n");
355015f2bd95SEwan Crawford       else
3551b9c1b51eSKate Stone         strm.Printf(
3552b9c1b51eSKate Stone             "%s\n",
3553b9c1b51eSKate Stone             AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
355415f2bd95SEwan Crawford     }
355515f2bd95SEwan Crawford 
355615f2bd95SEwan Crawford     strm.EOL();
355715f2bd95SEwan Crawford     strm.IndentLess();
355815f2bd95SEwan Crawford   }
355915f2bd95SEwan Crawford   strm.IndentLess();
356015f2bd95SEwan Crawford }
356115f2bd95SEwan Crawford 
35627dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
3563b9c1b51eSKate Stone void RenderScriptRuntime::BreakOnModuleKernels(
3564b9c1b51eSKate Stone     const RSModuleDescriptorSP rsmodule_sp) {
3565b9c1b51eSKate Stone   for (const auto &kernel : rsmodule_sp->m_kernels) {
35667dc7771cSEwan Crawford     // Don't set breakpoint on 'root' kernel
35677dc7771cSEwan Crawford     if (strcmp(kernel.m_name.AsCString(), "root") == 0)
35687dc7771cSEwan Crawford       continue;
35697dc7771cSEwan Crawford 
35707dc7771cSEwan Crawford     CreateKernelBreakpoint(kernel.m_name);
35717dc7771cSEwan Crawford   }
35727dc7771cSEwan Crawford }
35737dc7771cSEwan Crawford 
357480af0b9eSLuke Drummond // Method is internally called by the 'kernel breakpoint all' command to enable
357580af0b9eSLuke Drummond // or disable breaking on all kernels. When do_break is true we want to enable
357680af0b9eSLuke Drummond // this functionality. When do_break is false we want to disable it.
3577b9c1b51eSKate Stone void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3578b9c1b51eSKate Stone   Log *log(
3579b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
35807dc7771cSEwan Crawford 
35817dc7771cSEwan Crawford   InitSearchFilter(target);
35827dc7771cSEwan Crawford 
35837dc7771cSEwan Crawford   // Set breakpoints on all the kernels
3584b9c1b51eSKate Stone   if (do_break && !m_breakAllKernels) {
35857dc7771cSEwan Crawford     m_breakAllKernels = true;
35867dc7771cSEwan Crawford 
35877dc7771cSEwan Crawford     for (const auto &module : m_rsmodules)
35887dc7771cSEwan Crawford       BreakOnModuleKernels(module);
35897dc7771cSEwan Crawford 
35907dc7771cSEwan Crawford     if (log)
3591b9c1b51eSKate Stone       log->Printf("%s(True) - breakpoints set on all currently loaded kernels.",
3592b9c1b51eSKate Stone                   __FUNCTION__);
3593b9c1b51eSKate Stone   } else if (!do_break &&
3594b9c1b51eSKate Stone              m_breakAllKernels) // Breakpoints won't be set on any new kernels.
35957dc7771cSEwan Crawford   {
35967dc7771cSEwan Crawford     m_breakAllKernels = false;
35977dc7771cSEwan Crawford 
35987dc7771cSEwan Crawford     if (log)
3599b9c1b51eSKate Stone       log->Printf("%s(False) - breakpoints no longer automatically set.",
3600b9c1b51eSKate Stone                   __FUNCTION__);
36017dc7771cSEwan Crawford   }
36027dc7771cSEwan Crawford }
36037dc7771cSEwan Crawford 
36047dc7771cSEwan Crawford // Given the name of a kernel this function creates a breakpoint using our
36057dc7771cSEwan Crawford // own breakpoint resolver, and returns the Breakpoint shared pointer.
36067dc7771cSEwan Crawford BreakpointSP
3607b9c1b51eSKate Stone RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) {
3608b9c1b51eSKate Stone   Log *log(
3609b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
36107dc7771cSEwan Crawford 
3611b9c1b51eSKate Stone   if (!m_filtersp) {
36127dc7771cSEwan Crawford     if (log)
3613b3f7f69dSAidan Dodds       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
36147dc7771cSEwan Crawford     return nullptr;
36157dc7771cSEwan Crawford   }
36167dc7771cSEwan Crawford 
36177dc7771cSEwan Crawford   BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3618b842f2ecSJim Ingham   Target &target = GetProcess()->GetTarget();
3619b842f2ecSJim Ingham   BreakpointSP bp = target.CreateBreakpoint(
3620b9c1b51eSKate Stone       m_filtersp, resolver_sp, false, false, false);
36217dc7771cSEwan Crawford 
3622b9c1b51eSKate Stone   // Give RS breakpoints a specific name, so the user can manipulate them as a
3623b9c1b51eSKate Stone   // group.
362497206d57SZachary Turner   Status err;
3625b842f2ecSJim Ingham   target.AddNameToBreakpoint(bp, "RenderScriptKernel", err);
3626b842f2ecSJim Ingham   if (err.Fail() && log)
3627b3bbcb12SLuke Drummond     if (log)
3628b3bbcb12SLuke Drummond       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3629b3bbcb12SLuke Drummond                   err.AsCString());
3630b3bbcb12SLuke Drummond 
3631b3bbcb12SLuke Drummond   return bp;
3632b3bbcb12SLuke Drummond }
3633b3bbcb12SLuke Drummond 
3634b3bbcb12SLuke Drummond BreakpointSP
3635b3bbcb12SLuke Drummond RenderScriptRuntime::CreateReductionBreakpoint(const ConstString &name,
3636b3bbcb12SLuke Drummond                                                int kernel_types) {
3637b3bbcb12SLuke Drummond   Log *log(
3638b3bbcb12SLuke Drummond       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3639b3bbcb12SLuke Drummond 
3640b3bbcb12SLuke Drummond   if (!m_filtersp) {
3641b3bbcb12SLuke Drummond     if (log)
3642b3bbcb12SLuke Drummond       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3643b3bbcb12SLuke Drummond     return nullptr;
3644b3bbcb12SLuke Drummond   }
3645b3bbcb12SLuke Drummond 
3646b3bbcb12SLuke Drummond   BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3647b3bbcb12SLuke Drummond       nullptr, name, &m_rsmodules, kernel_types));
3648b842f2ecSJim Ingham   Target &target = GetProcess()->GetTarget();
3649b842f2ecSJim Ingham   BreakpointSP bp = target.CreateBreakpoint(
3650b3bbcb12SLuke Drummond       m_filtersp, resolver_sp, false, false, false);
3651b3bbcb12SLuke Drummond 
3652b3bbcb12SLuke Drummond   // Give RS breakpoints a specific name, so the user can manipulate them as a
3653b3bbcb12SLuke Drummond   // group.
365497206d57SZachary Turner   Status err;
3655b842f2ecSJim Ingham   target.AddNameToBreakpoint(bp, "RenderScriptReduction", err);
3656b842f2ecSJim Ingham   if (err.Fail() && log)
3657b9c1b51eSKate Stone       log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3658b9c1b51eSKate Stone                   err.AsCString());
365954782db7SEwan Crawford 
36607dc7771cSEwan Crawford   return bp;
36617dc7771cSEwan Crawford }
36627dc7771cSEwan Crawford 
3663b9c1b51eSKate Stone // Given an expression for a variable this function tries to calculate the
366480af0b9eSLuke Drummond // variable's value. If this is possible it returns true and sets the uint64_t
366580af0b9eSLuke Drummond // parameter to the variables unsigned value. Otherwise function returns false.
3666b9c1b51eSKate Stone bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3667b9c1b51eSKate Stone                                                 const char *var_name,
3668b9c1b51eSKate Stone                                                 uint64_t &val) {
3669018f5a7eSEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
367097206d57SZachary Turner   Status err;
3671018f5a7eSEwan Crawford   VariableSP var_sp;
3672018f5a7eSEwan Crawford 
3673018f5a7eSEwan Crawford   // Find variable in stack frame
3674b3f7f69dSAidan Dodds   ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3675b3f7f69dSAidan Dodds       var_name, eNoDynamicValues,
3676b9c1b51eSKate Stone       StackFrame::eExpressionPathOptionCheckPtrVsMember |
3677b9c1b51eSKate Stone           StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
367880af0b9eSLuke Drummond       var_sp, err));
367980af0b9eSLuke Drummond   if (!err.Success()) {
3680018f5a7eSEwan Crawford     if (log)
3681b9c1b51eSKate Stone       log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__,
3682b9c1b51eSKate Stone                   var_name);
3683018f5a7eSEwan Crawford     return false;
3684018f5a7eSEwan Crawford   }
3685018f5a7eSEwan Crawford 
3686b3f7f69dSAidan Dodds   // Find the uint32_t value for the variable
3687018f5a7eSEwan Crawford   bool success = false;
3688018f5a7eSEwan Crawford   val = value_sp->GetValueAsUnsigned(0, &success);
3689b9c1b51eSKate Stone   if (!success) {
3690018f5a7eSEwan Crawford     if (log)
3691b9c1b51eSKate Stone       log->Printf("%s - error, couldn't parse '%s' as an uint32_t.",
3692b9c1b51eSKate Stone                   __FUNCTION__, var_name);
3693018f5a7eSEwan Crawford     return false;
3694018f5a7eSEwan Crawford   }
3695018f5a7eSEwan Crawford 
3696018f5a7eSEwan Crawford   return true;
3697018f5a7eSEwan Crawford }
3698018f5a7eSEwan Crawford 
3699b9c1b51eSKate Stone // Function attempts to find the current coordinate of a kernel invocation by
370080af0b9eSLuke Drummond // investigating the values of frame variables in the .expand function. These
370180af0b9eSLuke Drummond // coordinates are returned via the coord array reference parameter. Returns
370280af0b9eSLuke Drummond // true if the coordinates could be found, and false otherwise.
3703b9c1b51eSKate Stone bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3704b9c1b51eSKate Stone                                               Thread *thread_ptr) {
370500f56eebSLuke Drummond   static const char *const x_expr = "rsIndex";
370600f56eebSLuke Drummond   static const char *const y_expr = "p->current.y";
370700f56eebSLuke Drummond   static const char *const z_expr = "p->current.z";
37081e05c3bcSGreg Clayton 
37094f8817c2SEwan Crawford   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
37104f8817c2SEwan Crawford 
3711b9c1b51eSKate Stone   if (!thread_ptr) {
37124f8817c2SEwan Crawford     if (log)
37134f8817c2SEwan Crawford       log->Printf("%s - Error, No thread pointer", __FUNCTION__);
37144f8817c2SEwan Crawford 
37154f8817c2SEwan Crawford     return false;
37164f8817c2SEwan Crawford   }
37174f8817c2SEwan Crawford 
3718b9c1b51eSKate Stone   // Walk the call stack looking for a function whose name has the suffix
371980af0b9eSLuke Drummond   // '.expand' and contains the variables we're looking for.
3720b9c1b51eSKate Stone   for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
37214f8817c2SEwan Crawford     if (!thread_ptr->SetSelectedFrameByIndex(i))
37224f8817c2SEwan Crawford       continue;
37234f8817c2SEwan Crawford 
37244f8817c2SEwan Crawford     StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
37254f8817c2SEwan Crawford     if (!frame_sp)
37264f8817c2SEwan Crawford       continue;
37274f8817c2SEwan Crawford 
37284f8817c2SEwan Crawford     // Find the function name
37294f8817c2SEwan Crawford     const SymbolContext sym_ctx = frame_sp->GetSymbolContext(false);
373000f56eebSLuke Drummond     const ConstString func_name = sym_ctx.GetFunctionName();
373100f56eebSLuke Drummond     if (!func_name)
37324f8817c2SEwan Crawford       continue;
37334f8817c2SEwan Crawford 
37344f8817c2SEwan Crawford     if (log)
3735b9c1b51eSKate Stone       log->Printf("%s - Inspecting function '%s'", __FUNCTION__,
373600f56eebSLuke Drummond                   func_name.GetCString());
37374f8817c2SEwan Crawford 
37384f8817c2SEwan Crawford     // Check if function name has .expand suffix
373900f56eebSLuke Drummond     if (!func_name.GetStringRef().endswith(".expand"))
37404f8817c2SEwan Crawford       continue;
37414f8817c2SEwan Crawford 
37424f8817c2SEwan Crawford     if (log)
3743b9c1b51eSKate Stone       log->Printf("%s - Found .expand function '%s'", __FUNCTION__,
374400f56eebSLuke Drummond                   func_name.GetCString());
37454f8817c2SEwan Crawford 
3746b9c1b51eSKate Stone     // Get values for variables in .expand frame that tell us the current kernel
3747b9c1b51eSKate Stone     // invocation
374800f56eebSLuke Drummond     uint64_t x, y, z;
374900f56eebSLuke Drummond     bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
375000f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
375100f56eebSLuke Drummond                  GetFrameVarAsUnsigned(frame_sp, z_expr, z);
37524f8817c2SEwan Crawford 
375300f56eebSLuke Drummond     if (found) {
375400f56eebSLuke Drummond       // The RenderScript runtime uses uint32_t for these vars. If they're not
375500f56eebSLuke Drummond       // within bounds, our frame parsing is garbage
375600f56eebSLuke Drummond       assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
375700f56eebSLuke Drummond       coord.x = (uint32_t)x;
375800f56eebSLuke Drummond       coord.y = (uint32_t)y;
375900f56eebSLuke Drummond       coord.z = (uint32_t)z;
37604f8817c2SEwan Crawford       return true;
37614f8817c2SEwan Crawford     }
376200f56eebSLuke Drummond   }
37634f8817c2SEwan Crawford   return false;
37644f8817c2SEwan Crawford }
37654f8817c2SEwan Crawford 
3766b9c1b51eSKate Stone // Callback when a kernel breakpoint hits and we're looking for a specific
376780af0b9eSLuke Drummond // coordinate. Baton parameter contains a pointer to the target coordinate we
376880af0b9eSLuke Drummond // want to break on.
3769b9c1b51eSKate Stone // Function then checks the .expand frame for the current coordinate and breaks
3770b9c1b51eSKate Stone // to user if it matches.
3771018f5a7eSEwan Crawford // Parameter 'break_id' is the id of the Breakpoint which made the callback.
3772018f5a7eSEwan Crawford // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
3773018f5a7eSEwan Crawford // a single logical breakpoint can have multiple addresses.
3774b9c1b51eSKate Stone bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3775b9c1b51eSKate Stone                                               StoppointCallbackContext *ctx,
3776b9c1b51eSKate Stone                                               user_id_t break_id,
3777b9c1b51eSKate Stone                                               user_id_t break_loc_id) {
3778b9c1b51eSKate Stone   Log *log(
3779b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3780018f5a7eSEwan Crawford 
3781b9c1b51eSKate Stone   assert(baton &&
3782b9c1b51eSKate Stone          "Error: null baton in conditional kernel breakpoint callback");
3783018f5a7eSEwan Crawford 
3784018f5a7eSEwan Crawford   // Coordinate we want to stop on
378500f56eebSLuke Drummond   RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3786018f5a7eSEwan Crawford 
3787018f5a7eSEwan Crawford   if (log)
378800f56eebSLuke Drummond     log->Printf("%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__, break_id,
378900f56eebSLuke Drummond                 target_coord.x, target_coord.y, target_coord.z);
3790018f5a7eSEwan Crawford 
37914f8817c2SEwan Crawford   // Select current thread
3792018f5a7eSEwan Crawford   ExecutionContext context(ctx->exe_ctx_ref);
37934f8817c2SEwan Crawford   Thread *thread_ptr = context.GetThreadPtr();
37944f8817c2SEwan Crawford   assert(thread_ptr && "Null thread pointer");
37954f8817c2SEwan Crawford 
37964f8817c2SEwan Crawford   // Find current kernel invocation from .expand frame variables
379700f56eebSLuke Drummond   RSCoordinate current_coord{};
3798b9c1b51eSKate Stone   if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3799018f5a7eSEwan Crawford     if (log)
3800b9c1b51eSKate Stone       log->Printf("%s - Error, couldn't select .expand stack frame",
3801b9c1b51eSKate Stone                   __FUNCTION__);
3802018f5a7eSEwan Crawford     return false;
3803018f5a7eSEwan Crawford   }
3804018f5a7eSEwan Crawford 
3805018f5a7eSEwan Crawford   if (log)
380600f56eebSLuke Drummond     log->Printf("%s - " FMT_COORD, __FUNCTION__, current_coord.x,
380700f56eebSLuke Drummond                 current_coord.y, current_coord.z);
3808018f5a7eSEwan Crawford 
3809b9c1b51eSKate Stone   // Check if the current kernel invocation coordinate matches our target
3810b9c1b51eSKate Stone   // coordinate
381100f56eebSLuke Drummond   if (target_coord == current_coord) {
3812018f5a7eSEwan Crawford     if (log)
381300f56eebSLuke Drummond       log->Printf("%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
381400f56eebSLuke Drummond                   current_coord.y, current_coord.z);
3815018f5a7eSEwan Crawford 
3816b9c1b51eSKate Stone     BreakpointSP breakpoint_sp =
3817b9c1b51eSKate Stone         context.GetTargetPtr()->GetBreakpointByID(break_id);
3818b9c1b51eSKate Stone     assert(breakpoint_sp != nullptr &&
3819b9c1b51eSKate Stone            "Error: Couldn't find breakpoint matching break id for callback");
3820b9c1b51eSKate Stone     breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3821b9c1b51eSKate Stone                                       // should only be hit once.
3822018f5a7eSEwan Crawford     return true;
3823018f5a7eSEwan Crawford   }
3824018f5a7eSEwan Crawford 
3825018f5a7eSEwan Crawford   // No match on coordinate
3826018f5a7eSEwan Crawford   return false;
3827018f5a7eSEwan Crawford }
3828018f5a7eSEwan Crawford 
382900f56eebSLuke Drummond void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
383000f56eebSLuke Drummond                                          const RSCoordinate &coord) {
383100f56eebSLuke Drummond   messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
383200f56eebSLuke Drummond                   coord.x, coord.y, coord.z);
383300f56eebSLuke Drummond   messages.EOL();
383400f56eebSLuke Drummond 
383500f56eebSLuke Drummond   // Allocate memory for the baton, and copy over coordinate
383600f56eebSLuke Drummond   RSCoordinate *baton = new RSCoordinate(coord);
383700f56eebSLuke Drummond 
383800f56eebSLuke Drummond   // Create a callback that will be invoked every time the breakpoint is hit.
383900f56eebSLuke Drummond   // The baton object passed to the handler is the target coordinate we want to
384000f56eebSLuke Drummond   // break on.
384100f56eebSLuke Drummond   bp->SetCallback(KernelBreakpointHit, baton, true);
384200f56eebSLuke Drummond 
384300f56eebSLuke Drummond   // Store a shared pointer to the baton, so the memory will eventually be
384400f56eebSLuke Drummond   // cleaned up after destruction
384500f56eebSLuke Drummond   m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
384600f56eebSLuke Drummond }
384700f56eebSLuke Drummond 
3848b9c1b51eSKate Stone // Tries to set a breakpoint on the start of a kernel, resolved using the kernel
384980af0b9eSLuke Drummond // name. Argument 'coords', represents a three dimensional coordinate which can
385080af0b9eSLuke Drummond // be
385180af0b9eSLuke Drummond // used to specify a single kernel instance to break on. If this is set then we
385280af0b9eSLuke Drummond // add a callback
3853b9c1b51eSKate Stone // to the breakpoint.
385400f56eebSLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
385500f56eebSLuke Drummond                                                   Stream &messages,
385600f56eebSLuke Drummond                                                   const char *name,
385700f56eebSLuke Drummond                                                   const RSCoordinate *coord) {
385800f56eebSLuke Drummond   if (!name)
385900f56eebSLuke Drummond     return false;
38604640cde1SColin Riley 
38617dc7771cSEwan Crawford   InitSearchFilter(target);
386298156583SEwan Crawford 
38634640cde1SColin Riley   ConstString kernel_name(name);
38647dc7771cSEwan Crawford   BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
386500f56eebSLuke Drummond   if (!bp)
386600f56eebSLuke Drummond     return false;
3867018f5a7eSEwan Crawford 
3868018f5a7eSEwan Crawford   // We have a conditional breakpoint on a specific coordinate
386900f56eebSLuke Drummond   if (coord)
387000f56eebSLuke Drummond     SetConditional(bp, messages, *coord);
3871018f5a7eSEwan Crawford 
387200f56eebSLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3873018f5a7eSEwan Crawford 
387400f56eebSLuke Drummond   return true;
38754640cde1SColin Riley }
38764640cde1SColin Riley 
387721fed052SAidan Dodds BreakpointSP
387821fed052SAidan Dodds RenderScriptRuntime::CreateScriptGroupBreakpoint(const ConstString &name,
387921fed052SAidan Dodds                                                  bool stop_on_all) {
388021fed052SAidan Dodds   Log *log(
388121fed052SAidan Dodds       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
388221fed052SAidan Dodds 
388321fed052SAidan Dodds   if (!m_filtersp) {
388421fed052SAidan Dodds     if (log)
388521fed052SAidan Dodds       log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
388621fed052SAidan Dodds     return nullptr;
388721fed052SAidan Dodds   }
388821fed052SAidan Dodds 
388921fed052SAidan Dodds   BreakpointResolverSP resolver_sp(new RSScriptGroupBreakpointResolver(
389021fed052SAidan Dodds       nullptr, name, m_scriptGroups, stop_on_all));
3891b842f2ecSJim Ingham   Target &target = GetProcess()->GetTarget();
3892b842f2ecSJim Ingham   BreakpointSP bp = target.CreateBreakpoint(
389321fed052SAidan Dodds       m_filtersp, resolver_sp, false, false, false);
389421fed052SAidan Dodds   // Give RS breakpoints a specific name, so the user can manipulate them as a
389521fed052SAidan Dodds   // group.
389697206d57SZachary Turner   Status err;
3897b842f2ecSJim Ingham   target.AddNameToBreakpoint(bp, name.GetCString(), err);
3898b842f2ecSJim Ingham   if (err.Fail() && log)
389921fed052SAidan Dodds     log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
390021fed052SAidan Dodds                 err.AsCString());
390121fed052SAidan Dodds   // ask the breakpoint to resolve itself
390221fed052SAidan Dodds   bp->ResolveBreakpoint();
390321fed052SAidan Dodds   return bp;
390421fed052SAidan Dodds }
390521fed052SAidan Dodds 
390621fed052SAidan Dodds bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target,
390721fed052SAidan Dodds                                                        Stream &strm,
390821fed052SAidan Dodds                                                        const ConstString &name,
390921fed052SAidan Dodds                                                        bool multi) {
391021fed052SAidan Dodds   InitSearchFilter(target);
391121fed052SAidan Dodds   BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi);
391221fed052SAidan Dodds   if (bp)
391321fed052SAidan Dodds     bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
391421fed052SAidan Dodds   return bool(bp);
391521fed052SAidan Dodds }
391621fed052SAidan Dodds 
3917b3bbcb12SLuke Drummond bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3918b3bbcb12SLuke Drummond                                                      Stream &messages,
3919b3bbcb12SLuke Drummond                                                      const char *reduce_name,
3920b3bbcb12SLuke Drummond                                                      const RSCoordinate *coord,
3921b3bbcb12SLuke Drummond                                                      int kernel_types) {
3922b3bbcb12SLuke Drummond   if (!reduce_name)
3923b3bbcb12SLuke Drummond     return false;
3924b3bbcb12SLuke Drummond 
3925b3bbcb12SLuke Drummond   InitSearchFilter(target);
3926b3bbcb12SLuke Drummond   BreakpointSP bp =
3927b3bbcb12SLuke Drummond       CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3928b3bbcb12SLuke Drummond   if (!bp)
3929b3bbcb12SLuke Drummond     return false;
3930b3bbcb12SLuke Drummond 
3931b3bbcb12SLuke Drummond   if (coord)
3932b3bbcb12SLuke Drummond     SetConditional(bp, messages, *coord);
3933b3bbcb12SLuke Drummond 
3934b3bbcb12SLuke Drummond   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3935b3bbcb12SLuke Drummond 
3936b3bbcb12SLuke Drummond   return true;
3937b3bbcb12SLuke Drummond }
3938b3bbcb12SLuke Drummond 
3939b9c1b51eSKate Stone void RenderScriptRuntime::DumpModules(Stream &strm) const {
39405ec532a9SColin Riley   strm.Printf("RenderScript Modules:");
39415ec532a9SColin Riley   strm.EOL();
39425ec532a9SColin Riley   strm.IndentMore();
3943b9c1b51eSKate Stone   for (const auto &module : m_rsmodules) {
39444640cde1SColin Riley     module->Dump(strm);
39455ec532a9SColin Riley   }
39465ec532a9SColin Riley   strm.IndentLess();
39475ec532a9SColin Riley }
39485ec532a9SColin Riley 
394978f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails *
3950b9c1b51eSKate Stone RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3951b9c1b51eSKate Stone   for (const auto &s : m_scripts) {
395278f339d1SEwan Crawford     if (s->script.isValid())
395378f339d1SEwan Crawford       if (*s->script == address)
395478f339d1SEwan Crawford         return s.get();
395578f339d1SEwan Crawford   }
3956b9c1b51eSKate Stone   if (create) {
395778f339d1SEwan Crawford     std::unique_ptr<ScriptDetails> s(new ScriptDetails);
395878f339d1SEwan Crawford     s->script = address;
395978f339d1SEwan Crawford     m_scripts.push_back(std::move(s));
3960d10ca9deSEwan Crawford     return m_scripts.back().get();
396178f339d1SEwan Crawford   }
396278f339d1SEwan Crawford   return nullptr;
396378f339d1SEwan Crawford }
396478f339d1SEwan Crawford 
396578f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails *
3966b9c1b51eSKate Stone RenderScriptRuntime::LookUpAllocation(addr_t address) {
3967b9c1b51eSKate Stone   for (const auto &a : m_allocations) {
396878f339d1SEwan Crawford     if (a->address.isValid())
396978f339d1SEwan Crawford       if (*a->address == address)
397078f339d1SEwan Crawford         return a.get();
397178f339d1SEwan Crawford   }
39725d057637SLuke Drummond   return nullptr;
39735d057637SLuke Drummond }
39745d057637SLuke Drummond 
39755d057637SLuke Drummond RenderScriptRuntime::AllocationDetails *
3976b9c1b51eSKate Stone RenderScriptRuntime::CreateAllocation(addr_t address) {
39775d057637SLuke Drummond   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
39785d057637SLuke Drummond 
39795d057637SLuke Drummond   // Remove any previous allocation which contains the same address
39805d057637SLuke Drummond   auto it = m_allocations.begin();
3981b9c1b51eSKate Stone   while (it != m_allocations.end()) {
3982b9c1b51eSKate Stone     if (*((*it)->address) == address) {
39835d057637SLuke Drummond       if (log)
3984b9c1b51eSKate Stone         log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64,
3985b9c1b51eSKate Stone                     __FUNCTION__, (*it)->id, address);
39865d057637SLuke Drummond 
39875d057637SLuke Drummond       it = m_allocations.erase(it);
3988b9c1b51eSKate Stone     } else {
39895d057637SLuke Drummond       it++;
39905d057637SLuke Drummond     }
39915d057637SLuke Drummond   }
39925d057637SLuke Drummond 
399378f339d1SEwan Crawford   std::unique_ptr<AllocationDetails> a(new AllocationDetails);
399478f339d1SEwan Crawford   a->address = address;
399578f339d1SEwan Crawford   m_allocations.push_back(std::move(a));
3996d10ca9deSEwan Crawford   return m_allocations.back().get();
399778f339d1SEwan Crawford }
399878f339d1SEwan Crawford 
399921fed052SAidan Dodds bool RenderScriptRuntime::ResolveKernelName(lldb::addr_t kernel_addr,
400021fed052SAidan Dodds                                             ConstString &name) {
400121fed052SAidan Dodds   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
400221fed052SAidan Dodds 
400321fed052SAidan Dodds   Target &target = GetProcess()->GetTarget();
400421fed052SAidan Dodds   Address resolved;
400521fed052SAidan Dodds   // RenderScript module
400621fed052SAidan Dodds   if (!target.GetSectionLoadList().ResolveLoadAddress(kernel_addr, resolved)) {
400721fed052SAidan Dodds     if (log)
400821fed052SAidan Dodds       log->Printf("%s: unable to resolve 0x%" PRIx64 " to a loaded symbol",
400921fed052SAidan Dodds                   __FUNCTION__, kernel_addr);
401021fed052SAidan Dodds     return false;
401121fed052SAidan Dodds   }
401221fed052SAidan Dodds 
401321fed052SAidan Dodds   Symbol *sym = resolved.CalculateSymbolContextSymbol();
401421fed052SAidan Dodds   if (!sym)
401521fed052SAidan Dodds     return false;
401621fed052SAidan Dodds 
401721fed052SAidan Dodds   name = sym->GetName();
401821fed052SAidan Dodds   assert(IsRenderScriptModule(resolved.CalculateSymbolContextModule()));
401921fed052SAidan Dodds   if (log)
402021fed052SAidan Dodds     log->Printf("%s: 0x%" PRIx64 " resolved to the symbol '%s'", __FUNCTION__,
402121fed052SAidan Dodds                 kernel_addr, name.GetCString());
402221fed052SAidan Dodds   return true;
402321fed052SAidan Dodds }
402421fed052SAidan Dodds 
4025b9c1b51eSKate Stone void RSModuleDescriptor::Dump(Stream &strm) const {
40267f193d69SLuke Drummond   int indent = strm.GetIndentLevel();
40277f193d69SLuke Drummond 
40285ec532a9SColin Riley   strm.Indent();
40295ec532a9SColin Riley   m_module->GetFileSpec().Dump(&strm);
40307f193d69SLuke Drummond   strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
40317f193d69SLuke Drummond                                              : "Debug info does not exist.");
40325ec532a9SColin Riley   strm.EOL();
40335ec532a9SColin Riley   strm.IndentMore();
40347f193d69SLuke Drummond 
40355ec532a9SColin Riley   strm.Indent();
4036189598edSColin Riley   strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
40375ec532a9SColin Riley   strm.EOL();
40385ec532a9SColin Riley   strm.IndentMore();
4039b9c1b51eSKate Stone   for (const auto &global : m_globals) {
40405ec532a9SColin Riley     global.Dump(strm);
40415ec532a9SColin Riley   }
40425ec532a9SColin Riley   strm.IndentLess();
40437f193d69SLuke Drummond 
40445ec532a9SColin Riley   strm.Indent();
4045189598edSColin Riley   strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
40465ec532a9SColin Riley   strm.EOL();
40475ec532a9SColin Riley   strm.IndentMore();
4048b9c1b51eSKate Stone   for (const auto &kernel : m_kernels) {
40495ec532a9SColin Riley     kernel.Dump(strm);
40505ec532a9SColin Riley   }
40517f193d69SLuke Drummond   strm.IndentLess();
40527f193d69SLuke Drummond 
40537f193d69SLuke Drummond   strm.Indent();
40544640cde1SColin Riley   strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
40554640cde1SColin Riley   strm.EOL();
40564640cde1SColin Riley   strm.IndentMore();
4057b9c1b51eSKate Stone   for (const auto &key_val : m_pragmas) {
40587f193d69SLuke Drummond     strm.Indent();
40594640cde1SColin Riley     strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
40604640cde1SColin Riley     strm.EOL();
40614640cde1SColin Riley   }
40627f193d69SLuke Drummond   strm.IndentLess();
40637f193d69SLuke Drummond 
40647f193d69SLuke Drummond   strm.Indent();
40657f193d69SLuke Drummond   strm.Printf("Reductions: %" PRIu64,
40667f193d69SLuke Drummond               static_cast<uint64_t>(m_reductions.size()));
40677f193d69SLuke Drummond   strm.EOL();
40687f193d69SLuke Drummond   strm.IndentMore();
40697f193d69SLuke Drummond   for (const auto &reduction : m_reductions) {
40707f193d69SLuke Drummond     reduction.Dump(strm);
40717f193d69SLuke Drummond   }
40727f193d69SLuke Drummond 
40737f193d69SLuke Drummond   strm.SetIndentLevel(indent);
40745ec532a9SColin Riley }
40755ec532a9SColin Riley 
4076b9c1b51eSKate Stone void RSGlobalDescriptor::Dump(Stream &strm) const {
40775ec532a9SColin Riley   strm.Indent(m_name.AsCString());
40784640cde1SColin Riley   VariableList var_list;
40794640cde1SColin Riley   m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
4080b9c1b51eSKate Stone   if (var_list.GetSize() == 1) {
40814640cde1SColin Riley     auto var = var_list.GetVariableAtIndex(0);
40824640cde1SColin Riley     auto type = var->GetType();
4083b9c1b51eSKate Stone     if (type) {
40844640cde1SColin Riley       strm.Printf(" - ");
40854640cde1SColin Riley       type->DumpTypeName(&strm);
4086b9c1b51eSKate Stone     } else {
40874640cde1SColin Riley       strm.Printf(" - Unknown Type");
40884640cde1SColin Riley     }
4089b9c1b51eSKate Stone   } else {
40904640cde1SColin Riley     strm.Printf(" - variable identified, but not found in binary");
4091b9c1b51eSKate Stone     const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
4092b9c1b51eSKate Stone         m_name, eSymbolTypeData);
4093b9c1b51eSKate Stone     if (s) {
40944640cde1SColin Riley       strm.Printf(" (symbol exists) ");
40954640cde1SColin Riley     }
40964640cde1SColin Riley   }
40974640cde1SColin Riley 
40985ec532a9SColin Riley   strm.EOL();
40995ec532a9SColin Riley }
41005ec532a9SColin Riley 
4101b9c1b51eSKate Stone void RSKernelDescriptor::Dump(Stream &strm) const {
41025ec532a9SColin Riley   strm.Indent(m_name.AsCString());
41035ec532a9SColin Riley   strm.EOL();
41045ec532a9SColin Riley }
41055ec532a9SColin Riley 
41067f193d69SLuke Drummond void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
41077f193d69SLuke Drummond   stream.Indent(m_reduce_name.AsCString());
41087f193d69SLuke Drummond   stream.IndentMore();
41097f193d69SLuke Drummond   stream.EOL();
41107f193d69SLuke Drummond   stream.Indent();
41117f193d69SLuke Drummond   stream.Printf("accumulator: %s", m_accum_name.AsCString());
41127f193d69SLuke Drummond   stream.EOL();
41137f193d69SLuke Drummond   stream.Indent();
41147f193d69SLuke Drummond   stream.Printf("initializer: %s", m_init_name.AsCString());
41157f193d69SLuke Drummond   stream.EOL();
41167f193d69SLuke Drummond   stream.Indent();
41177f193d69SLuke Drummond   stream.Printf("combiner: %s", m_comb_name.AsCString());
41187f193d69SLuke Drummond   stream.EOL();
41197f193d69SLuke Drummond   stream.Indent();
41207f193d69SLuke Drummond   stream.Printf("outconverter: %s", m_outc_name.AsCString());
41217f193d69SLuke Drummond   stream.EOL();
41227f193d69SLuke Drummond   // XXX This is currently unspecified by RenderScript, and unused
41237f193d69SLuke Drummond   // stream.Indent();
41247f193d69SLuke Drummond   // stream.Printf("halter: '%s'", m_init_name.AsCString());
41257f193d69SLuke Drummond   // stream.EOL();
41267f193d69SLuke Drummond   stream.IndentLess();
41277f193d69SLuke Drummond }
41287f193d69SLuke Drummond 
4129b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
41305ec532a9SColin Riley public:
41315ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
4132b9c1b51eSKate Stone       : CommandObjectParsed(
4133b9c1b51eSKate Stone             interpreter, "renderscript module dump",
4134b9c1b51eSKate Stone             "Dumps renderscript specific information for all modules.",
4135b9c1b51eSKate Stone             "renderscript module dump",
4136b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
41375ec532a9SColin Riley 
4138222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
41395ec532a9SColin Riley 
4140b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
41415ec532a9SColin Riley     RenderScriptRuntime *runtime =
4142b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4143b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
41445ec532a9SColin Riley     runtime->DumpModules(result.GetOutputStream());
41455ec532a9SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
41465ec532a9SColin Riley     return true;
41475ec532a9SColin Riley   }
41485ec532a9SColin Riley };
41495ec532a9SColin Riley 
4150b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
41515ec532a9SColin Riley public:
41525ec532a9SColin Riley   CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
4153b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript module",
4154b9c1b51eSKate Stone                                "Commands that deal with RenderScript modules.",
4155b9c1b51eSKate Stone                                nullptr) {
4156b9c1b51eSKate Stone     LoadSubCommand(
4157b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
4158b9c1b51eSKate Stone                     interpreter)));
41595ec532a9SColin Riley   }
41605ec532a9SColin Riley 
4161222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeModule() override = default;
41625ec532a9SColin Riley };
41635ec532a9SColin Riley 
4164b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
41654640cde1SColin Riley public:
41664640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
4167b9c1b51eSKate Stone       : CommandObjectParsed(
4168b9c1b51eSKate Stone             interpreter, "renderscript kernel list",
4169b3f7f69dSAidan Dodds             "Lists renderscript kernel names and associated script resources.",
4170b9c1b51eSKate Stone             "renderscript kernel list",
4171b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
41724640cde1SColin Riley 
4173222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelList() override = default;
41744640cde1SColin Riley 
4175b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
41764640cde1SColin Riley     RenderScriptRuntime *runtime =
4177b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4178b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
41794640cde1SColin Riley     runtime->DumpKernels(result.GetOutputStream());
41804640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
41814640cde1SColin Riley     return true;
41824640cde1SColin Riley   }
41834640cde1SColin Riley };
41844640cde1SColin Riley 
4185b3bbcb12SLuke Drummond static OptionDefinition g_renderscript_reduction_bp_set_options[] = {
4186b3bbcb12SLuke Drummond     {LLDB_OPT_SET_1, false, "function-role", 't',
4187b3bbcb12SLuke Drummond      OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOneLiner,
4188b3bbcb12SLuke Drummond      "Break on a comma separated set of reduction kernel types "
4189b3bbcb12SLuke Drummond      "(accumulator,outcoverter,combiner,initializer"},
4190b3bbcb12SLuke Drummond     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4191b3bbcb12SLuke Drummond      nullptr, nullptr, 0, eArgTypeValue,
4192b3bbcb12SLuke Drummond      "Set a breakpoint on a single invocation of the kernel with specified "
4193b3bbcb12SLuke Drummond      "coordinate.\n"
4194b3bbcb12SLuke Drummond      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4195b3bbcb12SLuke Drummond      "integers representing kernel dimensions. "
4196b3bbcb12SLuke Drummond      "Any unset dimensions will be defaulted to zero."}};
4197b3bbcb12SLuke Drummond 
4198b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReductionBreakpointSet
4199b3bbcb12SLuke Drummond     : public CommandObjectParsed {
4200b3bbcb12SLuke Drummond public:
4201b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4202b3bbcb12SLuke Drummond       CommandInterpreter &interpreter)
4203b3bbcb12SLuke Drummond       : CommandObjectParsed(
4204b3bbcb12SLuke Drummond             interpreter, "renderscript reduction breakpoint set",
4205b3bbcb12SLuke Drummond             "Set a breakpoint on named RenderScript general reductions",
4206b3bbcb12SLuke Drummond             "renderscript reduction breakpoint set  <kernel_name> [-t "
4207b3bbcb12SLuke Drummond             "<reduction_kernel_type,...>]",
4208b3bbcb12SLuke Drummond             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4209b3bbcb12SLuke Drummond                 eCommandProcessMustBePaused),
4210b3bbcb12SLuke Drummond         m_options(){};
4211b3bbcb12SLuke Drummond 
4212b3bbcb12SLuke Drummond   class CommandOptions : public Options {
4213b3bbcb12SLuke Drummond   public:
4214b3bbcb12SLuke Drummond     CommandOptions()
4215b3bbcb12SLuke Drummond         : Options(),
4216b3bbcb12SLuke Drummond           m_kernel_types(RSReduceBreakpointResolver::eKernelTypeAll) {}
4217b3bbcb12SLuke Drummond 
4218b3bbcb12SLuke Drummond     ~CommandOptions() override = default;
4219b3bbcb12SLuke Drummond 
422097206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4221b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
422297206d57SZachary Turner       Status err;
4223b3bbcb12SLuke Drummond       StreamString err_str;
4224b3bbcb12SLuke Drummond       const int short_option = m_getopt_table[option_idx].val;
4225b3bbcb12SLuke Drummond       switch (short_option) {
4226b3bbcb12SLuke Drummond       case 't':
4227fe11483bSZachary Turner         if (!ParseReductionTypes(option_arg, err_str))
4228b3bbcb12SLuke Drummond           err.SetErrorStringWithFormat(
4229fe11483bSZachary Turner               "Unable to deduce reduction types for %s: %s",
4230fe11483bSZachary Turner               option_arg.str().c_str(), err_str.GetData());
4231b3bbcb12SLuke Drummond         break;
4232b3bbcb12SLuke Drummond       case 'c': {
4233b3bbcb12SLuke Drummond         auto coord = RSCoordinate{};
4234fe11483bSZachary Turner         if (!ParseCoordinate(option_arg, coord))
4235b3bbcb12SLuke Drummond           err.SetErrorStringWithFormat("unable to parse coordinate for %s",
4236fe11483bSZachary Turner                                        option_arg.str().c_str());
4237b3bbcb12SLuke Drummond         else {
4238b3bbcb12SLuke Drummond           m_have_coord = true;
4239b3bbcb12SLuke Drummond           m_coord = coord;
4240b3bbcb12SLuke Drummond         }
4241b3bbcb12SLuke Drummond         break;
4242b3bbcb12SLuke Drummond       }
4243b3bbcb12SLuke Drummond       default:
4244b3bbcb12SLuke Drummond         err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
4245b3bbcb12SLuke Drummond       }
4246b3bbcb12SLuke Drummond       return err;
4247b3bbcb12SLuke Drummond     }
4248b3bbcb12SLuke Drummond 
4249b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4250b3bbcb12SLuke Drummond       m_have_coord = false;
4251b3bbcb12SLuke Drummond     }
4252b3bbcb12SLuke Drummond 
4253b3bbcb12SLuke Drummond     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4254b3bbcb12SLuke Drummond       return llvm::makeArrayRef(g_renderscript_reduction_bp_set_options);
4255b3bbcb12SLuke Drummond     }
4256b3bbcb12SLuke Drummond 
4257fe11483bSZachary Turner     bool ParseReductionTypes(llvm::StringRef option_val,
4258fe11483bSZachary Turner                              StreamString &err_str) {
4259b3bbcb12SLuke Drummond       m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
4260b3bbcb12SLuke Drummond       const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
4261b3bbcb12SLuke Drummond         return llvm::StringSwitch<int>(name)
4262b3bbcb12SLuke Drummond             .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
4263b3bbcb12SLuke Drummond             .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
4264b3bbcb12SLuke Drummond             .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
4265b3bbcb12SLuke Drummond             .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
4266b3bbcb12SLuke Drummond             .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
4267b3bbcb12SLuke Drummond             // Currently not exposed by the runtime
4268b3bbcb12SLuke Drummond             // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
4269b3bbcb12SLuke Drummond             .Default(0);
4270b3bbcb12SLuke Drummond       };
4271b3bbcb12SLuke Drummond 
4272b3bbcb12SLuke Drummond       // Matching a comma separated list of known words is fairly
4273b3bbcb12SLuke Drummond       // straightforward with PCRE, but we're
4274b3bbcb12SLuke Drummond       // using ERE, so we end up with a little ugliness...
4275b3bbcb12SLuke Drummond       RegularExpression::Match match(/* max_matches */ 5);
4276b3bbcb12SLuke Drummond       RegularExpression match_type_list(
4277b3bbcb12SLuke Drummond           llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
4278b3bbcb12SLuke Drummond 
4279b3bbcb12SLuke Drummond       assert(match_type_list.IsValid());
4280b3bbcb12SLuke Drummond 
4281fe11483bSZachary Turner       if (!match_type_list.Execute(option_val, &match)) {
4282b3bbcb12SLuke Drummond         err_str.PutCString(
4283b3bbcb12SLuke Drummond             "a comma-separated list of kernel types is required");
4284b3bbcb12SLuke Drummond         return false;
4285b3bbcb12SLuke Drummond       }
4286b3bbcb12SLuke Drummond 
4287b3bbcb12SLuke Drummond       // splitting on commas is much easier with llvm::StringRef than regex
4288b3bbcb12SLuke Drummond       llvm::SmallVector<llvm::StringRef, 5> type_names;
4289b3bbcb12SLuke Drummond       llvm::StringRef(option_val).split(type_names, ',');
4290b3bbcb12SLuke Drummond 
4291b3bbcb12SLuke Drummond       for (const auto &name : type_names) {
4292b3bbcb12SLuke Drummond         const int type = reduce_name_to_type(name);
4293b3bbcb12SLuke Drummond         if (!type) {
4294b3bbcb12SLuke Drummond           err_str.Printf("unknown kernel type name %s", name.str().c_str());
4295b3bbcb12SLuke Drummond           return false;
4296b3bbcb12SLuke Drummond         }
4297b3bbcb12SLuke Drummond         m_kernel_types |= type;
4298b3bbcb12SLuke Drummond       }
4299b3bbcb12SLuke Drummond 
4300b3bbcb12SLuke Drummond       return true;
4301b3bbcb12SLuke Drummond     }
4302b3bbcb12SLuke Drummond 
4303b3bbcb12SLuke Drummond     int m_kernel_types;
4304b3bbcb12SLuke Drummond     llvm::StringRef m_reduce_name;
4305b3bbcb12SLuke Drummond     RSCoordinate m_coord;
4306b3bbcb12SLuke Drummond     bool m_have_coord;
4307b3bbcb12SLuke Drummond   };
4308b3bbcb12SLuke Drummond 
4309b3bbcb12SLuke Drummond   Options *GetOptions() override { return &m_options; }
4310b3bbcb12SLuke Drummond 
4311b3bbcb12SLuke Drummond   bool DoExecute(Args &command, CommandReturnObject &result) override {
4312b3bbcb12SLuke Drummond     const size_t argc = command.GetArgumentCount();
4313b3bbcb12SLuke Drummond     if (argc < 1) {
4314b3bbcb12SLuke Drummond       result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
4315b3bbcb12SLuke Drummond                                    "and an optional kernel type list",
4316b3bbcb12SLuke Drummond                                    m_cmd_name.c_str());
4317b3bbcb12SLuke Drummond       result.SetStatus(eReturnStatusFailed);
4318b3bbcb12SLuke Drummond       return false;
4319b3bbcb12SLuke Drummond     }
4320b3bbcb12SLuke Drummond 
4321b3bbcb12SLuke Drummond     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4322b3bbcb12SLuke Drummond         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4323b3bbcb12SLuke Drummond             eLanguageTypeExtRenderScript));
4324b3bbcb12SLuke Drummond 
4325b3bbcb12SLuke Drummond     auto &outstream = result.GetOutputStream();
4326b3bbcb12SLuke Drummond     auto name = command.GetArgumentAtIndex(0);
4327b3bbcb12SLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
4328b3bbcb12SLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4329b3bbcb12SLuke Drummond     if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
4330b3bbcb12SLuke Drummond                                              m_options.m_kernel_types)) {
4331b3bbcb12SLuke Drummond       result.SetStatus(eReturnStatusFailed);
4332b3bbcb12SLuke Drummond       result.AppendError("Error: unable to place breakpoint on reduction");
4333b3bbcb12SLuke Drummond       return false;
4334b3bbcb12SLuke Drummond     }
4335b3bbcb12SLuke Drummond     result.AppendMessage("Breakpoint(s) created");
4336b3bbcb12SLuke Drummond     result.SetStatus(eReturnStatusSuccessFinishResult);
4337b3bbcb12SLuke Drummond     return true;
4338b3bbcb12SLuke Drummond   }
4339b3bbcb12SLuke Drummond 
4340b3bbcb12SLuke Drummond private:
4341b3bbcb12SLuke Drummond   CommandOptions m_options;
4342b3bbcb12SLuke Drummond };
4343b3bbcb12SLuke Drummond 
43441f0f5b5bSZachary Turner static OptionDefinition g_renderscript_kernel_bp_set_options[] = {
43451f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
43461f0f5b5bSZachary Turner      nullptr, nullptr, 0, eArgTypeValue,
43471f0f5b5bSZachary Turner      "Set a breakpoint on a single invocation of the kernel with specified "
43481f0f5b5bSZachary Turner      "coordinate.\n"
43491f0f5b5bSZachary Turner      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
43501f0f5b5bSZachary Turner      "integers representing kernel dimensions. "
43511f0f5b5bSZachary Turner      "Any unset dimensions will be defaulted to zero."}};
43521f0f5b5bSZachary Turner 
4353b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointSet
4354b9c1b51eSKate Stone     : public CommandObjectParsed {
43554640cde1SColin Riley public:
4356b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4357b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4358b9c1b51eSKate Stone       : CommandObjectParsed(
4359b9c1b51eSKate Stone             interpreter, "renderscript kernel breakpoint set",
4360b3f7f69dSAidan Dodds             "Sets a breakpoint on a renderscript kernel.",
4361b3f7f69dSAidan Dodds             "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
4362b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4363b9c1b51eSKate Stone                 eCommandProcessMustBePaused),
4364b9c1b51eSKate Stone         m_options() {}
43654640cde1SColin Riley 
4366222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
4367222b937cSEugene Zelenko 
4368b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
4369018f5a7eSEwan Crawford 
4370b9c1b51eSKate Stone   class CommandOptions : public Options {
4371018f5a7eSEwan Crawford   public:
4372e1cfbc79STodd Fiala     CommandOptions() : Options() {}
4373018f5a7eSEwan Crawford 
4374222b937cSEugene Zelenko     ~CommandOptions() override = default;
4375018f5a7eSEwan Crawford 
437697206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4377b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
437897206d57SZachary Turner       Status err;
4379018f5a7eSEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
4380018f5a7eSEwan Crawford 
4381b9c1b51eSKate Stone       switch (short_option) {
438200f56eebSLuke Drummond       case 'c': {
438300f56eebSLuke Drummond         auto coord = RSCoordinate{};
438400f56eebSLuke Drummond         if (!ParseCoordinate(option_arg, coord))
438580af0b9eSLuke Drummond           err.SetErrorStringWithFormat(
4386b9c1b51eSKate Stone               "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
4387fe11483bSZachary Turner               option_arg.str().c_str());
438800f56eebSLuke Drummond         else {
438900f56eebSLuke Drummond           m_have_coord = true;
439000f56eebSLuke Drummond           m_coord = coord;
439100f56eebSLuke Drummond         }
4392018f5a7eSEwan Crawford         break;
439300f56eebSLuke Drummond       }
4394018f5a7eSEwan Crawford       default:
439580af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4396018f5a7eSEwan Crawford         break;
4397018f5a7eSEwan Crawford       }
439880af0b9eSLuke Drummond       return err;
4399018f5a7eSEwan Crawford     }
4400018f5a7eSEwan Crawford 
4401b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
440200f56eebSLuke Drummond       m_have_coord = false;
4403018f5a7eSEwan Crawford     }
4404018f5a7eSEwan Crawford 
44051f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
440670602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
44071f0f5b5bSZachary Turner     }
4408018f5a7eSEwan Crawford 
440900f56eebSLuke Drummond     RSCoordinate m_coord;
441000f56eebSLuke Drummond     bool m_have_coord;
4411018f5a7eSEwan Crawford   };
4412018f5a7eSEwan Crawford 
4413b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
44144640cde1SColin Riley     const size_t argc = command.GetArgumentCount();
4415b9c1b51eSKate Stone     if (argc < 1) {
4416b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4417b9c1b51eSKate Stone           "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4418b3f7f69dSAidan Dodds           m_cmd_name.c_str());
4419018f5a7eSEwan Crawford       result.SetStatus(eReturnStatusFailed);
4420018f5a7eSEwan Crawford       return false;
4421018f5a7eSEwan Crawford     }
4422018f5a7eSEwan Crawford 
44234640cde1SColin Riley     RenderScriptRuntime *runtime =
4424b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4425b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
44264640cde1SColin Riley 
442700f56eebSLuke Drummond     auto &outstream = result.GetOutputStream();
442800f56eebSLuke Drummond     auto &target = m_exe_ctx.GetTargetSP();
442900f56eebSLuke Drummond     auto name = command.GetArgumentAtIndex(0);
443000f56eebSLuke Drummond     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
443100f56eebSLuke Drummond     if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
443200f56eebSLuke Drummond       result.SetStatus(eReturnStatusFailed);
443300f56eebSLuke Drummond       result.AppendErrorWithFormat(
443400f56eebSLuke Drummond           "Error: unable to set breakpoint on kernel '%s'", name);
443500f56eebSLuke Drummond       return false;
443600f56eebSLuke Drummond     }
44374640cde1SColin Riley 
44384640cde1SColin Riley     result.AppendMessage("Breakpoint(s) created");
44394640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
44404640cde1SColin Riley     return true;
44414640cde1SColin Riley   }
44424640cde1SColin Riley 
4443018f5a7eSEwan Crawford private:
4444018f5a7eSEwan Crawford   CommandOptions m_options;
44454640cde1SColin Riley };
44464640cde1SColin Riley 
4447b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4448b9c1b51eSKate Stone     : public CommandObjectParsed {
44497dc7771cSEwan Crawford public:
4450b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4451b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4452b3f7f69dSAidan Dodds       : CommandObjectParsed(
4453b3f7f69dSAidan Dodds             interpreter, "renderscript kernel breakpoint all",
4454b9c1b51eSKate Stone             "Automatically sets a breakpoint on all renderscript kernels that "
4455b9c1b51eSKate Stone             "are or will be loaded.\n"
4456b9c1b51eSKate Stone             "Disabling option means breakpoints will no longer be set on any "
4457b9c1b51eSKate Stone             "kernels loaded in the future, "
44587dc7771cSEwan Crawford             "but does not remove currently set breakpoints.",
44597dc7771cSEwan Crawford             "renderscript kernel breakpoint all <enable/disable>",
4460b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4461b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
44627dc7771cSEwan Crawford 
4463222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
44647dc7771cSEwan Crawford 
4465b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
44667dc7771cSEwan Crawford     const size_t argc = command.GetArgumentCount();
4467b9c1b51eSKate Stone     if (argc != 1) {
4468b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4469b9c1b51eSKate Stone           "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
44707dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
44717dc7771cSEwan Crawford       return false;
44727dc7771cSEwan Crawford     }
44737dc7771cSEwan Crawford 
4474b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4475b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4476b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
44777dc7771cSEwan Crawford 
44787dc7771cSEwan Crawford     bool do_break = false;
44797dc7771cSEwan Crawford     const char *argument = command.GetArgumentAtIndex(0);
4480b9c1b51eSKate Stone     if (strcmp(argument, "enable") == 0) {
44817dc7771cSEwan Crawford       do_break = true;
44827dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will be set on all kernels.");
4483b9c1b51eSKate Stone     } else if (strcmp(argument, "disable") == 0) {
44847dc7771cSEwan Crawford       do_break = false;
44857dc7771cSEwan Crawford       result.AppendMessage("Breakpoints will not be set on any new kernels.");
4486b9c1b51eSKate Stone     } else {
4487b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4488b9c1b51eSKate Stone           "Argument must be either 'enable' or 'disable'");
44897dc7771cSEwan Crawford       result.SetStatus(eReturnStatusFailed);
44907dc7771cSEwan Crawford       return false;
44917dc7771cSEwan Crawford     }
44927dc7771cSEwan Crawford 
44937dc7771cSEwan Crawford     runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
44947dc7771cSEwan Crawford 
44957dc7771cSEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
44967dc7771cSEwan Crawford     return true;
44977dc7771cSEwan Crawford   }
44987dc7771cSEwan Crawford };
44997dc7771cSEwan Crawford 
4500b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReductionBreakpoint
4501b3bbcb12SLuke Drummond     : public CommandObjectMultiword {
4502b3bbcb12SLuke Drummond public:
4503b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReductionBreakpoint(
4504b3bbcb12SLuke Drummond       CommandInterpreter &interpreter)
4505b3bbcb12SLuke Drummond       : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4506b3bbcb12SLuke Drummond                                "Commands that manipulate breakpoints on "
4507b3bbcb12SLuke Drummond                                "renderscript general reductions.",
4508b3bbcb12SLuke Drummond                                nullptr) {
4509b3bbcb12SLuke Drummond     LoadSubCommand(
4510b3bbcb12SLuke Drummond         "set", CommandObjectSP(
4511b3bbcb12SLuke Drummond                    new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4512b3bbcb12SLuke Drummond                        interpreter)));
4513b3bbcb12SLuke Drummond   }
4514b3bbcb12SLuke Drummond 
4515b3bbcb12SLuke Drummond   ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4516b3bbcb12SLuke Drummond };
4517b3bbcb12SLuke Drummond 
4518b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelCoordinate
4519b9c1b51eSKate Stone     : public CommandObjectParsed {
45204f8817c2SEwan Crawford public:
4521b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelCoordinate(
4522b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4523b9c1b51eSKate Stone       : CommandObjectParsed(
4524b9c1b51eSKate Stone             interpreter, "renderscript kernel coordinate",
45254f8817c2SEwan Crawford             "Shows the (x,y,z) coordinate of the current kernel invocation.",
45264f8817c2SEwan Crawford             "renderscript kernel coordinate",
4527b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4528b9c1b51eSKate Stone                 eCommandProcessMustBePaused) {}
45294f8817c2SEwan Crawford 
45304f8817c2SEwan Crawford   ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
45314f8817c2SEwan Crawford 
4532b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
453300f56eebSLuke Drummond     RSCoordinate coord{};
4534b9c1b51eSKate Stone     bool success = RenderScriptRuntime::GetKernelCoordinate(
4535b9c1b51eSKate Stone         coord, m_exe_ctx.GetThreadPtr());
45364f8817c2SEwan Crawford     Stream &stream = result.GetOutputStream();
45374f8817c2SEwan Crawford 
4538b9c1b51eSKate Stone     if (success) {
453900f56eebSLuke Drummond       stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
45404f8817c2SEwan Crawford       stream.EOL();
45414f8817c2SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4542b9c1b51eSKate Stone     } else {
45434f8817c2SEwan Crawford       stream.Printf("Error: Coordinate could not be found.");
45444f8817c2SEwan Crawford       stream.EOL();
45454f8817c2SEwan Crawford       result.SetStatus(eReturnStatusFailed);
45464f8817c2SEwan Crawford     }
45474f8817c2SEwan Crawford     return true;
45484f8817c2SEwan Crawford   }
45494f8817c2SEwan Crawford };
45504f8817c2SEwan Crawford 
4551b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernelBreakpoint
4552b9c1b51eSKate Stone     : public CommandObjectMultiword {
45537dc7771cSEwan Crawford public:
4554b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeKernelBreakpoint(
4555b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4556b9c1b51eSKate Stone       : CommandObjectMultiword(
4557b9c1b51eSKate Stone             interpreter, "renderscript kernel",
4558b9c1b51eSKate Stone             "Commands that generate breakpoints on renderscript kernels.",
4559b9c1b51eSKate Stone             nullptr) {
4560b9c1b51eSKate Stone     LoadSubCommand(
4561b9c1b51eSKate Stone         "set",
4562b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4563b9c1b51eSKate Stone             interpreter)));
4564b9c1b51eSKate Stone     LoadSubCommand(
4565b9c1b51eSKate Stone         "all",
4566b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4567b9c1b51eSKate Stone             interpreter)));
45687dc7771cSEwan Crawford   }
45697dc7771cSEwan Crawford 
4570222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
45717dc7771cSEwan Crawford };
45727dc7771cSEwan Crawford 
4573b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
45744640cde1SColin Riley public:
45754640cde1SColin Riley   CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4576b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript kernel",
4577b9c1b51eSKate Stone                                "Commands that deal with RenderScript kernels.",
4578b9c1b51eSKate Stone                                nullptr) {
4579b9c1b51eSKate Stone     LoadSubCommand(
4580b9c1b51eSKate Stone         "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4581b9c1b51eSKate Stone                     interpreter)));
4582b9c1b51eSKate Stone     LoadSubCommand(
4583b9c1b51eSKate Stone         "coordinate",
4584b9c1b51eSKate Stone         CommandObjectSP(
4585b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4586b9c1b51eSKate Stone     LoadSubCommand(
4587b9c1b51eSKate Stone         "breakpoint",
4588b9c1b51eSKate Stone         CommandObjectSP(
4589b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
45904640cde1SColin Riley   }
45914640cde1SColin Riley 
4592222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeKernel() override = default;
45934640cde1SColin Riley };
45944640cde1SColin Riley 
4595b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
45964640cde1SColin Riley public:
45974640cde1SColin Riley   CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4598b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript context dump",
4599b9c1b51eSKate Stone                             "Dumps renderscript context information.",
4600b9c1b51eSKate Stone                             "renderscript context dump",
4601b9c1b51eSKate Stone                             eCommandRequiresProcess |
4602b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
46034640cde1SColin Riley 
4604222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContextDump() override = default;
46054640cde1SColin Riley 
4606b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
46074640cde1SColin Riley     RenderScriptRuntime *runtime =
4608b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4609b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
46104640cde1SColin Riley     runtime->DumpContexts(result.GetOutputStream());
46114640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
46124640cde1SColin Riley     return true;
46134640cde1SColin Riley   }
46144640cde1SColin Riley };
46154640cde1SColin Riley 
46161f0f5b5bSZachary Turner static OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
46171f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
46181f0f5b5bSZachary Turner      nullptr, nullptr, 0, eArgTypeFilename,
46191f0f5b5bSZachary Turner      "Print results to specified file instead of command line."}};
46201f0f5b5bSZachary Turner 
4621b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
46224640cde1SColin Riley public:
46234640cde1SColin Riley   CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4624b9c1b51eSKate Stone       : CommandObjectMultiword(interpreter, "renderscript context",
4625b9c1b51eSKate Stone                                "Commands that deal with RenderScript contexts.",
4626b9c1b51eSKate Stone                                nullptr) {
4627b9c1b51eSKate Stone     LoadSubCommand(
4628b9c1b51eSKate Stone         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4629b9c1b51eSKate Stone                     interpreter)));
46304640cde1SColin Riley   }
46314640cde1SColin Riley 
4632222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeContext() override = default;
46334640cde1SColin Riley };
46344640cde1SColin Riley 
4635b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationDump
4636b9c1b51eSKate Stone     : public CommandObjectParsed {
4637a0f08674SEwan Crawford public:
4638b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationDump(
4639b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4640a0f08674SEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation dump",
4641b9c1b51eSKate Stone                             "Displays the contents of a particular allocation",
4642b9c1b51eSKate Stone                             "renderscript allocation dump <ID>",
4643b9c1b51eSKate Stone                             eCommandRequiresProcess |
4644b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched),
4645b9c1b51eSKate Stone         m_options() {}
4646a0f08674SEwan Crawford 
4647222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4648222b937cSEugene Zelenko 
4649b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
4650a0f08674SEwan Crawford 
4651b9c1b51eSKate Stone   class CommandOptions : public Options {
4652a0f08674SEwan Crawford   public:
4653e1cfbc79STodd Fiala     CommandOptions() : Options() {}
4654a0f08674SEwan Crawford 
4655222b937cSEugene Zelenko     ~CommandOptions() override = default;
4656a0f08674SEwan Crawford 
465797206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4658b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
465997206d57SZachary Turner       Status err;
4660a0f08674SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
4661a0f08674SEwan Crawford 
4662b9c1b51eSKate Stone       switch (short_option) {
4663a0f08674SEwan Crawford       case 'f':
4664a0f08674SEwan Crawford         m_outfile.SetFile(option_arg, true);
4665b9c1b51eSKate Stone         if (m_outfile.Exists()) {
4666a0f08674SEwan Crawford           m_outfile.Clear();
4667fe11483bSZachary Turner           err.SetErrorStringWithFormat("file already exists: '%s'",
4668fe11483bSZachary Turner                                        option_arg.str().c_str());
4669a0f08674SEwan Crawford         }
4670a0f08674SEwan Crawford         break;
4671a0f08674SEwan Crawford       default:
467280af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4673a0f08674SEwan Crawford         break;
4674a0f08674SEwan Crawford       }
467580af0b9eSLuke Drummond       return err;
4676a0f08674SEwan Crawford     }
4677a0f08674SEwan Crawford 
4678b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4679a0f08674SEwan Crawford       m_outfile.Clear();
4680a0f08674SEwan Crawford     }
4681a0f08674SEwan Crawford 
46821f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
468370602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
46841f0f5b5bSZachary Turner     }
4685a0f08674SEwan Crawford 
4686a0f08674SEwan Crawford     FileSpec m_outfile;
4687a0f08674SEwan Crawford   };
4688a0f08674SEwan Crawford 
4689b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4690a0f08674SEwan Crawford     const size_t argc = command.GetArgumentCount();
4691b9c1b51eSKate Stone     if (argc < 1) {
4692b9c1b51eSKate Stone       result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4693b9c1b51eSKate Stone                                    "As well as an optional -f argument",
4694a0f08674SEwan Crawford                                    m_cmd_name.c_str());
4695a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4696a0f08674SEwan Crawford       return false;
4697a0f08674SEwan Crawford     }
4698a0f08674SEwan Crawford 
4699b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4700b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4701b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4702a0f08674SEwan Crawford 
4703a0f08674SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
470480af0b9eSLuke Drummond     bool success = false;
4705b9c1b51eSKate Stone     const uint32_t id =
470680af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
470780af0b9eSLuke Drummond     if (!success) {
4708b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4709b9c1b51eSKate Stone                                    id_cstr);
4710a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4711a0f08674SEwan Crawford       return false;
4712a0f08674SEwan Crawford     }
4713a0f08674SEwan Crawford 
4714a0f08674SEwan Crawford     Stream *output_strm = nullptr;
4715a0f08674SEwan Crawford     StreamFile outfile_stream;
4716b9c1b51eSKate Stone     const FileSpec &outfile_spec =
4717b9c1b51eSKate Stone         m_options.m_outfile; // Dump allocation to file instead
4718b9c1b51eSKate Stone     if (outfile_spec) {
4719a0f08674SEwan Crawford       // Open output file
4720a0f08674SEwan Crawford       char path[256];
4721a0f08674SEwan Crawford       outfile_spec.GetPath(path, sizeof(path));
4722b9c1b51eSKate Stone       if (outfile_stream.GetFile()
4723b9c1b51eSKate Stone               .Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate)
4724b9c1b51eSKate Stone               .Success()) {
4725a0f08674SEwan Crawford         output_strm = &outfile_stream;
4726a0f08674SEwan Crawford         result.GetOutputStream().Printf("Results written to '%s'", path);
4727a0f08674SEwan Crawford         result.GetOutputStream().EOL();
4728b9c1b51eSKate Stone       } else {
4729a0f08674SEwan Crawford         result.AppendErrorWithFormat("Couldn't open file '%s'", path);
4730a0f08674SEwan Crawford         result.SetStatus(eReturnStatusFailed);
4731a0f08674SEwan Crawford         return false;
4732a0f08674SEwan Crawford       }
4733b9c1b51eSKate Stone     } else
4734a0f08674SEwan Crawford       output_strm = &result.GetOutputStream();
4735a0f08674SEwan Crawford 
4736a0f08674SEwan Crawford     assert(output_strm != nullptr);
473780af0b9eSLuke Drummond     bool dumped =
4738b9c1b51eSKate Stone         runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4739a0f08674SEwan Crawford 
474080af0b9eSLuke Drummond     if (dumped)
4741a0f08674SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
4742a0f08674SEwan Crawford     else
4743a0f08674SEwan Crawford       result.SetStatus(eReturnStatusFailed);
4744a0f08674SEwan Crawford 
4745a0f08674SEwan Crawford     return true;
4746a0f08674SEwan Crawford   }
4747a0f08674SEwan Crawford 
4748a0f08674SEwan Crawford private:
4749a0f08674SEwan Crawford   CommandOptions m_options;
4750a0f08674SEwan Crawford };
4751a0f08674SEwan Crawford 
47521f0f5b5bSZachary Turner static OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
47531f0f5b5bSZachary Turner     {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
47541f0f5b5bSZachary Turner      nullptr, 0, eArgTypeIndex,
47551f0f5b5bSZachary Turner      "Only show details of a single allocation with specified id."}};
4756a0f08674SEwan Crawford 
4757b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationList
4758b9c1b51eSKate Stone     : public CommandObjectParsed {
475915f2bd95SEwan Crawford public:
4760b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationList(
4761b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4762b9c1b51eSKate Stone       : CommandObjectParsed(
4763b9c1b51eSKate Stone             interpreter, "renderscript allocation list",
4764b9c1b51eSKate Stone             "List renderscript allocations and their information.",
4765b9c1b51eSKate Stone             "renderscript allocation list",
4766b3f7f69dSAidan Dodds             eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4767b9c1b51eSKate Stone         m_options() {}
476815f2bd95SEwan Crawford 
4769222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4770222b937cSEugene Zelenko 
4771b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
477215f2bd95SEwan Crawford 
4773b9c1b51eSKate Stone   class CommandOptions : public Options {
477415f2bd95SEwan Crawford   public:
4775e1cfbc79STodd Fiala     CommandOptions() : Options(), m_id(0) {}
477615f2bd95SEwan Crawford 
4777222b937cSEugene Zelenko     ~CommandOptions() override = default;
477815f2bd95SEwan Crawford 
477997206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4780b3bbcb12SLuke Drummond                           ExecutionContext *exe_ctx) override {
478197206d57SZachary Turner       Status err;
478215f2bd95SEwan Crawford       const int short_option = m_getopt_table[option_idx].val;
478315f2bd95SEwan Crawford 
4784b9c1b51eSKate Stone       switch (short_option) {
4785b649b005SEwan Crawford       case 'i':
4786fe11483bSZachary Turner         if (option_arg.getAsInteger(0, m_id))
478780af0b9eSLuke Drummond           err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4788b9c1b51eSKate Stone                                        short_option);
478915f2bd95SEwan Crawford         break;
479080af0b9eSLuke Drummond       default:
479180af0b9eSLuke Drummond         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
479280af0b9eSLuke Drummond         break;
479315f2bd95SEwan Crawford       }
479480af0b9eSLuke Drummond       return err;
479515f2bd95SEwan Crawford     }
479615f2bd95SEwan Crawford 
4797b3bbcb12SLuke Drummond     void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
479815f2bd95SEwan Crawford 
47991f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
480070602439SZachary Turner       return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
48011f0f5b5bSZachary Turner     }
480215f2bd95SEwan Crawford 
4803b649b005SEwan Crawford     uint32_t m_id;
480415f2bd95SEwan Crawford   };
480515f2bd95SEwan Crawford 
4806b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
4807b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4808b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4809b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
4810b9c1b51eSKate Stone     runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4811b9c1b51eSKate Stone                              m_options.m_id);
481215f2bd95SEwan Crawford     result.SetStatus(eReturnStatusSuccessFinishResult);
481315f2bd95SEwan Crawford     return true;
481415f2bd95SEwan Crawford   }
481515f2bd95SEwan Crawford 
481615f2bd95SEwan Crawford private:
481715f2bd95SEwan Crawford   CommandOptions m_options;
481815f2bd95SEwan Crawford };
481915f2bd95SEwan Crawford 
4820b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationLoad
4821b9c1b51eSKate Stone     : public CommandObjectParsed {
482255232f09SEwan Crawford public:
4823b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationLoad(
4824b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4825b3f7f69dSAidan Dodds       : CommandObjectParsed(
4826b9c1b51eSKate Stone             interpreter, "renderscript allocation load",
4827b9c1b51eSKate Stone             "Loads renderscript allocation contents from a file.",
4828b9c1b51eSKate Stone             "renderscript allocation load <ID> <filename>",
4829b9c1b51eSKate Stone             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
483055232f09SEwan Crawford 
4831222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
483255232f09SEwan Crawford 
4833b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
483455232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4835b9c1b51eSKate Stone     if (argc != 2) {
4836b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4837b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4838b3f7f69dSAidan Dodds           m_cmd_name.c_str());
483955232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
484055232f09SEwan Crawford       return false;
484155232f09SEwan Crawford     }
484255232f09SEwan Crawford 
4843b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4844b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4845b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
484655232f09SEwan Crawford 
484755232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
484880af0b9eSLuke Drummond     bool success = false;
4849b9c1b51eSKate Stone     const uint32_t id =
485080af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
485180af0b9eSLuke Drummond     if (!success) {
4852b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4853b9c1b51eSKate Stone                                    id_cstr);
485455232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
485555232f09SEwan Crawford       return false;
485655232f09SEwan Crawford     }
485755232f09SEwan Crawford 
485880af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
485980af0b9eSLuke Drummond     bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
486080af0b9eSLuke Drummond                                           m_exe_ctx.GetFramePtr());
486155232f09SEwan Crawford 
486280af0b9eSLuke Drummond     if (loaded)
486355232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
486455232f09SEwan Crawford     else
486555232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
486655232f09SEwan Crawford 
486755232f09SEwan Crawford     return true;
486855232f09SEwan Crawford   }
486955232f09SEwan Crawford };
487055232f09SEwan Crawford 
4871b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationSave
4872b9c1b51eSKate Stone     : public CommandObjectParsed {
487355232f09SEwan Crawford public:
4874b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationSave(
4875b9c1b51eSKate Stone       CommandInterpreter &interpreter)
4876b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript allocation save",
4877b9c1b51eSKate Stone                             "Write renderscript allocation contents to a file.",
4878b9c1b51eSKate Stone                             "renderscript allocation save <ID> <filename>",
4879b9c1b51eSKate Stone                             eCommandRequiresProcess |
4880b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
488155232f09SEwan Crawford 
4882222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
488355232f09SEwan Crawford 
4884b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
488555232f09SEwan Crawford     const size_t argc = command.GetArgumentCount();
4886b9c1b51eSKate Stone     if (argc != 2) {
4887b9c1b51eSKate Stone       result.AppendErrorWithFormat(
4888b9c1b51eSKate Stone           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4889b3f7f69dSAidan Dodds           m_cmd_name.c_str());
489055232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
489155232f09SEwan Crawford       return false;
489255232f09SEwan Crawford     }
489355232f09SEwan Crawford 
4894b3f7f69dSAidan Dodds     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4895b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4896b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
489755232f09SEwan Crawford 
489855232f09SEwan Crawford     const char *id_cstr = command.GetArgumentAtIndex(0);
489980af0b9eSLuke Drummond     bool success = false;
4900b9c1b51eSKate Stone     const uint32_t id =
490180af0b9eSLuke Drummond         StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
490280af0b9eSLuke Drummond     if (!success) {
4903b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4904b9c1b51eSKate Stone                                    id_cstr);
490555232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
490655232f09SEwan Crawford       return false;
490755232f09SEwan Crawford     }
490855232f09SEwan Crawford 
490980af0b9eSLuke Drummond     const char *path = command.GetArgumentAtIndex(1);
491080af0b9eSLuke Drummond     bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
491180af0b9eSLuke Drummond                                          m_exe_ctx.GetFramePtr());
491255232f09SEwan Crawford 
491380af0b9eSLuke Drummond     if (saved)
491455232f09SEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
491555232f09SEwan Crawford     else
491655232f09SEwan Crawford       result.SetStatus(eReturnStatusFailed);
491755232f09SEwan Crawford 
491855232f09SEwan Crawford     return true;
491955232f09SEwan Crawford   }
492055232f09SEwan Crawford };
492155232f09SEwan Crawford 
4922b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocationRefresh
4923b9c1b51eSKate Stone     : public CommandObjectParsed {
49240d2bfcfbSEwan Crawford public:
4925b9c1b51eSKate Stone   CommandObjectRenderScriptRuntimeAllocationRefresh(
4926b9c1b51eSKate Stone       CommandInterpreter &interpreter)
49270d2bfcfbSEwan Crawford       : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4928b9c1b51eSKate Stone                             "Recomputes the details of all allocations.",
4929b9c1b51eSKate Stone                             "renderscript allocation refresh",
4930b9c1b51eSKate Stone                             eCommandRequiresProcess |
4931b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
49320d2bfcfbSEwan Crawford 
49330d2bfcfbSEwan Crawford   ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
49340d2bfcfbSEwan Crawford 
4935b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
49360d2bfcfbSEwan Crawford     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4937b9c1b51eSKate Stone         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4938b9c1b51eSKate Stone             eLanguageTypeExtRenderScript));
49390d2bfcfbSEwan Crawford 
4940b9c1b51eSKate Stone     bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4941b9c1b51eSKate Stone                                                     m_exe_ctx.GetFramePtr());
49420d2bfcfbSEwan Crawford 
4943b9c1b51eSKate Stone     if (success) {
49440d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusSuccessFinishResult);
49450d2bfcfbSEwan Crawford       return true;
4946b9c1b51eSKate Stone     } else {
49470d2bfcfbSEwan Crawford       result.SetStatus(eReturnStatusFailed);
49480d2bfcfbSEwan Crawford       return false;
49490d2bfcfbSEwan Crawford     }
49500d2bfcfbSEwan Crawford   }
49510d2bfcfbSEwan Crawford };
49520d2bfcfbSEwan Crawford 
4953b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeAllocation
4954b9c1b51eSKate Stone     : public CommandObjectMultiword {
495515f2bd95SEwan Crawford public:
495615f2bd95SEwan Crawford   CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4957b9c1b51eSKate Stone       : CommandObjectMultiword(
4958b9c1b51eSKate Stone             interpreter, "renderscript allocation",
4959b9c1b51eSKate Stone             "Commands that deal with RenderScript allocations.", nullptr) {
4960b9c1b51eSKate Stone     LoadSubCommand(
4961b9c1b51eSKate Stone         "list",
4962b9c1b51eSKate Stone         CommandObjectSP(
4963b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4964b9c1b51eSKate Stone     LoadSubCommand(
4965b9c1b51eSKate Stone         "dump",
4966b9c1b51eSKate Stone         CommandObjectSP(
4967b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4968b9c1b51eSKate Stone     LoadSubCommand(
4969b9c1b51eSKate Stone         "save",
4970b9c1b51eSKate Stone         CommandObjectSP(
4971b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4972b9c1b51eSKate Stone     LoadSubCommand(
4973b9c1b51eSKate Stone         "load",
4974b9c1b51eSKate Stone         CommandObjectSP(
4975b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4976b9c1b51eSKate Stone     LoadSubCommand(
4977b9c1b51eSKate Stone         "refresh",
4978b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4979b9c1b51eSKate Stone             interpreter)));
498015f2bd95SEwan Crawford   }
498115f2bd95SEwan Crawford 
4982222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeAllocation() override = default;
498315f2bd95SEwan Crawford };
498415f2bd95SEwan Crawford 
4985b9c1b51eSKate Stone class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
49864640cde1SColin Riley public:
49874640cde1SColin Riley   CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4988b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "renderscript status",
4989b9c1b51eSKate Stone                             "Displays current RenderScript runtime status.",
4990b9c1b51eSKate Stone                             "renderscript status",
4991b9c1b51eSKate Stone                             eCommandRequiresProcess |
4992b9c1b51eSKate Stone                                 eCommandProcessMustBeLaunched) {}
49934640cde1SColin Riley 
4994222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntimeStatus() override = default;
49954640cde1SColin Riley 
4996b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
49974640cde1SColin Riley     RenderScriptRuntime *runtime =
4998b9c1b51eSKate Stone         (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4999b9c1b51eSKate Stone             eLanguageTypeExtRenderScript);
500097206d57SZachary Turner     runtime->DumpStatus(result.GetOutputStream());
50014640cde1SColin Riley     result.SetStatus(eReturnStatusSuccessFinishResult);
50024640cde1SColin Riley     return true;
50034640cde1SColin Riley   }
50044640cde1SColin Riley };
50054640cde1SColin Riley 
5006b3bbcb12SLuke Drummond class CommandObjectRenderScriptRuntimeReduction
5007b3bbcb12SLuke Drummond     : public CommandObjectMultiword {
5008b3bbcb12SLuke Drummond public:
5009b3bbcb12SLuke Drummond   CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
5010b3bbcb12SLuke Drummond       : CommandObjectMultiword(interpreter, "renderscript reduction",
5011b3bbcb12SLuke Drummond                                "Commands that handle general reduction kernels",
5012b3bbcb12SLuke Drummond                                nullptr) {
5013b3bbcb12SLuke Drummond     LoadSubCommand(
5014b3bbcb12SLuke Drummond         "breakpoint",
5015b3bbcb12SLuke Drummond         CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
5016b3bbcb12SLuke Drummond             interpreter)));
5017b3bbcb12SLuke Drummond   }
5018b3bbcb12SLuke Drummond   ~CommandObjectRenderScriptRuntimeReduction() override = default;
5019b3bbcb12SLuke Drummond };
5020b3bbcb12SLuke Drummond 
5021b9c1b51eSKate Stone class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
50225ec532a9SColin Riley public:
50235ec532a9SColin Riley   CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
5024b9c1b51eSKate Stone       : CommandObjectMultiword(
5025b9c1b51eSKate Stone             interpreter, "renderscript",
5026b9c1b51eSKate Stone             "Commands for operating on the RenderScript runtime.",
5027b9c1b51eSKate Stone             "renderscript <subcommand> [<subcommand-options>]") {
5028b9c1b51eSKate Stone     LoadSubCommand(
5029b9c1b51eSKate Stone         "module", CommandObjectSP(
5030b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeModule(interpreter)));
5031b9c1b51eSKate Stone     LoadSubCommand(
5032b9c1b51eSKate Stone         "status", CommandObjectSP(
5033b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeStatus(interpreter)));
5034b9c1b51eSKate Stone     LoadSubCommand(
5035b9c1b51eSKate Stone         "kernel", CommandObjectSP(
5036b9c1b51eSKate Stone                       new CommandObjectRenderScriptRuntimeKernel(interpreter)));
5037b9c1b51eSKate Stone     LoadSubCommand("context",
5038b9c1b51eSKate Stone                    CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
5039b9c1b51eSKate Stone                        interpreter)));
5040b9c1b51eSKate Stone     LoadSubCommand(
5041b9c1b51eSKate Stone         "allocation",
5042b9c1b51eSKate Stone         CommandObjectSP(
5043b9c1b51eSKate Stone             new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
504421fed052SAidan Dodds     LoadSubCommand("scriptgroup",
504521fed052SAidan Dodds                    NewCommandObjectRenderScriptScriptGroup(interpreter));
5046b3bbcb12SLuke Drummond     LoadSubCommand(
5047b3bbcb12SLuke Drummond         "reduction",
5048b3bbcb12SLuke Drummond         CommandObjectSP(
5049b3bbcb12SLuke Drummond             new CommandObjectRenderScriptRuntimeReduction(interpreter)));
50505ec532a9SColin Riley   }
50515ec532a9SColin Riley 
5052222b937cSEugene Zelenko   ~CommandObjectRenderScriptRuntime() override = default;
50535ec532a9SColin Riley };
5054ef20b08fSColin Riley 
5055b9c1b51eSKate Stone void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
5056ef20b08fSColin Riley 
5057ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
5058b9c1b51eSKate Stone     : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
5059b9c1b51eSKate Stone       m_debuggerPresentFlagged(false), m_breakAllKernels(false),
5060b9c1b51eSKate Stone       m_ir_passes(nullptr) {
50614640cde1SColin Riley   ModulesDidLoad(process->GetTarget().GetImages());
5062ef20b08fSColin Riley }
50634640cde1SColin Riley 
5064b9c1b51eSKate Stone lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
5065b9c1b51eSKate Stone     lldb_private::CommandInterpreter &interpreter) {
50660a66e2f1SEnrico Granata   return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
50674640cde1SColin Riley }
50684640cde1SColin Riley 
506978f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
5070