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
13222b937cSEugene Zelenko // Project includes
145ec532a9SColin Riley #include "RenderScriptRuntime.h"
155ec532a9SColin Riley 
16b3f7f69dSAidan Dodds #include "lldb/Breakpoint/StoppointCallbackContext.h"
175ec532a9SColin Riley #include "lldb/Core/ConstString.h"
185ec532a9SColin Riley #include "lldb/Core/Debugger.h"
195ec532a9SColin Riley #include "lldb/Core/Error.h"
205ec532a9SColin Riley #include "lldb/Core/Log.h"
215ec532a9SColin Riley #include "lldb/Core/PluginManager.h"
22018f5a7eSEwan Crawford #include "lldb/Core/RegularExpression.h"
23b3f7f69dSAidan Dodds #include "lldb/Core/ValueObjectVariable.h"
248b244e21SEwan Crawford #include "lldb/DataFormatters/DumpValueObjectOptions.h"
25b3f7f69dSAidan Dodds #include "lldb/Expression/UserExpression.h"
26a0f08674SEwan Crawford #include "lldb/Host/StringConvert.h"
27b3f7f69dSAidan Dodds #include "lldb/Interpreter/Args.h"
28b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandInterpreter.h"
29b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandObjectMultiword.h"
30b3f7f69dSAidan Dodds #include "lldb/Interpreter/CommandReturnObject.h"
31b3f7f69dSAidan Dodds #include "lldb/Interpreter/Options.h"
325ec532a9SColin Riley #include "lldb/Symbol/Symbol.h"
334640cde1SColin Riley #include "lldb/Symbol/Type.h"
34b3f7f69dSAidan Dodds #include "lldb/Symbol/VariableList.h"
355ec532a9SColin Riley #include "lldb/Target/Process.h"
36b3f7f69dSAidan Dodds #include "lldb/Target/RegisterContext.h"
375ec532a9SColin Riley #include "lldb/Target/Target.h"
38018f5a7eSEwan Crawford #include "lldb/Target/Thread.h"
395ec532a9SColin Riley 
405ec532a9SColin Riley using namespace lldb;
415ec532a9SColin Riley using namespace lldb_private;
4298156583SEwan Crawford using namespace lldb_renderscript;
435ec532a9SColin Riley 
44b3f7f69dSAidan Dodds namespace
45b3f7f69dSAidan Dodds {
4678f339d1SEwan Crawford 
4778f339d1SEwan Crawford // The empirical_type adds a basic level of validation to arbitrary data
4878f339d1SEwan Crawford // allowing us to track if data has been discovered and stored or not.
4978f339d1SEwan Crawford // An empirical_type will be marked as valid only if it has been explicitly assigned to.
50b3f7f69dSAidan Dodds template <typename type_t> class empirical_type
5178f339d1SEwan Crawford {
5278f339d1SEwan Crawford public:
5378f339d1SEwan Crawford     // Ctor. Contents is invalid when constructed.
54b3f7f69dSAidan Dodds     empirical_type() : valid(false) {}
5578f339d1SEwan Crawford 
5678f339d1SEwan Crawford     // Return true and copy contents to out if valid, else return false.
57b3f7f69dSAidan Dodds     bool
58b3f7f69dSAidan Dodds     get(type_t &out) const
5978f339d1SEwan Crawford     {
6078f339d1SEwan Crawford         if (valid)
6178f339d1SEwan Crawford             out = data;
6278f339d1SEwan Crawford         return valid;
6378f339d1SEwan Crawford     }
6478f339d1SEwan Crawford 
6578f339d1SEwan Crawford     // Return a pointer to the contents or nullptr if it was not valid.
66b3f7f69dSAidan Dodds     const type_t *
67b3f7f69dSAidan Dodds     get() const
6878f339d1SEwan Crawford     {
6978f339d1SEwan Crawford         return valid ? &data : nullptr;
7078f339d1SEwan Crawford     }
7178f339d1SEwan Crawford 
7278f339d1SEwan Crawford     // Assign data explicitly.
73b3f7f69dSAidan Dodds     void
74b3f7f69dSAidan Dodds     set(const type_t in)
7578f339d1SEwan Crawford     {
7678f339d1SEwan Crawford         data = in;
7778f339d1SEwan Crawford         valid = true;
7878f339d1SEwan Crawford     }
7978f339d1SEwan Crawford 
8078f339d1SEwan Crawford     // Mark contents as invalid.
81b3f7f69dSAidan Dodds     void
82b3f7f69dSAidan Dodds     invalidate()
8378f339d1SEwan Crawford     {
8478f339d1SEwan Crawford         valid = false;
8578f339d1SEwan Crawford     }
8678f339d1SEwan Crawford 
8778f339d1SEwan Crawford     // Returns true if this type contains valid data.
88b3f7f69dSAidan Dodds     bool
89b3f7f69dSAidan Dodds     isValid() const
9078f339d1SEwan Crawford     {
9178f339d1SEwan Crawford         return valid;
9278f339d1SEwan Crawford     }
9378f339d1SEwan Crawford 
9478f339d1SEwan Crawford     // Assignment operator.
95b3f7f69dSAidan Dodds     empirical_type<type_t> &
96b3f7f69dSAidan Dodds     operator=(const type_t in)
9778f339d1SEwan Crawford     {
9878f339d1SEwan Crawford         set(in);
9978f339d1SEwan Crawford         return *this;
10078f339d1SEwan Crawford     }
10178f339d1SEwan Crawford 
10278f339d1SEwan Crawford     // Dereference operator returns contents.
10378f339d1SEwan Crawford     // Warning: Will assert if not valid so use only when you know data is valid.
10478f339d1SEwan Crawford     const type_t &operator*() const
10578f339d1SEwan Crawford     {
10678f339d1SEwan Crawford         assert(valid);
10778f339d1SEwan Crawford         return data;
10878f339d1SEwan Crawford     }
10978f339d1SEwan Crawford 
11078f339d1SEwan Crawford protected:
11178f339d1SEwan Crawford     bool valid;
11278f339d1SEwan Crawford     type_t data;
11378f339d1SEwan Crawford };
11478f339d1SEwan Crawford 
115f4786785SAidan Dodds // ArgItem is used by the GetArgs() function when reading function arguments from the target.
116f4786785SAidan Dodds struct ArgItem
117f4786785SAidan Dodds {
118f4786785SAidan Dodds     enum
119f4786785SAidan Dodds     {
120f4786785SAidan Dodds         ePointer,
121f4786785SAidan Dodds         eInt32,
122f4786785SAidan Dodds         eInt64,
123f4786785SAidan Dodds         eLong,
124f4786785SAidan Dodds         eBool
125f4786785SAidan Dodds     } type;
126f4786785SAidan Dodds 
127f4786785SAidan Dodds     uint64_t value;
128f4786785SAidan Dodds 
129f4786785SAidan Dodds     explicit operator uint64_t() const { return value; }
130f4786785SAidan Dodds };
131f4786785SAidan Dodds 
132f4786785SAidan Dodds // Context structure to be passed into GetArgsXXX(), argument reading functions below.
133f4786785SAidan Dodds struct GetArgsCtx
134f4786785SAidan Dodds {
135f4786785SAidan Dodds     RegisterContext *reg_ctx;
136f4786785SAidan Dodds     Process *process;
137f4786785SAidan Dodds };
138f4786785SAidan Dodds 
139f4786785SAidan Dodds bool
140f4786785SAidan Dodds GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
141f4786785SAidan Dodds {
142f4786785SAidan Dodds     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
143f4786785SAidan Dodds 
14467dc3e15SAidan Dodds     Error error;
14567dc3e15SAidan Dodds 
146f4786785SAidan Dodds     // get the current stack pointer
147f4786785SAidan Dodds     uint64_t sp = ctx.reg_ctx->GetSP();
148f4786785SAidan Dodds 
149f4786785SAidan Dodds     for (size_t i = 0; i < num_args; ++i)
150f4786785SAidan Dodds     {
151f4786785SAidan Dodds         ArgItem &arg = arg_list[i];
152f4786785SAidan Dodds         // advance up the stack by one argument
153f4786785SAidan Dodds         sp += sizeof(uint32_t);
154f4786785SAidan Dodds         // get the argument type size
155f4786785SAidan Dodds         size_t arg_size = sizeof(uint32_t);
156f4786785SAidan Dodds         // read the argument from memory
157f4786785SAidan Dodds         arg.value = 0;
158f4786785SAidan Dodds         Error error;
159f4786785SAidan Dodds         size_t read = ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), error);
160f4786785SAidan Dodds         if (read != arg_size || !error.Success())
161f4786785SAidan Dodds         {
162f4786785SAidan Dodds             if (log)
163f4786785SAidan Dodds                 log->Printf("%s - error reading argument: %" PRIu64 " '%s'", __FUNCTION__, uint64_t(i),
164f4786785SAidan Dodds                             error.AsCString());
165f4786785SAidan Dodds             return false;
166f4786785SAidan Dodds         }
167f4786785SAidan Dodds     }
168f4786785SAidan Dodds     return true;
169f4786785SAidan Dodds }
170f4786785SAidan Dodds 
171f4786785SAidan Dodds bool
172f4786785SAidan Dodds GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
173f4786785SAidan Dodds {
174f4786785SAidan Dodds     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
175f4786785SAidan Dodds 
176f4786785SAidan Dodds     // number of arguments passed in registers
177f4786785SAidan Dodds     static const uint32_t c_args_in_reg = 6;
178f4786785SAidan Dodds     // register passing order
1791ee07253SSaleem Abdulrasool     static const std::array<const char *, c_args_in_reg> c_reg_names{{"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
180f4786785SAidan Dodds     // argument type to size mapping
1811ee07253SSaleem Abdulrasool     static const std::array<size_t, 5> arg_size{{
182f4786785SAidan Dodds         8, // ePointer,
183f4786785SAidan Dodds         4, // eInt32,
184f4786785SAidan Dodds         8, // eInt64,
185f4786785SAidan Dodds         8, // eLong,
186f4786785SAidan Dodds         4, // eBool,
1871ee07253SSaleem Abdulrasool     }};
188f4786785SAidan Dodds 
18917e07c0aSAidan Dodds     Error error;
19017e07c0aSAidan Dodds 
191f4786785SAidan Dodds     // get the current stack pointer
192f4786785SAidan Dodds     uint64_t sp = ctx.reg_ctx->GetSP();
193f4786785SAidan Dodds     // step over the return address
194f4786785SAidan Dodds     sp += sizeof(uint64_t);
195f4786785SAidan Dodds 
196f4786785SAidan Dodds     // check the stack alignment was correct (16 byte aligned)
197f4786785SAidan Dodds     if ((sp & 0xf) != 0x0)
198f4786785SAidan Dodds     {
199f4786785SAidan Dodds         if (log)
200f4786785SAidan Dodds             log->Printf("%s - stack misaligned", __FUNCTION__);
201f4786785SAidan Dodds         return false;
202f4786785SAidan Dodds     }
203f4786785SAidan Dodds 
204f4786785SAidan Dodds     // find the start of arguments on the stack
205f4786785SAidan Dodds     uint64_t sp_offset = 0;
206f4786785SAidan Dodds     for (uint32_t i = c_args_in_reg; i < num_args; ++i)
207f4786785SAidan Dodds     {
208f4786785SAidan Dodds         sp_offset += arg_size[arg_list[i].type];
209f4786785SAidan Dodds     }
210f4786785SAidan Dodds     // round up to multiple of 16
211f4786785SAidan Dodds     sp_offset = (sp_offset + 0xf) & 0xf;
212f4786785SAidan Dodds     sp += sp_offset;
213f4786785SAidan Dodds 
214f4786785SAidan Dodds     for (size_t i = 0; i < num_args; ++i)
215f4786785SAidan Dodds     {
216f4786785SAidan Dodds         bool success = false;
217f4786785SAidan Dodds         ArgItem &arg = arg_list[i];
218f4786785SAidan Dodds         // arguments passed in registers
219f4786785SAidan Dodds         if (i < c_args_in_reg)
220f4786785SAidan Dodds         {
221f4786785SAidan Dodds             const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoByName(c_reg_names[i]);
222f4786785SAidan Dodds             RegisterValue rVal;
223f4786785SAidan Dodds             if (ctx.reg_ctx->ReadRegister(rArg, rVal))
224f4786785SAidan Dodds                 arg.value = rVal.GetAsUInt64(0, &success);
225f4786785SAidan Dodds         }
226f4786785SAidan Dodds         // arguments passed on the stack
227f4786785SAidan Dodds         else
228f4786785SAidan Dodds         {
229f4786785SAidan Dodds             // get the argument type size
230f4786785SAidan Dodds             const size_t size = arg_size[arg_list[i].type];
231f4786785SAidan Dodds             // read the argument from memory
232f4786785SAidan Dodds             arg.value = 0;
233f4786785SAidan Dodds             // note: due to little endian layout reading 4 or 8 bytes will give the correct value.
234f4786785SAidan Dodds             size_t read = ctx.process->ReadMemory(sp, &arg.value, size, error);
235f4786785SAidan Dodds             success = (error.Success() && read==size);
236f4786785SAidan Dodds             // advance past this argument
237f4786785SAidan Dodds             sp -= size;
238f4786785SAidan Dodds         }
239f4786785SAidan Dodds         // fail if we couldn't read this argument
240f4786785SAidan Dodds         if (!success)
241f4786785SAidan Dodds         {
242f4786785SAidan Dodds             if (log)
24317e07c0aSAidan Dodds                 log->Printf("%s - error reading argument: %" PRIu64", reason: %s",
24417e07c0aSAidan Dodds                             __FUNCTION__, uint64_t(i), error.AsCString("n/a"));
245f4786785SAidan Dodds             return false;
246f4786785SAidan Dodds         }
247f4786785SAidan Dodds     }
248f4786785SAidan Dodds     return true;
249f4786785SAidan Dodds }
250f4786785SAidan Dodds 
251f4786785SAidan Dodds bool
252f4786785SAidan Dodds GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
253f4786785SAidan Dodds {
254f4786785SAidan Dodds     // number of arguments passed in registers
255f4786785SAidan Dodds     static const uint32_t c_args_in_reg = 4;
256f4786785SAidan Dodds 
257f4786785SAidan Dodds     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
258f4786785SAidan Dodds 
25917e07c0aSAidan Dodds     Error error;
26017e07c0aSAidan Dodds 
261f4786785SAidan Dodds     // get the current stack pointer
262f4786785SAidan Dodds     uint64_t sp = ctx.reg_ctx->GetSP();
263f4786785SAidan Dodds 
264f4786785SAidan Dodds     for (size_t i = 0; i < num_args; ++i)
265f4786785SAidan Dodds     {
266f4786785SAidan Dodds         bool success = false;
267f4786785SAidan Dodds         ArgItem &arg = arg_list[i];
268f4786785SAidan Dodds         // arguments passed in registers
269f4786785SAidan Dodds         if (i < c_args_in_reg)
270f4786785SAidan Dodds         {
271f4786785SAidan Dodds             const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
272f4786785SAidan Dodds             RegisterValue rVal;
273f4786785SAidan Dodds             if (ctx.reg_ctx->ReadRegister(rArg, rVal))
274f4786785SAidan Dodds                 arg.value = rVal.GetAsUInt32(0, &success);
275f4786785SAidan Dodds         }
276f4786785SAidan Dodds         // arguments passed on the stack
277f4786785SAidan Dodds         else
278f4786785SAidan Dodds         {
279f4786785SAidan Dodds             // get the argument type size
280f4786785SAidan Dodds             const size_t arg_size = sizeof(uint32_t);
281f4786785SAidan Dodds             // clear all 64bits
282f4786785SAidan Dodds             arg.value = 0;
283f4786785SAidan Dodds             // read this argument from memory
284f4786785SAidan Dodds             size_t bytes_read = ctx.process->ReadMemory(sp, &arg.value, arg_size, error);
285f4786785SAidan Dodds             success = (error.Success() && bytes_read == arg_size);
286f4786785SAidan Dodds             // advance the stack pointer
287f4786785SAidan Dodds             sp += sizeof(uint32_t);
288f4786785SAidan Dodds         }
289f4786785SAidan Dodds         // fail if we couldn't read this argument
290f4786785SAidan Dodds         if (!success)
291f4786785SAidan Dodds         {
292f4786785SAidan Dodds             if (log)
29317e07c0aSAidan Dodds                 log->Printf("%s - error reading argument: %" PRIu64", reason: %s",
29417e07c0aSAidan Dodds                             __FUNCTION__, uint64_t(i), error.AsCString("n/a"));
295f4786785SAidan Dodds             return false;
296f4786785SAidan Dodds         }
297f4786785SAidan Dodds     }
298f4786785SAidan Dodds     return true;
299f4786785SAidan Dodds }
300f4786785SAidan Dodds 
301f4786785SAidan Dodds bool
302f4786785SAidan Dodds GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
303f4786785SAidan Dodds {
304f4786785SAidan Dodds     // number of arguments passed in registers
305f4786785SAidan Dodds     static const uint32_t c_args_in_reg = 8;
306f4786785SAidan Dodds 
307f4786785SAidan Dodds     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
308f4786785SAidan Dodds 
309f4786785SAidan Dodds     for (size_t i = 0; i < num_args; ++i)
310f4786785SAidan Dodds     {
311f4786785SAidan Dodds         bool success = false;
312f4786785SAidan Dodds         ArgItem &arg = arg_list[i];
313f4786785SAidan Dodds         // arguments passed in registers
314f4786785SAidan Dodds         if (i < c_args_in_reg)
315f4786785SAidan Dodds         {
316f4786785SAidan Dodds             const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
317f4786785SAidan Dodds             RegisterValue rVal;
318f4786785SAidan Dodds             if (ctx.reg_ctx->ReadRegister(rArg, rVal))
319f4786785SAidan Dodds                 arg.value = rVal.GetAsUInt64(0, &success);
320f4786785SAidan Dodds         }
321f4786785SAidan Dodds         // arguments passed on the stack
322f4786785SAidan Dodds         else
323f4786785SAidan Dodds         {
324f4786785SAidan Dodds             if (log)
325f4786785SAidan Dodds                 log->Printf("%s - reading arguments spilled to stack not implemented", __FUNCTION__);
326f4786785SAidan Dodds         }
327f4786785SAidan Dodds         // fail if we couldn't read this argument
328f4786785SAidan Dodds         if (!success)
329f4786785SAidan Dodds         {
330f4786785SAidan Dodds             if (log)
331f4786785SAidan Dodds                 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__,
332f4786785SAidan Dodds                             uint64_t(i));
333f4786785SAidan Dodds             return false;
334f4786785SAidan Dodds         }
335f4786785SAidan Dodds     }
336f4786785SAidan Dodds     return true;
337f4786785SAidan Dodds }
338f4786785SAidan Dodds 
339f4786785SAidan Dodds bool
340f4786785SAidan Dodds GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
341f4786785SAidan Dodds {
342f4786785SAidan Dodds     // number of arguments passed in registers
343f4786785SAidan Dodds     static const uint32_t c_args_in_reg = 4;
344f4786785SAidan Dodds     // register file offset to first argument
345f4786785SAidan Dodds     static const uint32_t c_reg_offset = 4;
346f4786785SAidan Dodds 
347f4786785SAidan Dodds     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
348f4786785SAidan Dodds 
34917e07c0aSAidan Dodds     Error error;
35017e07c0aSAidan Dodds 
35117e07c0aSAidan Dodds     // find offset to arguments on the stack (+16 to skip over a0-a3 shadow space)
35217e07c0aSAidan Dodds     uint64_t sp = ctx.reg_ctx->GetSP() + 16;
35317e07c0aSAidan Dodds 
354f4786785SAidan Dodds     for (size_t i = 0; i < num_args; ++i)
355f4786785SAidan Dodds     {
356f4786785SAidan Dodds         bool success = false;
357f4786785SAidan Dodds         ArgItem &arg = arg_list[i];
358f4786785SAidan Dodds         // arguments passed in registers
359f4786785SAidan Dodds         if (i < c_args_in_reg)
360f4786785SAidan Dodds         {
361f4786785SAidan Dodds             const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i + c_reg_offset);
362f4786785SAidan Dodds             RegisterValue rVal;
363f4786785SAidan Dodds             if (ctx.reg_ctx->ReadRegister(rArg, rVal))
364f4786785SAidan Dodds                 arg.value = rVal.GetAsUInt64(0, &success);
365f4786785SAidan Dodds         }
366f4786785SAidan Dodds         // arguments passed on the stack
367f4786785SAidan Dodds         else
368f4786785SAidan Dodds         {
3696dd4b579SAidan Dodds             const size_t arg_size = sizeof(uint32_t);
3706dd4b579SAidan Dodds             arg.value = 0;
37167dc3e15SAidan Dodds             size_t bytes_read = ctx.process->ReadMemory(sp, &arg.value, arg_size, error);
3726dd4b579SAidan Dodds             success = (error.Success() && bytes_read == arg_size);
37367dc3e15SAidan Dodds             // advance the stack pointer
37467dc3e15SAidan Dodds             sp += arg_size;
375f4786785SAidan Dodds         }
376f4786785SAidan Dodds         // fail if we couldn't read this argument
377f4786785SAidan Dodds         if (!success)
378f4786785SAidan Dodds         {
379f4786785SAidan Dodds             if (log)
38067dc3e15SAidan Dodds                 log->Printf("%s - error reading argument: %" PRIu64", reason: %s",
38167dc3e15SAidan Dodds                             __FUNCTION__, uint64_t(i), error.AsCString("n/a"));
382f4786785SAidan Dodds             return false;
383f4786785SAidan Dodds         }
384f4786785SAidan Dodds     }
385f4786785SAidan Dodds     return true;
386f4786785SAidan Dodds }
387f4786785SAidan Dodds 
388f4786785SAidan Dodds bool
389f4786785SAidan Dodds GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
390f4786785SAidan Dodds {
391f4786785SAidan Dodds     // number of arguments passed in registers
392f4786785SAidan Dodds     static const uint32_t c_args_in_reg = 8;
393f4786785SAidan Dodds     // register file offset to first argument
394f4786785SAidan Dodds     static const uint32_t c_reg_offset = 4;
395f4786785SAidan Dodds 
396f4786785SAidan Dodds     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
397f4786785SAidan Dodds 
39817e07c0aSAidan Dodds     Error error;
39917e07c0aSAidan Dodds 
400f4786785SAidan Dodds     // get the current stack pointer
401f4786785SAidan Dodds     uint64_t sp = ctx.reg_ctx->GetSP();
402f4786785SAidan Dodds 
403f4786785SAidan Dodds     for (size_t i = 0; i < num_args; ++i)
404f4786785SAidan Dodds     {
405f4786785SAidan Dodds         bool success = false;
406f4786785SAidan Dodds         ArgItem &arg = arg_list[i];
407f4786785SAidan Dodds         // arguments passed in registers
408f4786785SAidan Dodds         if (i < c_args_in_reg)
409f4786785SAidan Dodds         {
410f4786785SAidan Dodds             const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i + c_reg_offset);
411f4786785SAidan Dodds             RegisterValue rVal;
412f4786785SAidan Dodds             if (ctx.reg_ctx->ReadRegister(rArg, rVal))
41372f77525SAidan Dodds                 arg.value = rVal.GetAsUInt64(0, &success);
414f4786785SAidan Dodds         }
415f4786785SAidan Dodds         // arguments passed on the stack
416f4786785SAidan Dodds         else
417f4786785SAidan Dodds         {
418f4786785SAidan Dodds             // get the argument type size
419f4786785SAidan Dodds             const size_t arg_size = sizeof(uint64_t);
420f4786785SAidan Dodds             // clear all 64bits
421f4786785SAidan Dodds             arg.value = 0;
422f4786785SAidan Dodds             // read this argument from memory
423f4786785SAidan Dodds             size_t bytes_read = ctx.process->ReadMemory(sp, &arg.value, arg_size, error);
424f4786785SAidan Dodds             success = (error.Success() && bytes_read == arg_size);
425f4786785SAidan Dodds             // advance the stack pointer
426f4786785SAidan Dodds             sp += arg_size;
427f4786785SAidan Dodds         }
428f4786785SAidan Dodds         // fail if we couldn't read this argument
429f4786785SAidan Dodds         if (!success)
430f4786785SAidan Dodds         {
431f4786785SAidan Dodds             if (log)
43217e07c0aSAidan Dodds                 log->Printf("%s - error reading argument: %" PRIu64", reason: %s",
43317e07c0aSAidan Dodds                             __FUNCTION__, uint64_t(i), error.AsCString("n/a"));
434f4786785SAidan Dodds             return false;
435f4786785SAidan Dodds         }
436f4786785SAidan Dodds     }
437f4786785SAidan Dodds     return true;
438f4786785SAidan Dodds }
439f4786785SAidan Dodds 
440f4786785SAidan Dodds bool
441f4786785SAidan Dodds GetArgs(ExecutionContext &context, ArgItem *arg_list, size_t num_args)
442f4786785SAidan Dodds {
443f4786785SAidan Dodds     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
444f4786785SAidan Dodds 
445f4786785SAidan Dodds     // verify that we have a target
446f4786785SAidan Dodds     if (!context.GetTargetPtr())
447f4786785SAidan Dodds     {
448f4786785SAidan Dodds         if (log)
449f4786785SAidan Dodds             log->Printf("%s - invalid target", __FUNCTION__);
450f4786785SAidan Dodds         return false;
451f4786785SAidan Dodds     }
452f4786785SAidan Dodds 
453f4786785SAidan Dodds     GetArgsCtx ctx = {context.GetRegisterContext(), context.GetProcessPtr()};
454f4786785SAidan Dodds     assert(ctx.reg_ctx && ctx.process);
455f4786785SAidan Dodds 
456f4786785SAidan Dodds     // dispatch based on architecture
457f4786785SAidan Dodds     switch (context.GetTargetPtr()->GetArchitecture().GetMachine())
458f4786785SAidan Dodds     {
459f4786785SAidan Dodds         case llvm::Triple::ArchType::x86:
460f4786785SAidan Dodds             return GetArgsX86(ctx, arg_list, num_args);
461f4786785SAidan Dodds 
462f4786785SAidan Dodds         case llvm::Triple::ArchType::x86_64:
463f4786785SAidan Dodds             return GetArgsX86_64(ctx, arg_list, num_args);
464f4786785SAidan Dodds 
465f4786785SAidan Dodds         case llvm::Triple::ArchType::arm:
466f4786785SAidan Dodds             return GetArgsArm(ctx, arg_list, num_args);
467f4786785SAidan Dodds 
468f4786785SAidan Dodds         case llvm::Triple::ArchType::aarch64:
469f4786785SAidan Dodds             return GetArgsAarch64(ctx, arg_list, num_args);
470f4786785SAidan Dodds 
471f4786785SAidan Dodds         case llvm::Triple::ArchType::mipsel:
472f4786785SAidan Dodds             return GetArgsMipsel(ctx, arg_list, num_args);
473f4786785SAidan Dodds 
474f4786785SAidan Dodds         case llvm::Triple::ArchType::mips64el:
475f4786785SAidan Dodds             return GetArgsMips64el(ctx, arg_list, num_args);
476f4786785SAidan Dodds 
477f4786785SAidan Dodds         default:
478f4786785SAidan Dodds             // unsupported architecture
479f4786785SAidan Dodds             if (log)
480f4786785SAidan Dodds             {
481f4786785SAidan Dodds                 log->Printf("%s - architecture not supported: '%s'", __FUNCTION__,
482f4786785SAidan Dodds                             context.GetTargetRef().GetArchitecture().GetArchitectureName());
483f4786785SAidan Dodds             }
484f4786785SAidan Dodds             return false;
485f4786785SAidan Dodds     }
486f4786785SAidan Dodds }
487222b937cSEugene Zelenko } // anonymous namespace
48878f339d1SEwan Crawford 
48978f339d1SEwan Crawford // The ScriptDetails class collects data associated with a single script instance.
49078f339d1SEwan Crawford struct RenderScriptRuntime::ScriptDetails
49178f339d1SEwan Crawford {
492222b937cSEugene Zelenko     ~ScriptDetails() = default;
49378f339d1SEwan Crawford 
49478f339d1SEwan Crawford     enum ScriptType
49578f339d1SEwan Crawford     {
49678f339d1SEwan Crawford         eScript,
49778f339d1SEwan Crawford         eScriptC
49878f339d1SEwan Crawford     };
49978f339d1SEwan Crawford 
50078f339d1SEwan Crawford     // The derived type of the script.
50178f339d1SEwan Crawford     empirical_type<ScriptType> type;
50278f339d1SEwan Crawford     // The name of the original source file.
50378f339d1SEwan Crawford     empirical_type<std::string> resName;
50478f339d1SEwan Crawford     // Path to script .so file on the device.
50578f339d1SEwan Crawford     empirical_type<std::string> scriptDyLib;
50678f339d1SEwan Crawford     // Directory where kernel objects are cached on device.
50778f339d1SEwan Crawford     empirical_type<std::string> cacheDir;
50878f339d1SEwan Crawford     // Pointer to the context which owns this script.
50978f339d1SEwan Crawford     empirical_type<lldb::addr_t> context;
51078f339d1SEwan Crawford     // Pointer to the script object itself.
51178f339d1SEwan Crawford     empirical_type<lldb::addr_t> script;
51278f339d1SEwan Crawford };
51378f339d1SEwan Crawford 
5148b244e21SEwan Crawford // This Element class represents the Element object in RS,
5158b244e21SEwan Crawford // defining the type associated with an Allocation.
5168b244e21SEwan Crawford struct RenderScriptRuntime::Element
51778f339d1SEwan Crawford {
51815f2bd95SEwan Crawford     // Taken from rsDefines.h
51915f2bd95SEwan Crawford     enum DataKind
52015f2bd95SEwan Crawford     {
52115f2bd95SEwan Crawford         RS_KIND_USER,
52215f2bd95SEwan Crawford         RS_KIND_PIXEL_L = 7,
52315f2bd95SEwan Crawford         RS_KIND_PIXEL_A,
52415f2bd95SEwan Crawford         RS_KIND_PIXEL_LA,
52515f2bd95SEwan Crawford         RS_KIND_PIXEL_RGB,
52615f2bd95SEwan Crawford         RS_KIND_PIXEL_RGBA,
52715f2bd95SEwan Crawford         RS_KIND_PIXEL_DEPTH,
52815f2bd95SEwan Crawford         RS_KIND_PIXEL_YUV,
52915f2bd95SEwan Crawford         RS_KIND_INVALID = 100
53015f2bd95SEwan Crawford     };
53178f339d1SEwan Crawford 
53215f2bd95SEwan Crawford     // Taken from rsDefines.h
53378f339d1SEwan Crawford     enum DataType
53478f339d1SEwan Crawford     {
53515f2bd95SEwan Crawford         RS_TYPE_NONE = 0,
53615f2bd95SEwan Crawford         RS_TYPE_FLOAT_16,
53715f2bd95SEwan Crawford         RS_TYPE_FLOAT_32,
53815f2bd95SEwan Crawford         RS_TYPE_FLOAT_64,
53915f2bd95SEwan Crawford         RS_TYPE_SIGNED_8,
54015f2bd95SEwan Crawford         RS_TYPE_SIGNED_16,
54115f2bd95SEwan Crawford         RS_TYPE_SIGNED_32,
54215f2bd95SEwan Crawford         RS_TYPE_SIGNED_64,
54315f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_8,
54415f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_16,
54515f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_32,
54615f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_64,
5472e920715SEwan Crawford         RS_TYPE_BOOLEAN,
5482e920715SEwan Crawford 
5492e920715SEwan Crawford         RS_TYPE_UNSIGNED_5_6_5,
5502e920715SEwan Crawford         RS_TYPE_UNSIGNED_5_5_5_1,
5512e920715SEwan Crawford         RS_TYPE_UNSIGNED_4_4_4_4,
5522e920715SEwan Crawford 
5532e920715SEwan Crawford         RS_TYPE_MATRIX_4X4,
5542e920715SEwan Crawford         RS_TYPE_MATRIX_3X3,
5552e920715SEwan Crawford         RS_TYPE_MATRIX_2X2,
5562e920715SEwan Crawford 
5572e920715SEwan Crawford         RS_TYPE_ELEMENT = 1000,
5582e920715SEwan Crawford         RS_TYPE_TYPE,
5592e920715SEwan Crawford         RS_TYPE_ALLOCATION,
5602e920715SEwan Crawford         RS_TYPE_SAMPLER,
5612e920715SEwan Crawford         RS_TYPE_SCRIPT,
5622e920715SEwan Crawford         RS_TYPE_MESH,
5632e920715SEwan Crawford         RS_TYPE_PROGRAM_FRAGMENT,
5642e920715SEwan Crawford         RS_TYPE_PROGRAM_VERTEX,
5652e920715SEwan Crawford         RS_TYPE_PROGRAM_RASTER,
5662e920715SEwan Crawford         RS_TYPE_PROGRAM_STORE,
5672e920715SEwan Crawford         RS_TYPE_FONT,
5682e920715SEwan Crawford 
5692e920715SEwan Crawford         RS_TYPE_INVALID = 10000
57078f339d1SEwan Crawford     };
57178f339d1SEwan Crawford 
5728b244e21SEwan Crawford     std::vector<Element> children;            // Child Element fields for structs
5738b244e21SEwan Crawford     empirical_type<lldb::addr_t> element_ptr; // Pointer to the RS Element of the Type
5748b244e21SEwan Crawford     empirical_type<DataType> type;            // Type of each data pointer stored by the allocation
5758b244e21SEwan Crawford     empirical_type<DataKind> type_kind;       // Defines pixel type if Allocation is created from an image
5768b244e21SEwan Crawford     empirical_type<uint32_t> type_vec_size;   // Vector size of each data point, e.g '4' for uchar4
5778b244e21SEwan Crawford     empirical_type<uint32_t> field_count;     // Number of Subelements
5788b244e21SEwan Crawford     empirical_type<uint32_t> datum_size;      // Size of a single Element with padding
5798b244e21SEwan Crawford     empirical_type<uint32_t> padding;         // Number of padding bytes
5808b244e21SEwan Crawford     empirical_type<uint32_t> array_size;      // Number of items in array, only needed for strucrs
5818b244e21SEwan Crawford     ConstString type_name;                    // Name of type, only needed for structs
5828b244e21SEwan Crawford 
583b3f7f69dSAidan Dodds     static const ConstString &
584b3f7f69dSAidan Dodds     GetFallbackStructName(); // Print this as the type name of a struct Element
5858b244e21SEwan Crawford                              // If we can't resolve the actual struct name
5868b59062aSEwan Crawford 
587b3f7f69dSAidan Dodds     bool
588b3f7f69dSAidan Dodds     shouldRefresh() const
5898b59062aSEwan Crawford     {
5908b59062aSEwan Crawford         const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
5918b59062aSEwan Crawford         const bool valid_type = type.isValid() && type_vec_size.isValid() && type_kind.isValid();
5928b59062aSEwan Crawford         return !valid_ptr || !valid_type || !datum_size.isValid();
5938b59062aSEwan Crawford     }
5948b244e21SEwan Crawford };
5958b244e21SEwan Crawford 
5968b244e21SEwan Crawford // This AllocationDetails class collects data associated with a single
5978b244e21SEwan Crawford // allocation instance.
5988b244e21SEwan Crawford struct RenderScriptRuntime::AllocationDetails
5998b244e21SEwan Crawford {
60015f2bd95SEwan Crawford     struct Dimension
60178f339d1SEwan Crawford     {
60215f2bd95SEwan Crawford         uint32_t dim_1;
60315f2bd95SEwan Crawford         uint32_t dim_2;
60415f2bd95SEwan Crawford         uint32_t dim_3;
60515f2bd95SEwan Crawford         uint32_t cubeMap;
60615f2bd95SEwan Crawford 
60715f2bd95SEwan Crawford         Dimension()
60815f2bd95SEwan Crawford         {
60915f2bd95SEwan Crawford             dim_1 = 0;
61015f2bd95SEwan Crawford             dim_2 = 0;
61115f2bd95SEwan Crawford             dim_3 = 0;
61215f2bd95SEwan Crawford             cubeMap = 0;
61315f2bd95SEwan Crawford         }
61478f339d1SEwan Crawford     };
61578f339d1SEwan Crawford 
61626e52a70SEwan Crawford     // The FileHeader struct specifies the header we use for writing allocations to a binary file.
61726e52a70SEwan Crawford     // Our format begins with the ASCII characters "RSAD", identifying the file as an allocation dump.
61826e52a70SEwan Crawford     // Member variables dims and hdr_size are then written consecutively, immediately followed by an instance of
61926e52a70SEwan Crawford     // the ElementHeader struct. Because Elements can contain subelements, there may be more than one instance
62026e52a70SEwan Crawford     // of the ElementHeader struct. With this first instance being the root element, and the other instances being
62126e52a70SEwan Crawford     // the root's descendants. To identify which instances are an ElementHeader's children, each struct
62226e52a70SEwan Crawford     // is immediately followed by a sequence of consecutive offsets to the start of its child structs.
62326e52a70SEwan Crawford     // These offsets are 4 bytes in size, and the 0 offset signifies no more children.
62455232f09SEwan Crawford     struct FileHeader
62555232f09SEwan Crawford     {
62655232f09SEwan Crawford         uint8_t ident[4];  // ASCII 'RSAD' identifying the file
62726e52a70SEwan Crawford         uint32_t dims[3];  // Dimensions
62826e52a70SEwan Crawford         uint16_t hdr_size; // Header size in bytes, including all element headers
62926e52a70SEwan Crawford     };
63026e52a70SEwan Crawford 
63126e52a70SEwan Crawford     struct ElementHeader
63226e52a70SEwan Crawford     {
63355232f09SEwan Crawford         uint16_t type;         // DataType enum
63455232f09SEwan Crawford         uint32_t kind;         // DataKind enum
63555232f09SEwan Crawford         uint32_t element_size; // Size of a single element, including padding
63626e52a70SEwan Crawford         uint16_t vector_size;  // Vector width
63726e52a70SEwan Crawford         uint32_t array_size;   // Number of elements in array
63855232f09SEwan Crawford     };
63955232f09SEwan Crawford 
64015f2bd95SEwan Crawford     // Monotonically increasing from 1
641b3f7f69dSAidan Dodds     static uint32_t ID;
64215f2bd95SEwan Crawford 
64315f2bd95SEwan Crawford     // Maps Allocation DataType enum and vector size to printable strings
64415f2bd95SEwan Crawford     // using mapping from RenderScript numerical types summary documentation
64515f2bd95SEwan Crawford     static const char *RsDataTypeToString[][4];
64615f2bd95SEwan Crawford 
64715f2bd95SEwan Crawford     // Maps Allocation DataKind enum to printable strings
64815f2bd95SEwan Crawford     static const char *RsDataKindToString[];
64915f2bd95SEwan Crawford 
650a0f08674SEwan Crawford     // Maps allocation types to format sizes for printing.
651b3f7f69dSAidan Dodds     static const uint32_t RSTypeToFormat[][3];
652a0f08674SEwan Crawford 
65315f2bd95SEwan Crawford     // Give each allocation an ID as a way
65415f2bd95SEwan Crawford     // for commands to reference it.
655b3f7f69dSAidan Dodds     const uint32_t id;
65615f2bd95SEwan Crawford 
6578b244e21SEwan Crawford     RenderScriptRuntime::Element element;  // Allocation Element type
65815f2bd95SEwan Crawford     empirical_type<Dimension> dimension;   // Dimensions of the Allocation
65915f2bd95SEwan Crawford     empirical_type<lldb::addr_t> address;  // Pointer to address of the RS Allocation
66015f2bd95SEwan Crawford     empirical_type<lldb::addr_t> data_ptr; // Pointer to the data held by the Allocation
66115f2bd95SEwan Crawford     empirical_type<lldb::addr_t> type_ptr; // Pointer to the RS Type of the Allocation
66215f2bd95SEwan Crawford     empirical_type<lldb::addr_t> context;  // Pointer to the RS Context of the Allocation
663a0f08674SEwan Crawford     empirical_type<uint32_t> size;         // Size of the allocation
664a0f08674SEwan Crawford     empirical_type<uint32_t> stride;       // Stride between rows of the allocation
66515f2bd95SEwan Crawford 
66615f2bd95SEwan Crawford     // Give each allocation an id, so we can reference it in user commands.
667b3f7f69dSAidan Dodds     AllocationDetails() : id(ID++) {}
6688b59062aSEwan Crawford 
669b3f7f69dSAidan Dodds     bool
670b3f7f69dSAidan Dodds     shouldRefresh() const
6718b59062aSEwan Crawford     {
6728b59062aSEwan Crawford         bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
6738b59062aSEwan Crawford         valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
6748b59062aSEwan Crawford         return !valid_ptrs || !dimension.isValid() || !size.isValid() || element.shouldRefresh();
6758b59062aSEwan Crawford     }
67615f2bd95SEwan Crawford };
67715f2bd95SEwan Crawford 
678fe06b5adSAdrian McCarthy const ConstString &
679fe06b5adSAdrian McCarthy RenderScriptRuntime::Element::GetFallbackStructName()
680fe06b5adSAdrian McCarthy {
681fe06b5adSAdrian McCarthy     static const ConstString FallbackStructName("struct");
682fe06b5adSAdrian McCarthy     return FallbackStructName;
683fe06b5adSAdrian McCarthy }
6848b244e21SEwan Crawford 
685b3f7f69dSAidan Dodds uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
68615f2bd95SEwan Crawford 
687b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
68815f2bd95SEwan Crawford     "User",
689b3f7f69dSAidan Dodds     "Undefined",  "Undefined",   "Undefined", "Undefined", "Undefined",  "Undefined", // Enum jumps from 0 to 7
690b3f7f69dSAidan Dodds     "L Pixel",    "A Pixel",     "LA Pixel",  "RGB Pixel",
691b3f7f69dSAidan Dodds     "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
69215f2bd95SEwan Crawford 
693b3f7f69dSAidan Dodds const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
69415f2bd95SEwan Crawford     {"None", "None", "None", "None"},
69515f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
69615f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
69715f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
69815f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
69915f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
70015f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
70115f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
70215f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
70315f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
70415f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
70515f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
7062e920715SEwan Crawford     {"bool", "bool2", "bool3", "bool4"},
7072e920715SEwan Crawford     {"packed_565", "packed_565", "packed_565", "packed_565"},
7082e920715SEwan Crawford     {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
7092e920715SEwan Crawford     {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
7102e920715SEwan Crawford     {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
7112e920715SEwan Crawford     {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
7122e920715SEwan Crawford     {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
7132e920715SEwan Crawford 
7142e920715SEwan Crawford     // Handlers
7152e920715SEwan Crawford     {"RS Element", "RS Element", "RS Element", "RS Element"},
7162e920715SEwan Crawford     {"RS Type", "RS Type", "RS Type", "RS Type"},
7172e920715SEwan Crawford     {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
7182e920715SEwan Crawford     {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
7192e920715SEwan Crawford     {"RS Script", "RS Script", "RS Script", "RS Script"},
7202e920715SEwan Crawford 
7212e920715SEwan Crawford     // Deprecated
7222e920715SEwan Crawford     {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
7232e920715SEwan Crawford     {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment", "RS Program Fragment"},
7242e920715SEwan Crawford     {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex", "RS Program Vertex"},
7252e920715SEwan Crawford     {"RS Program Raster", "RS Program Raster", "RS Program Raster", "RS Program Raster"},
7262e920715SEwan Crawford     {"RS Program Store", "RS Program Store", "RS Program Store", "RS Program Store"},
727b3f7f69dSAidan Dodds     {"RS Font", "RS Font", "RS Font", "RS Font"}};
72878f339d1SEwan Crawford 
729a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
730b3f7f69dSAidan Dodds enum TypeToFormatIndex
731b3f7f69dSAidan Dodds {
732a0f08674SEwan Crawford     eFormatSingle = 0,
733a0f08674SEwan Crawford     eFormatVector,
734a0f08674SEwan Crawford     eElementSize
735a0f08674SEwan Crawford };
736a0f08674SEwan Crawford 
737a0f08674SEwan Crawford // { format enum of single element, format enum of element vector, size of element}
738b3f7f69dSAidan Dodds const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
739a0f08674SEwan Crawford     {eFormatHex, eFormatHex, 1},                                          // RS_TYPE_NONE
740a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat16, 2},                            // RS_TYPE_FLOAT_16
741a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},                // RS_TYPE_FLOAT_32
742a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},               // RS_TYPE_FLOAT_64
743a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},               // RS_TYPE_SIGNED_8
744a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},             // RS_TYPE_SIGNED_16
745a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},             // RS_TYPE_SIGNED_32
746a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},             // RS_TYPE_SIGNED_64
747a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},              // RS_TYPE_UNSIGNED_8
748a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},            // RS_TYPE_UNSIGNED_16
749a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},            // RS_TYPE_UNSIGNED_32
750a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},            // RS_TYPE_UNSIGNED_64
7512e920715SEwan Crawford     {eFormatBoolean, eFormatBoolean, 1},                                  // RS_TYPE_BOOL
7522e920715SEwan Crawford     {eFormatHex, eFormatHex, sizeof(uint16_t)},                           // RS_TYPE_UNSIGNED_5_6_5
7532e920715SEwan Crawford     {eFormatHex, eFormatHex, sizeof(uint16_t)},                           // RS_TYPE_UNSIGNED_5_5_5_1
7542e920715SEwan Crawford     {eFormatHex, eFormatHex, sizeof(uint16_t)},                           // RS_TYPE_UNSIGNED_4_4_4_4
7552e920715SEwan Crawford     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16}, // RS_TYPE_MATRIX_4X4
7562e920715SEwan Crawford     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},  // RS_TYPE_MATRIX_3X3
7572e920715SEwan Crawford     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}   // RS_TYPE_MATRIX_2X2
758a0f08674SEwan Crawford };
759a0f08674SEwan Crawford 
7605ec532a9SColin Riley //------------------------------------------------------------------
7615ec532a9SColin Riley // Static Functions
7625ec532a9SColin Riley //------------------------------------------------------------------
7635ec532a9SColin Riley LanguageRuntime *
7645ec532a9SColin Riley RenderScriptRuntime::CreateInstance(Process *process, lldb::LanguageType language)
7655ec532a9SColin Riley {
7665ec532a9SColin Riley 
7675ec532a9SColin Riley     if (language == eLanguageTypeExtRenderScript)
7685ec532a9SColin Riley         return new RenderScriptRuntime(process);
7695ec532a9SColin Riley     else
770b3f7f69dSAidan Dodds         return nullptr;
7715ec532a9SColin Riley }
7725ec532a9SColin Riley 
77398156583SEwan Crawford // Callback with a module to search for matching symbols.
77498156583SEwan Crawford // We first check that the module contains RS kernels.
77598156583SEwan Crawford // Then look for a symbol which matches our kernel name.
77698156583SEwan Crawford // The breakpoint address is finally set using the address of this symbol.
77798156583SEwan Crawford Searcher::CallbackReturn
778b3f7f69dSAidan Dodds RSBreakpointResolver::SearchCallback(SearchFilter &filter, SymbolContext &context, Address *, bool)
77998156583SEwan Crawford {
78098156583SEwan Crawford     ModuleSP module = context.module_sp;
78198156583SEwan Crawford 
78298156583SEwan Crawford     if (!module)
78398156583SEwan Crawford         return Searcher::eCallbackReturnContinue;
78498156583SEwan Crawford 
78598156583SEwan Crawford     // Is this a module containing renderscript kernels?
78698156583SEwan Crawford     if (nullptr == module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData))
78798156583SEwan Crawford         return Searcher::eCallbackReturnContinue;
78898156583SEwan Crawford 
78998156583SEwan Crawford     // Attempt to set a breakpoint on the kernel name symbol within the module library.
79098156583SEwan Crawford     // If it's not found, it's likely debug info is unavailable - try to set a
79198156583SEwan Crawford     // breakpoint on <name>.expand.
79298156583SEwan Crawford 
79398156583SEwan Crawford     const Symbol *kernel_sym = module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
79498156583SEwan Crawford     if (!kernel_sym)
79598156583SEwan Crawford     {
79698156583SEwan Crawford         std::string kernel_name_expanded(m_kernel_name.AsCString());
79798156583SEwan Crawford         kernel_name_expanded.append(".expand");
79898156583SEwan Crawford         kernel_sym = module->FindFirstSymbolWithNameAndType(ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
79998156583SEwan Crawford     }
80098156583SEwan Crawford 
80198156583SEwan Crawford     if (kernel_sym)
80298156583SEwan Crawford     {
80398156583SEwan Crawford         Address bp_addr = kernel_sym->GetAddress();
80498156583SEwan Crawford         if (filter.AddressPasses(bp_addr))
80598156583SEwan Crawford             m_breakpoint->AddLocation(bp_addr);
80698156583SEwan Crawford     }
80798156583SEwan Crawford 
80898156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
80998156583SEwan Crawford }
81098156583SEwan Crawford 
8115ec532a9SColin Riley void
8125ec532a9SColin Riley RenderScriptRuntime::Initialize()
8135ec532a9SColin Riley {
814b3f7f69dSAidan Dodds     PluginManager::RegisterPlugin(GetPluginNameStatic(), "RenderScript language support", CreateInstance,
815b3f7f69dSAidan Dodds                                   GetCommandObject);
8165ec532a9SColin Riley }
8175ec532a9SColin Riley 
8185ec532a9SColin Riley void
8195ec532a9SColin Riley RenderScriptRuntime::Terminate()
8205ec532a9SColin Riley {
8215ec532a9SColin Riley     PluginManager::UnregisterPlugin(CreateInstance);
8225ec532a9SColin Riley }
8235ec532a9SColin Riley 
8245ec532a9SColin Riley lldb_private::ConstString
8255ec532a9SColin Riley RenderScriptRuntime::GetPluginNameStatic()
8265ec532a9SColin Riley {
8275ec532a9SColin Riley     static ConstString g_name("renderscript");
8285ec532a9SColin Riley     return g_name;
8295ec532a9SColin Riley }
8305ec532a9SColin Riley 
831ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
832ef20b08fSColin Riley RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp)
833ef20b08fSColin Riley {
834ef20b08fSColin Riley     if (module_sp)
835ef20b08fSColin Riley     {
836ef20b08fSColin Riley         // Is this a module containing renderscript kernels?
837ef20b08fSColin Riley         const Symbol *info_sym = module_sp->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
838ef20b08fSColin Riley         if (info_sym)
839ef20b08fSColin Riley         {
840ef20b08fSColin Riley             return eModuleKindKernelObj;
841ef20b08fSColin Riley         }
8424640cde1SColin Riley 
8434640cde1SColin Riley         // Is this the main RS runtime library
8444640cde1SColin Riley         const ConstString rs_lib("libRS.so");
8454640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_lib)
8464640cde1SColin Riley         {
8474640cde1SColin Riley             return eModuleKindLibRS;
8484640cde1SColin Riley         }
8494640cde1SColin Riley 
8504640cde1SColin Riley         const ConstString rs_driverlib("libRSDriver.so");
8514640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_driverlib)
8524640cde1SColin Riley         {
8534640cde1SColin Riley             return eModuleKindDriver;
8544640cde1SColin Riley         }
8554640cde1SColin Riley 
85615f2bd95SEwan Crawford         const ConstString rs_cpureflib("libRSCpuRef.so");
8574640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib)
8584640cde1SColin Riley         {
8594640cde1SColin Riley             return eModuleKindImpl;
8604640cde1SColin Riley         }
861ef20b08fSColin Riley     }
862ef20b08fSColin Riley     return eModuleKindIgnored;
863ef20b08fSColin Riley }
864ef20b08fSColin Riley 
865ef20b08fSColin Riley bool
866ef20b08fSColin Riley RenderScriptRuntime::IsRenderScriptModule(const lldb::ModuleSP &module_sp)
867ef20b08fSColin Riley {
868ef20b08fSColin Riley     return GetModuleKind(module_sp) != eModuleKindIgnored;
869ef20b08fSColin Riley }
870ef20b08fSColin Riley 
871ef20b08fSColin Riley void
872ef20b08fSColin Riley RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list)
873ef20b08fSColin Riley {
874bb19a13cSSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
875ef20b08fSColin Riley 
876ef20b08fSColin Riley     size_t num_modules = module_list.GetSize();
877ef20b08fSColin Riley     for (size_t i = 0; i < num_modules; i++)
878ef20b08fSColin Riley     {
879ef20b08fSColin Riley         auto mod = module_list.GetModuleAtIndex(i);
880ef20b08fSColin Riley         if (IsRenderScriptModule(mod))
881ef20b08fSColin Riley         {
882ef20b08fSColin Riley             LoadModule(mod);
883ef20b08fSColin Riley         }
884ef20b08fSColin Riley     }
885ef20b08fSColin Riley }
886ef20b08fSColin Riley 
8875ec532a9SColin Riley //------------------------------------------------------------------
8885ec532a9SColin Riley // PluginInterface protocol
8895ec532a9SColin Riley //------------------------------------------------------------------
8905ec532a9SColin Riley lldb_private::ConstString
8915ec532a9SColin Riley RenderScriptRuntime::GetPluginName()
8925ec532a9SColin Riley {
8935ec532a9SColin Riley     return GetPluginNameStatic();
8945ec532a9SColin Riley }
8955ec532a9SColin Riley 
8965ec532a9SColin Riley uint32_t
8975ec532a9SColin Riley RenderScriptRuntime::GetPluginVersion()
8985ec532a9SColin Riley {
8995ec532a9SColin Riley     return 1;
9005ec532a9SColin Riley }
9015ec532a9SColin Riley 
9025ec532a9SColin Riley bool
9035ec532a9SColin Riley RenderScriptRuntime::IsVTableName(const char *name)
9045ec532a9SColin Riley {
9055ec532a9SColin Riley     return false;
9065ec532a9SColin Riley }
9075ec532a9SColin Riley 
9085ec532a9SColin Riley bool
9095f57b6eeSEnrico Granata RenderScriptRuntime::GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic,
9105f57b6eeSEnrico Granata                                               TypeAndOrName &class_type_or_name, Address &address,
9115f57b6eeSEnrico Granata                                               Value::ValueType &value_type)
9125ec532a9SColin Riley {
9135ec532a9SColin Riley     return false;
9145ec532a9SColin Riley }
9155ec532a9SColin Riley 
916c74275bcSEnrico Granata TypeAndOrName
917b3f7f69dSAidan Dodds RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name, ValueObject &static_value)
918c74275bcSEnrico Granata {
919c74275bcSEnrico Granata     return type_and_or_name;
920c74275bcSEnrico Granata }
921c74275bcSEnrico Granata 
9225ec532a9SColin Riley bool
9235ec532a9SColin Riley RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value)
9245ec532a9SColin Riley {
9255ec532a9SColin Riley     return false;
9265ec532a9SColin Riley }
9275ec532a9SColin Riley 
9285ec532a9SColin Riley lldb::BreakpointResolverSP
9295ec532a9SColin Riley RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp, bool throw_bp)
9305ec532a9SColin Riley {
9315ec532a9SColin Riley     BreakpointResolverSP resolver_sp;
9325ec532a9SColin Riley     return resolver_sp;
9335ec532a9SColin Riley }
9345ec532a9SColin Riley 
935b3f7f69dSAidan Dodds const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] = {
9364640cde1SColin Riley     // rsdScript
93782780287SAidan Dodds     {
938b3f7f69dSAidan Dodds         "rsdScriptInit",
939b3f7f69dSAidan Dodds         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhjj",
940b3f7f69dSAidan Dodds         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhmj",
941b3f7f69dSAidan Dodds         0,
942b3f7f69dSAidan Dodds         RenderScriptRuntime::eModuleKindDriver,
943b3f7f69dSAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureScriptInit
94482780287SAidan Dodds     },
94582780287SAidan Dodds     {
946b3f7f69dSAidan Dodds         "rsdScriptInvokeForEachMulti",
947b3f7f69dSAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
948b3f7f69dSAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
949b3f7f69dSAidan Dodds         0,
950b3f7f69dSAidan Dodds         RenderScriptRuntime::eModuleKindDriver,
951b3f7f69dSAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti
95282780287SAidan Dodds     },
95382780287SAidan Dodds     {
954b3f7f69dSAidan Dodds         "rsdScriptSetGlobalVar",
955b3f7f69dSAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvj",
956b3f7f69dSAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvm",
957b3f7f69dSAidan Dodds         0,
958b3f7f69dSAidan Dodds         RenderScriptRuntime::eModuleKindDriver,
959b3f7f69dSAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar
96082780287SAidan Dodds     },
9614640cde1SColin Riley 
9624640cde1SColin Riley     // rsdAllocation
96382780287SAidan Dodds     {
964b3f7f69dSAidan Dodds         "rsdAllocationInit",
965b3f7f69dSAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb",
966b3f7f69dSAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb",
967b3f7f69dSAidan Dodds         0,
968b3f7f69dSAidan Dodds         RenderScriptRuntime::eModuleKindDriver,
969b3f7f69dSAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureAllocationInit
97082780287SAidan Dodds     },
97182780287SAidan Dodds     {
972b3f7f69dSAidan Dodds         "rsdAllocationRead2D",
973b3f7f69dSAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
974b3f7f69dSAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
975b3f7f69dSAidan Dodds         0,
976b3f7f69dSAidan Dodds         RenderScriptRuntime::eModuleKindDriver,
977b3f7f69dSAidan Dodds         nullptr
97882780287SAidan Dodds     },
979e69df382SEwan Crawford     {
980b3f7f69dSAidan Dodds         "rsdAllocationDestroy",
981b3f7f69dSAidan Dodds         "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE",
982b3f7f69dSAidan Dodds         "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE",
983b3f7f69dSAidan Dodds         0,
984b3f7f69dSAidan Dodds         RenderScriptRuntime::eModuleKindDriver,
985b3f7f69dSAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy
986e69df382SEwan Crawford     },
9874640cde1SColin Riley };
9884640cde1SColin Riley 
989222b937cSEugene Zelenko const size_t RenderScriptRuntime::s_runtimeHookCount = sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
9904640cde1SColin Riley 
9914640cde1SColin Riley bool
992b3f7f69dSAidan Dodds RenderScriptRuntime::HookCallback(void *baton, StoppointCallbackContext *ctx, lldb::user_id_t break_id,
993b3f7f69dSAidan Dodds                                   lldb::user_id_t break_loc_id)
9944640cde1SColin Riley {
9954640cde1SColin Riley     RuntimeHook *hook_info = (RuntimeHook *)baton;
9964640cde1SColin Riley     ExecutionContext context(ctx->exe_ctx_ref);
9974640cde1SColin Riley 
998b3f7f69dSAidan Dodds     RenderScriptRuntime *lang_rt =
999b3f7f69dSAidan Dodds         (RenderScriptRuntime *)context.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
10004640cde1SColin Riley 
10014640cde1SColin Riley     lang_rt->HookCallback(hook_info, context);
10024640cde1SColin Riley 
10034640cde1SColin Riley     return false;
10044640cde1SColin Riley }
10054640cde1SColin Riley 
10064640cde1SColin Riley void
10074640cde1SColin Riley RenderScriptRuntime::HookCallback(RuntimeHook *hook_info, ExecutionContext &context)
10084640cde1SColin Riley {
10094640cde1SColin Riley     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
10104640cde1SColin Riley 
10114640cde1SColin Riley     if (log)
1012b3f7f69dSAidan Dodds         log->Printf("%s - '%s'", __FUNCTION__, hook_info->defn->name);
10134640cde1SColin Riley 
10144640cde1SColin Riley     if (hook_info->defn->grabber)
10154640cde1SColin Riley     {
10164640cde1SColin Riley         (this->*(hook_info->defn->grabber))(hook_info, context);
10174640cde1SColin Riley     }
10184640cde1SColin Riley }
10194640cde1SColin Riley 
10204640cde1SColin Riley void
1021e09c44b6SAidan Dodds RenderScriptRuntime::CaptureScriptInvokeForEachMulti(RuntimeHook* hook_info,
1022e09c44b6SAidan Dodds                                                      ExecutionContext& context)
1023e09c44b6SAidan Dodds {
1024e09c44b6SAidan Dodds     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1025e09c44b6SAidan Dodds 
1026f4786785SAidan Dodds     enum
1027e09c44b6SAidan Dodds     {
1028f4786785SAidan Dodds         eRsContext = 0,
1029f4786785SAidan Dodds         eRsScript,
1030f4786785SAidan Dodds         eRsSlot,
1031f4786785SAidan Dodds         eRsAIns,
1032f4786785SAidan Dodds         eRsInLen,
1033f4786785SAidan Dodds         eRsAOut,
1034f4786785SAidan Dodds         eRsUsr,
1035f4786785SAidan Dodds         eRsUsrLen,
1036f4786785SAidan Dodds         eRsSc,
1037f4786785SAidan Dodds     };
1038e09c44b6SAidan Dodds 
10391ee07253SSaleem Abdulrasool     std::array<ArgItem, 9> args{{
1040f4786785SAidan Dodds         ArgItem{ArgItem::ePointer, 0}, // const Context       *rsc
1041f4786785SAidan Dodds         ArgItem{ArgItem::ePointer, 0}, // Script              *s
1042f4786785SAidan Dodds         ArgItem{ArgItem::eInt32, 0},   // uint32_t             slot
1043f4786785SAidan Dodds         ArgItem{ArgItem::ePointer, 0}, // const Allocation   **aIns
1044f4786785SAidan Dodds         ArgItem{ArgItem::eInt32, 0},   // size_t               inLen
1045f4786785SAidan Dodds         ArgItem{ArgItem::ePointer, 0}, // Allocation          *aout
1046f4786785SAidan Dodds         ArgItem{ArgItem::ePointer, 0}, // const void          *usr
1047f4786785SAidan Dodds         ArgItem{ArgItem::eInt32, 0},   // size_t               usrLen
1048f4786785SAidan Dodds         ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall  *sc
10491ee07253SSaleem Abdulrasool     }};
1050e09c44b6SAidan Dodds 
1051f4786785SAidan Dodds     bool success = GetArgs(context, &args[0], args.size());
1052e09c44b6SAidan Dodds     if (!success)
1053e09c44b6SAidan Dodds     {
1054e09c44b6SAidan Dodds         if (log)
1055b3f7f69dSAidan Dodds             log->Printf("%s - Error while reading the function parameters", __FUNCTION__);
1056e09c44b6SAidan Dodds         return;
1057e09c44b6SAidan Dodds     }
1058e09c44b6SAidan Dodds 
1059e09c44b6SAidan Dodds     const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1060e09c44b6SAidan Dodds     Error error;
1061e09c44b6SAidan Dodds     std::vector<uint64_t> allocs;
1062e09c44b6SAidan Dodds 
1063e09c44b6SAidan Dodds     // traverse allocation list
1064f4786785SAidan Dodds     for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i)
1065e09c44b6SAidan Dodds     {
1066e09c44b6SAidan Dodds         // calculate offest to allocation pointer
1067f4786785SAidan Dodds         const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1068e09c44b6SAidan Dodds 
1069e09c44b6SAidan Dodds         // Note: due to little endian layout, reading 32bits or 64bits into res64 will
1070e09c44b6SAidan Dodds         //       give the correct results.
1071e09c44b6SAidan Dodds 
1072e09c44b6SAidan Dodds         uint64_t res64 = 0;
1073e09c44b6SAidan Dodds         size_t read = m_process->ReadMemory(addr, &res64, target_ptr_size, error);
1074e09c44b6SAidan Dodds         if (read != target_ptr_size || !error.Success())
1075e09c44b6SAidan Dodds         {
1076e09c44b6SAidan Dodds             if (log)
1077f4786785SAidan Dodds                 log->Printf("%s - Error while reading allocation list argument %" PRIu64, __FUNCTION__, i);
1078e09c44b6SAidan Dodds         }
1079e09c44b6SAidan Dodds         else
1080e09c44b6SAidan Dodds         {
1081e09c44b6SAidan Dodds             allocs.push_back(res64);
1082e09c44b6SAidan Dodds         }
1083e09c44b6SAidan Dodds     }
1084e09c44b6SAidan Dodds 
1085e09c44b6SAidan Dodds     // if there is an output allocation track it
1086f4786785SAidan Dodds     if (uint64_t aOut = uint64_t(args[eRsAOut]))
1087e09c44b6SAidan Dodds     {
1088f4786785SAidan Dodds         allocs.push_back(aOut);
1089e09c44b6SAidan Dodds     }
1090e09c44b6SAidan Dodds 
1091e09c44b6SAidan Dodds     // for all allocations we have found
1092e09c44b6SAidan Dodds     for (const uint64_t alloc_addr : allocs)
1093e09c44b6SAidan Dodds     {
10945d057637SLuke Drummond         AllocationDetails *alloc = LookUpAllocation(alloc_addr);
10955d057637SLuke Drummond         if (!alloc)
10965d057637SLuke Drummond             alloc = CreateAllocation(alloc_addr);
10975d057637SLuke Drummond 
1098e09c44b6SAidan Dodds         if (alloc)
1099e09c44b6SAidan Dodds         {
1100e09c44b6SAidan Dodds             // save the allocation address
1101e09c44b6SAidan Dodds             if (alloc->address.isValid())
1102e09c44b6SAidan Dodds             {
1103e09c44b6SAidan Dodds                 // check the allocation address we already have matches
1104e09c44b6SAidan Dodds                 assert(*alloc->address.get() == alloc_addr);
1105e09c44b6SAidan Dodds             }
1106e09c44b6SAidan Dodds             else
1107e09c44b6SAidan Dodds             {
1108e09c44b6SAidan Dodds                 alloc->address = alloc_addr;
1109e09c44b6SAidan Dodds             }
1110e09c44b6SAidan Dodds 
1111e09c44b6SAidan Dodds             // save the context
1112e09c44b6SAidan Dodds             if (log)
1113e09c44b6SAidan Dodds             {
1114f4786785SAidan Dodds                 if (alloc->context.isValid() && *alloc->context.get() != addr_t(args[eRsContext]))
1115b3f7f69dSAidan Dodds                     log->Printf("%s - Allocation used by multiple contexts", __FUNCTION__);
1116e09c44b6SAidan Dodds             }
1117f4786785SAidan Dodds             alloc->context = addr_t(args[eRsContext]);
1118e09c44b6SAidan Dodds         }
1119e09c44b6SAidan Dodds     }
1120e09c44b6SAidan Dodds 
1121e09c44b6SAidan Dodds     // make sure we track this script object
1122f4786785SAidan Dodds     if (lldb_private::RenderScriptRuntime::ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true))
1123e09c44b6SAidan Dodds     {
1124e09c44b6SAidan Dodds         if (log)
1125e09c44b6SAidan Dodds         {
1126f4786785SAidan Dodds             if (script->context.isValid() && *script->context.get() != addr_t(args[eRsContext]))
1127b3f7f69dSAidan Dodds                 log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1128e09c44b6SAidan Dodds         }
1129f4786785SAidan Dodds         script->context = addr_t(args[eRsContext]);
1130e09c44b6SAidan Dodds     }
1131e09c44b6SAidan Dodds }
1132e09c44b6SAidan Dodds 
1133e09c44b6SAidan Dodds void
1134b3f7f69dSAidan Dodds RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook_info, ExecutionContext &context)
11354640cde1SColin Riley {
11364640cde1SColin Riley     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11374640cde1SColin Riley 
1138f4786785SAidan Dodds     enum
1139f4786785SAidan Dodds     {
1140f4786785SAidan Dodds         eRsContext,
1141f4786785SAidan Dodds         eRsScript,
1142f4786785SAidan Dodds         eRsId,
1143f4786785SAidan Dodds         eRsData,
1144f4786785SAidan Dodds         eRsLength,
1145f4786785SAidan Dodds     };
11464640cde1SColin Riley 
11471ee07253SSaleem Abdulrasool     std::array<ArgItem, 5> args{{
1148f4786785SAidan Dodds         ArgItem{ArgItem::ePointer, 0}, // eRsContext
1149f4786785SAidan Dodds         ArgItem{ArgItem::ePointer, 0}, // eRsScript
1150f4786785SAidan Dodds         ArgItem{ArgItem::eInt32, 0},   // eRsId
1151f4786785SAidan Dodds         ArgItem{ArgItem::ePointer, 0}, // eRsData
1152f4786785SAidan Dodds         ArgItem{ArgItem::eInt32, 0},   // eRsLength
11531ee07253SSaleem Abdulrasool     }};
11544640cde1SColin Riley 
1155f4786785SAidan Dodds     bool success = GetArgs(context, &args[0], args.size());
115682780287SAidan Dodds     if (!success)
115782780287SAidan Dodds     {
115882780287SAidan Dodds         if (log)
1159b3f7f69dSAidan Dodds             log->Printf("%s - error reading the function parameters.", __FUNCTION__);
116082780287SAidan Dodds         return;
116182780287SAidan Dodds     }
11624640cde1SColin Riley 
11634640cde1SColin Riley     if (log)
11644640cde1SColin Riley     {
1165f4786785SAidan Dodds         log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64 ":%" PRIu64 "bytes.", __FUNCTION__,
1166f4786785SAidan Dodds                     uint64_t(args[eRsContext]), uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1167f4786785SAidan Dodds                     uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
11684640cde1SColin Riley 
1169f4786785SAidan Dodds         addr_t script_addr = addr_t(args[eRsScript]);
11704640cde1SColin Riley         if (m_scriptMappings.find(script_addr) != m_scriptMappings.end())
11714640cde1SColin Riley         {
11724640cde1SColin Riley             auto rsm = m_scriptMappings[script_addr];
1173f4786785SAidan Dodds             if (uint64_t(args[eRsId]) < rsm->m_globals.size())
11744640cde1SColin Riley             {
1175f4786785SAidan Dodds                 auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1176f4786785SAidan Dodds                 log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__, rsg.m_name.AsCString(),
1177f4786785SAidan Dodds                             rsm->m_module->GetFileSpec().GetFilename().AsCString());
11784640cde1SColin Riley             }
11794640cde1SColin Riley         }
11804640cde1SColin Riley     }
11814640cde1SColin Riley }
11824640cde1SColin Riley 
11834640cde1SColin Riley void
1184b3f7f69dSAidan Dodds RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook_info, ExecutionContext &context)
11854640cde1SColin Riley {
11864640cde1SColin Riley     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
11874640cde1SColin Riley 
1188f4786785SAidan Dodds     enum
1189f4786785SAidan Dodds     {
1190f4786785SAidan Dodds         eRsContext,
1191f4786785SAidan Dodds         eRsAlloc,
1192f4786785SAidan Dodds         eRsForceZero
1193f4786785SAidan Dodds     };
11944640cde1SColin Riley 
11951ee07253SSaleem Abdulrasool     std::array<ArgItem, 3> args{{
1196f4786785SAidan Dodds         ArgItem{ArgItem::ePointer, 0}, // eRsContext
1197f4786785SAidan Dodds         ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1198f4786785SAidan Dodds         ArgItem{ArgItem::eBool, 0},    // eRsForceZero
11991ee07253SSaleem Abdulrasool     }};
12004640cde1SColin Riley 
1201f4786785SAidan Dodds     bool success = GetArgs(context, &args[0], args.size());
120282780287SAidan Dodds     if (!success) // error case
120382780287SAidan Dodds     {
120482780287SAidan Dodds         if (log)
1205b3f7f69dSAidan Dodds             log->Printf("%s - error while reading the function parameters", __FUNCTION__);
120682780287SAidan Dodds         return; // abort
120782780287SAidan Dodds     }
12084640cde1SColin Riley 
12094640cde1SColin Riley     if (log)
1210f4786785SAidan Dodds         log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .", __FUNCTION__, uint64_t(args[eRsContext]),
1211f4786785SAidan Dodds                     uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
121278f339d1SEwan Crawford 
12135d057637SLuke Drummond     AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
121478f339d1SEwan Crawford     if (alloc)
1215f4786785SAidan Dodds         alloc->context = uint64_t(args[eRsContext]);
12164640cde1SColin Riley }
12174640cde1SColin Riley 
12184640cde1SColin Riley void
1219e69df382SEwan Crawford RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook_info, ExecutionContext &context)
1220e69df382SEwan Crawford {
1221e69df382SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1222e69df382SEwan Crawford 
1223f4786785SAidan Dodds     enum
1224f4786785SAidan Dodds     {
1225f4786785SAidan Dodds         eRsContext,
1226f4786785SAidan Dodds         eRsAlloc,
1227f4786785SAidan Dodds     };
1228e69df382SEwan Crawford 
12291ee07253SSaleem Abdulrasool     std::array<ArgItem, 2> args{{
1230f4786785SAidan Dodds         ArgItem{ArgItem::ePointer, 0}, // eRsContext
1231f4786785SAidan Dodds         ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
12321ee07253SSaleem Abdulrasool     }};
1233f4786785SAidan Dodds 
1234f4786785SAidan Dodds     bool success = GetArgs(context, &args[0], args.size());
1235b3f7f69dSAidan Dodds     if (!success)
1236e69df382SEwan Crawford     {
1237e69df382SEwan Crawford         if (log)
1238b3f7f69dSAidan Dodds             log->Printf("%s - error while reading the function parameters.", __FUNCTION__);
1239b3f7f69dSAidan Dodds         return;
1240e69df382SEwan Crawford     }
1241e69df382SEwan Crawford 
1242e69df382SEwan Crawford     if (log)
1243f4786785SAidan Dodds         log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__, uint64_t(args[eRsContext]),
1244f4786785SAidan Dodds                     uint64_t(args[eRsAlloc]));
1245e69df382SEwan Crawford 
1246e69df382SEwan Crawford     for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter)
1247e69df382SEwan Crawford     {
1248e69df382SEwan Crawford         auto &allocation_ap = *iter; // get the unique pointer
1249f4786785SAidan Dodds         if (allocation_ap->address.isValid() && *allocation_ap->address.get() == addr_t(args[eRsAlloc]))
1250e69df382SEwan Crawford         {
1251e69df382SEwan Crawford             m_allocations.erase(iter);
1252e69df382SEwan Crawford             if (log)
1253b3f7f69dSAidan Dodds                 log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1254e69df382SEwan Crawford             return;
1255e69df382SEwan Crawford         }
1256e69df382SEwan Crawford     }
1257e69df382SEwan Crawford 
1258e69df382SEwan Crawford     if (log)
1259b3f7f69dSAidan Dodds         log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1260e69df382SEwan Crawford }
1261e69df382SEwan Crawford 
1262e69df382SEwan Crawford void
1263b3f7f69dSAidan Dodds RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook_info, ExecutionContext &context)
12644640cde1SColin Riley {
12654640cde1SColin Riley     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
12664640cde1SColin Riley 
12674640cde1SColin Riley     Error error;
12684640cde1SColin Riley     Process *process = context.GetProcessPtr();
12694640cde1SColin Riley 
1270f4786785SAidan Dodds     enum
1271f4786785SAidan Dodds     {
1272f4786785SAidan Dodds         eRsContext,
1273f4786785SAidan Dodds         eRsScript,
1274f4786785SAidan Dodds         eRsResNamePtr,
1275f4786785SAidan Dodds         eRsCachedDirPtr
1276f4786785SAidan Dodds     };
12774640cde1SColin Riley 
12781ee07253SSaleem Abdulrasool     std::array<ArgItem, 4> args{{ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
12791ee07253SSaleem Abdulrasool                                  ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
1280f4786785SAidan Dodds     bool success = GetArgs(context, &args[0], args.size());
128182780287SAidan Dodds     if (!success)
128282780287SAidan Dodds     {
128382780287SAidan Dodds         if (log)
1284b3f7f69dSAidan Dodds             log->Printf("%s - error while reading the function parameters.", __FUNCTION__);
128582780287SAidan Dodds         return;
128682780287SAidan Dodds     }
128782780287SAidan Dodds 
1288f4786785SAidan Dodds     std::string resname;
1289f4786785SAidan Dodds     process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), resname, error);
12904640cde1SColin Riley     if (error.Fail())
12914640cde1SColin Riley     {
12924640cde1SColin Riley         if (log)
1293b3f7f69dSAidan Dodds             log->Printf("%s - error reading resname: %s.", __FUNCTION__, error.AsCString());
12944640cde1SColin Riley     }
12954640cde1SColin Riley 
1296f4786785SAidan Dodds     std::string cachedir;
1297f4786785SAidan Dodds     process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cachedir, error);
12984640cde1SColin Riley     if (error.Fail())
12994640cde1SColin Riley     {
13004640cde1SColin Riley         if (log)
1301b3f7f69dSAidan Dodds             log->Printf("%s - error reading cachedir: %s.", __FUNCTION__, error.AsCString());
13024640cde1SColin Riley     }
13034640cde1SColin Riley 
13044640cde1SColin Riley     if (log)
1305f4786785SAidan Dodds         log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .", __FUNCTION__, uint64_t(args[eRsContext]),
1306f4786785SAidan Dodds                     uint64_t(args[eRsScript]), resname.c_str(), cachedir.c_str());
13074640cde1SColin Riley 
13084640cde1SColin Riley     if (resname.size() > 0)
13094640cde1SColin Riley     {
13104640cde1SColin Riley         StreamString strm;
13114640cde1SColin Riley         strm.Printf("librs.%s.so", resname.c_str());
13124640cde1SColin Riley 
1313f4786785SAidan Dodds         ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
131478f339d1SEwan Crawford         if (script)
131578f339d1SEwan Crawford         {
131678f339d1SEwan Crawford             script->type = ScriptDetails::eScriptC;
131778f339d1SEwan Crawford             script->cacheDir = cachedir;
131878f339d1SEwan Crawford             script->resName = resname;
131978f339d1SEwan Crawford             script->scriptDyLib = strm.GetData();
1320f4786785SAidan Dodds             script->context = addr_t(args[eRsContext]);
132178f339d1SEwan Crawford         }
13224640cde1SColin Riley 
13234640cde1SColin Riley         if (log)
1324f4786785SAidan Dodds             log->Printf("%s - '%s' tagged with context 0x%" PRIx64 " and script 0x%" PRIx64 ".", __FUNCTION__,
1325f4786785SAidan Dodds                         strm.GetData(), uint64_t(args[eRsContext]), uint64_t(args[eRsScript]));
13264640cde1SColin Riley     }
13274640cde1SColin Riley     else if (log)
13284640cde1SColin Riley     {
1329b3f7f69dSAidan Dodds         log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
13304640cde1SColin Riley     }
13314640cde1SColin Riley }
13324640cde1SColin Riley 
13334640cde1SColin Riley void
13344640cde1SColin Riley RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind)
13354640cde1SColin Riley {
13364640cde1SColin Riley     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
13374640cde1SColin Riley 
13384640cde1SColin Riley     if (!module)
13394640cde1SColin Riley     {
13404640cde1SColin Riley         return;
13414640cde1SColin Riley     }
13424640cde1SColin Riley 
134382780287SAidan Dodds     Target &target = GetProcess()->GetTarget();
134482780287SAidan Dodds     llvm::Triple::ArchType targetArchType = target.GetArchitecture().GetMachine();
134582780287SAidan Dodds 
1346b3f7f69dSAidan Dodds     if (targetArchType != llvm::Triple::ArchType::x86 &&
1347b3f7f69dSAidan Dodds         targetArchType != llvm::Triple::ArchType::arm &&
1348b3f7f69dSAidan Dodds         targetArchType != llvm::Triple::ArchType::aarch64 &&
1349b3f7f69dSAidan Dodds         targetArchType != llvm::Triple::ArchType::mipsel &&
1350b3f7f69dSAidan Dodds         targetArchType != llvm::Triple::ArchType::mips64el &&
1351b3f7f69dSAidan Dodds         targetArchType != llvm::Triple::ArchType::x86_64)
13524640cde1SColin Riley     {
13534640cde1SColin Riley         if (log)
1354b3f7f69dSAidan Dodds             log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
13554640cde1SColin Riley         return;
13564640cde1SColin Riley     }
13574640cde1SColin Riley 
135882780287SAidan Dodds     uint32_t archByteSize = target.GetArchitecture().GetAddressByteSize();
13594640cde1SColin Riley 
13604640cde1SColin Riley     for (size_t idx = 0; idx < s_runtimeHookCount; idx++)
13614640cde1SColin Riley     {
13624640cde1SColin Riley         const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1363b3f7f69dSAidan Dodds         if (hook_defn->kind != kind)
1364b3f7f69dSAidan Dodds         {
13654640cde1SColin Riley             continue;
13664640cde1SColin Riley         }
13674640cde1SColin Riley 
136882780287SAidan Dodds         const char *symbol_name = (archByteSize == 4) ? hook_defn->symbol_name_m32 : hook_defn->symbol_name_m64;
136982780287SAidan Dodds 
137082780287SAidan Dodds         const Symbol *sym = module->FindFirstSymbolWithNameAndType(ConstString(symbol_name), eSymbolTypeCode);
1371b3f7f69dSAidan Dodds         if (!sym)
1372b3f7f69dSAidan Dodds         {
1373b3f7f69dSAidan Dodds             if (log)
1374b3f7f69dSAidan Dodds             {
1375b3f7f69dSAidan Dodds                 log->Printf("%s - symbol '%s' related to the function %s not found",
1376b3f7f69dSAidan Dodds                             __FUNCTION__, symbol_name, hook_defn->name);
137782780287SAidan Dodds             }
137882780287SAidan Dodds             continue;
137982780287SAidan Dodds         }
13804640cde1SColin Riley 
1381358cf1eaSGreg Clayton         addr_t addr = sym->GetLoadAddress(&target);
13824640cde1SColin Riley         if (addr == LLDB_INVALID_ADDRESS)
13834640cde1SColin Riley         {
13844640cde1SColin Riley             if (log)
1385b3f7f69dSAidan Dodds                 log->Printf("%s - unable to resolve the address of hook function '%s' with symbol '%s'.",
1386b3f7f69dSAidan Dodds                             __FUNCTION__, hook_defn->name, symbol_name);
13874640cde1SColin Riley             continue;
13884640cde1SColin Riley         }
138982780287SAidan Dodds         else
139082780287SAidan Dodds         {
139182780287SAidan Dodds             if (log)
1392b3f7f69dSAidan Dodds                 log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1393b3f7f69dSAidan Dodds                             __FUNCTION__, hook_defn->name, addr);
139482780287SAidan Dodds         }
13954640cde1SColin Riley 
13964640cde1SColin Riley         RuntimeHookSP hook(new RuntimeHook());
13974640cde1SColin Riley         hook->address = addr;
13984640cde1SColin Riley         hook->defn = hook_defn;
13994640cde1SColin Riley         hook->bp_sp = target.CreateBreakpoint(addr, true, false);
14004640cde1SColin Riley         hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
14014640cde1SColin Riley         m_runtimeHooks[addr] = hook;
14024640cde1SColin Riley         if (log)
14034640cde1SColin Riley         {
1404b3f7f69dSAidan Dodds             log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64 " at 0x%" PRIx64 ".",
1405b3f7f69dSAidan Dodds                         __FUNCTION__, hook_defn->name, module->GetFileSpec().GetFilename().AsCString(),
1406b3f7f69dSAidan Dodds                         (uint64_t)hook_defn->version, (uint64_t)addr);
14074640cde1SColin Riley         }
14084640cde1SColin Riley     }
14094640cde1SColin Riley }
14104640cde1SColin Riley 
14114640cde1SColin Riley void
14124640cde1SColin Riley RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp)
14134640cde1SColin Riley {
14144640cde1SColin Riley     if (!rsmodule_sp)
14154640cde1SColin Riley         return;
14164640cde1SColin Riley 
14174640cde1SColin Riley     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
14184640cde1SColin Riley 
14194640cde1SColin Riley     const ModuleSP module = rsmodule_sp->m_module;
14204640cde1SColin Riley     const FileSpec &file = module->GetPlatformFileSpec();
14214640cde1SColin Riley 
142278f339d1SEwan Crawford     // Iterate over all of the scripts that we currently know of.
142378f339d1SEwan Crawford     // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
14244640cde1SColin Riley     for (const auto &rs_script : m_scripts)
14254640cde1SColin Riley     {
142678f339d1SEwan Crawford         // Extract the expected .so file path for this script.
142778f339d1SEwan Crawford         std::string dylib;
142878f339d1SEwan Crawford         if (!rs_script->scriptDyLib.get(dylib))
142978f339d1SEwan Crawford             continue;
143078f339d1SEwan Crawford 
143178f339d1SEwan Crawford         // Only proceed if the module that has loaded corresponds to this script.
143278f339d1SEwan Crawford         if (file.GetFilename() != ConstString(dylib.c_str()))
143378f339d1SEwan Crawford             continue;
143478f339d1SEwan Crawford 
143578f339d1SEwan Crawford         // Obtain the script address which we use as a key.
143678f339d1SEwan Crawford         lldb::addr_t script;
143778f339d1SEwan Crawford         if (!rs_script->script.get(script))
143878f339d1SEwan Crawford             continue;
143978f339d1SEwan Crawford 
144078f339d1SEwan Crawford         // If we have a script mapping for the current script.
144178f339d1SEwan Crawford         if (m_scriptMappings.find(script) != m_scriptMappings.end())
14424640cde1SColin Riley         {
144378f339d1SEwan Crawford             // if the module we have stored is different to the one we just received.
144478f339d1SEwan Crawford             if (m_scriptMappings[script] != rsmodule_sp)
14454640cde1SColin Riley             {
14464640cde1SColin Riley                 if (log)
1447b3f7f69dSAidan Dodds                     log->Printf("%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.", __FUNCTION__,
144878f339d1SEwan Crawford                                 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
14494640cde1SColin Riley             }
14504640cde1SColin Riley         }
145178f339d1SEwan Crawford         // We don't have a script mapping for the current script.
14524640cde1SColin Riley         else
14534640cde1SColin Riley         {
145478f339d1SEwan Crawford             // Obtain the script resource name.
145578f339d1SEwan Crawford             std::string resName;
145678f339d1SEwan Crawford             if (rs_script->resName.get(resName))
145778f339d1SEwan Crawford                 // Set the modules resource name.
145878f339d1SEwan Crawford                 rsmodule_sp->m_resname = resName;
145978f339d1SEwan Crawford             // Add Script/Module pair to map.
146078f339d1SEwan Crawford             m_scriptMappings[script] = rsmodule_sp;
14614640cde1SColin Riley             if (log)
1462b3f7f69dSAidan Dodds                 log->Printf("%s - script %" PRIx64 " associated with rsmodule '%s'.", __FUNCTION__,
146378f339d1SEwan Crawford                             (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
14644640cde1SColin Riley         }
14654640cde1SColin Riley     }
14664640cde1SColin Riley }
14674640cde1SColin Riley 
146815f2bd95SEwan Crawford // Uses the Target API to evaluate the expression passed as a parameter to the function
146975500e72SEd Maste // The result of that expression is returned an unsigned 64 bit int, via the result* parameter.
147015f2bd95SEwan Crawford // Function returns true on success, and false on failure
147115f2bd95SEwan Crawford bool
147215f2bd95SEwan Crawford RenderScriptRuntime::EvalRSExpression(const char *expression, StackFrame *frame_ptr, uint64_t *result)
147315f2bd95SEwan Crawford {
147415f2bd95SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
147515f2bd95SEwan Crawford     if (log)
1476b3f7f69dSAidan Dodds         log->Printf("%s(%s)", __FUNCTION__, expression);
147715f2bd95SEwan Crawford 
147815f2bd95SEwan Crawford     ValueObjectSP expr_result;
14798433fdbeSAidan Dodds     EvaluateExpressionOptions options;
14808433fdbeSAidan Dodds     options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
148115f2bd95SEwan Crawford     // Perform the actual expression evaluation
14828433fdbeSAidan Dodds     GetProcess()->GetTarget().EvaluateExpression(expression, frame_ptr, expr_result, options);
148315f2bd95SEwan Crawford 
148415f2bd95SEwan Crawford     if (!expr_result)
148515f2bd95SEwan Crawford     {
148615f2bd95SEwan Crawford         if (log)
1487b3f7f69dSAidan Dodds             log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
148815f2bd95SEwan Crawford         return false;
148915f2bd95SEwan Crawford     }
149015f2bd95SEwan Crawford 
149115f2bd95SEwan Crawford     // The result of the expression is invalid
149215f2bd95SEwan Crawford     if (!expr_result->GetError().Success())
149315f2bd95SEwan Crawford     {
149415f2bd95SEwan Crawford         Error err = expr_result->GetError();
149515f2bd95SEwan Crawford         if (err.GetError() == UserExpression::kNoResult) // Expression returned void, so this is actually a success
149615f2bd95SEwan Crawford         {
149715f2bd95SEwan Crawford             if (log)
1498b3f7f69dSAidan Dodds                 log->Printf("%s - expression returned void.", __FUNCTION__);
149915f2bd95SEwan Crawford 
150015f2bd95SEwan Crawford             result = nullptr;
150115f2bd95SEwan Crawford             return true;
150215f2bd95SEwan Crawford         }
150315f2bd95SEwan Crawford 
150415f2bd95SEwan Crawford         if (log)
1505b3f7f69dSAidan Dodds             log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1506b3f7f69dSAidan Dodds                         err.AsCString());
150715f2bd95SEwan Crawford         return false;
150815f2bd95SEwan Crawford     }
150915f2bd95SEwan Crawford 
151015f2bd95SEwan Crawford     bool success = false;
1511b3f7f69dSAidan Dodds     *result = expr_result->GetValueAsUnsigned(0, &success); // We only read the result as an uint32_t.
151215f2bd95SEwan Crawford 
151315f2bd95SEwan Crawford     if (!success)
151415f2bd95SEwan Crawford     {
151515f2bd95SEwan Crawford         if (log)
1516b3f7f69dSAidan Dodds             log->Printf("%s - couldn't convert expression result to uint32_t", __FUNCTION__);
151715f2bd95SEwan Crawford         return false;
151815f2bd95SEwan Crawford     }
151915f2bd95SEwan Crawford 
152015f2bd95SEwan Crawford     return true;
152115f2bd95SEwan Crawford }
152215f2bd95SEwan Crawford 
1523ea0636b5SEwan Crawford namespace
1524ea0636b5SEwan Crawford {
1525836d9651SEwan Crawford // Used to index expression format strings
1526836d9651SEwan Crawford enum ExpressionStrings
152715f2bd95SEwan Crawford {
1528836d9651SEwan Crawford    eExprGetOffsetPtr = 0,
1529836d9651SEwan Crawford    eExprAllocGetType,
1530836d9651SEwan Crawford    eExprTypeDimX,
1531836d9651SEwan Crawford    eExprTypeDimY,
1532836d9651SEwan Crawford    eExprTypeDimZ,
1533836d9651SEwan Crawford    eExprTypeElemPtr,
1534836d9651SEwan Crawford    eExprElementType,
1535836d9651SEwan Crawford    eExprElementKind,
1536836d9651SEwan Crawford    eExprElementVec,
1537836d9651SEwan Crawford    eExprElementFieldCount,
1538836d9651SEwan Crawford    eExprSubelementsId,
1539836d9651SEwan Crawford    eExprSubelementsName,
1540ea0636b5SEwan Crawford    eExprSubelementsArrSize,
1541ea0636b5SEwan Crawford 
1542ea0636b5SEwan Crawford    _eExprLast // keep at the end, implicit size of the array runtimeExpressions
1543836d9651SEwan Crawford };
154415f2bd95SEwan Crawford 
1545ea0636b5SEwan Crawford // max length of an expanded expression
1546ea0636b5SEwan Crawford const int jit_max_expr_size = 512;
1547ea0636b5SEwan Crawford 
1548ea0636b5SEwan Crawford // Retrieve the string to JIT for the given expression
1549ea0636b5SEwan Crawford const char*
1550ea0636b5SEwan Crawford JITTemplate(ExpressionStrings e)
155115f2bd95SEwan Crawford {
1552ea0636b5SEwan Crawford     // Format strings containing the expressions we may need to evaluate.
1553ea0636b5SEwan Crawford     static std::array<const char*, _eExprLast> runtimeExpressions = {{
155415f2bd95SEwan Crawford      // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1555577570b4SAidan Dodds      "(int*)_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace"
1556577570b4SAidan Dodds      "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)",
155715f2bd95SEwan Crawford 
155815f2bd95SEwan Crawford      // Type* rsaAllocationGetType(Context*, Allocation*)
1559577570b4SAidan Dodds      "(void*)rsaAllocationGetType(0x%" PRIx64 ", 0x%" PRIx64 ")",
156015f2bd95SEwan Crawford 
156115f2bd95SEwan Crawford      // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
156215f2bd95SEwan Crawford      // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ;
156315f2bd95SEwan Crawford      // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
156415f2bd95SEwan Crawford      // Need to specify 32 or 64 bit for uint_t since this differs between devices
1565577570b4SAidan Dodds      "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 6); data[0]", // X dim
1566577570b4SAidan Dodds      "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 6); data[1]", // Y dim
1567577570b4SAidan Dodds      "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 6); data[2]", // Z dim
1568577570b4SAidan Dodds      "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 6); data[5]", // Element ptr
156915f2bd95SEwan Crawford 
157015f2bd95SEwan Crawford      // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
157115f2bd95SEwan Crawford      // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData
1572577570b4SAidan Dodds      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 5); data[0]", // Type
1573577570b4SAidan Dodds      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 5); data[1]", // Kind
1574577570b4SAidan Dodds      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 5); data[3]", // Vector Size
1575577570b4SAidan Dodds      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 5); data[4]", // Field Count
15768b244e21SEwan Crawford 
15778b244e21SEwan Crawford      // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t *ids, const char **names,
15788b244e21SEwan Crawford      // size_t *arraySizes, uint32_t dataSize)
15798b244e21SEwan Crawford      // Needed for Allocations of structs to gather details about fields/Subelements
1580577570b4SAidan Dodds      // Element* of field
1581577570b4SAidan Dodds      "void* ids[%" PRIu32 "]; const char* names[%" PRIu32 "]; size_t arr_size[%" PRIu32 "];"
1582577570b4SAidan Dodds      "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64 ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]",
15838b244e21SEwan Crawford 
1584577570b4SAidan Dodds      // Name of field
1585577570b4SAidan Dodds      "void* ids[%" PRIu32 "]; const char* names[%" PRIu32 "]; size_t arr_size[%" PRIu32 "];"
1586577570b4SAidan Dodds      "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64 ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]",
15878b244e21SEwan Crawford 
1588577570b4SAidan Dodds      // Array size of field
1589577570b4SAidan Dodds      "void* ids[%" PRIu32 "]; const char* names[%" PRIu32 "]; size_t arr_size[%" PRIu32 "];"
1590577570b4SAidan Dodds      "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64 ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"
1591ea0636b5SEwan Crawford     }};
1592ea0636b5SEwan Crawford 
1593ea0636b5SEwan Crawford     return runtimeExpressions[e];
1594ea0636b5SEwan Crawford }
1595ea0636b5SEwan Crawford } // end of the anonymous namespace
1596ea0636b5SEwan Crawford 
159715f2bd95SEwan Crawford 
159815f2bd95SEwan Crawford // JITs the RS runtime for the internal data pointer of an allocation.
159915f2bd95SEwan Crawford // Is passed x,y,z coordinates for the pointer to a specific element.
160015f2bd95SEwan Crawford // Then sets the data_ptr member in Allocation with the result.
160115f2bd95SEwan Crawford // Returns true on success, false otherwise
160215f2bd95SEwan Crawford bool
1603b3f7f69dSAidan Dodds RenderScriptRuntime::JITDataPointer(AllocationDetails *allocation, StackFrame *frame_ptr, uint32_t x,
1604b3f7f69dSAidan Dodds                                     uint32_t y, uint32_t z)
160515f2bd95SEwan Crawford {
160615f2bd95SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
160715f2bd95SEwan Crawford 
160815f2bd95SEwan Crawford     if (!allocation->address.isValid())
160915f2bd95SEwan Crawford     {
161015f2bd95SEwan Crawford         if (log)
1611b3f7f69dSAidan Dodds             log->Printf("%s - failed to find allocation details.", __FUNCTION__);
161215f2bd95SEwan Crawford         return false;
161315f2bd95SEwan Crawford     }
161415f2bd95SEwan Crawford 
1615ea0636b5SEwan Crawford     const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1616ea0636b5SEwan Crawford     char buffer[jit_max_expr_size];
161715f2bd95SEwan Crawford 
1618ea0636b5SEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), x, y, z);
161915f2bd95SEwan Crawford     if (chars_written < 0)
162015f2bd95SEwan Crawford     {
162115f2bd95SEwan Crawford         if (log)
1622b3f7f69dSAidan Dodds             log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
162315f2bd95SEwan Crawford         return false;
162415f2bd95SEwan Crawford     }
1625ea0636b5SEwan Crawford     else if (chars_written >= jit_max_expr_size)
162615f2bd95SEwan Crawford     {
162715f2bd95SEwan Crawford         if (log)
1628b3f7f69dSAidan Dodds             log->Printf("%s - expression too long.", __FUNCTION__);
162915f2bd95SEwan Crawford         return false;
163015f2bd95SEwan Crawford     }
163115f2bd95SEwan Crawford 
163215f2bd95SEwan Crawford     uint64_t result = 0;
163315f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
163415f2bd95SEwan Crawford         return false;
163515f2bd95SEwan Crawford 
163615f2bd95SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
163715f2bd95SEwan Crawford     allocation->data_ptr = mem_ptr;
163815f2bd95SEwan Crawford 
163915f2bd95SEwan Crawford     return true;
164015f2bd95SEwan Crawford }
164115f2bd95SEwan Crawford 
164215f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
164315f2bd95SEwan Crawford // Then sets the type_ptr member in Allocation with the result.
164415f2bd95SEwan Crawford // Returns true on success, false otherwise
164515f2bd95SEwan Crawford bool
164615f2bd95SEwan Crawford RenderScriptRuntime::JITTypePointer(AllocationDetails *allocation, StackFrame *frame_ptr)
164715f2bd95SEwan Crawford {
164815f2bd95SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
164915f2bd95SEwan Crawford 
165015f2bd95SEwan Crawford     if (!allocation->address.isValid() || !allocation->context.isValid())
165115f2bd95SEwan Crawford     {
165215f2bd95SEwan Crawford         if (log)
1653b3f7f69dSAidan Dodds             log->Printf("%s - failed to find allocation details.", __FUNCTION__);
165415f2bd95SEwan Crawford         return false;
165515f2bd95SEwan Crawford     }
165615f2bd95SEwan Crawford 
1657ea0636b5SEwan Crawford     const char *expr_cstr = JITTemplate(eExprAllocGetType);
1658ea0636b5SEwan Crawford     char buffer[jit_max_expr_size];
165915f2bd95SEwan Crawford 
1660ea0636b5SEwan Crawford     int chars_written =
1661ea0636b5SEwan Crawford         snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->context.get(), *allocation->address.get());
166215f2bd95SEwan Crawford     if (chars_written < 0)
166315f2bd95SEwan Crawford     {
166415f2bd95SEwan Crawford         if (log)
1665b3f7f69dSAidan Dodds             log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
166615f2bd95SEwan Crawford         return false;
166715f2bd95SEwan Crawford     }
1668ea0636b5SEwan Crawford     else if (chars_written >= jit_max_expr_size)
166915f2bd95SEwan Crawford     {
167015f2bd95SEwan Crawford         if (log)
1671b3f7f69dSAidan Dodds             log->Printf("%s - expression too long.", __FUNCTION__);
167215f2bd95SEwan Crawford         return false;
167315f2bd95SEwan Crawford     }
167415f2bd95SEwan Crawford 
167515f2bd95SEwan Crawford     uint64_t result = 0;
167615f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
167715f2bd95SEwan Crawford         return false;
167815f2bd95SEwan Crawford 
167915f2bd95SEwan Crawford     addr_t type_ptr = static_cast<lldb::addr_t>(result);
168015f2bd95SEwan Crawford     allocation->type_ptr = type_ptr;
168115f2bd95SEwan Crawford 
168215f2bd95SEwan Crawford     return true;
168315f2bd95SEwan Crawford }
168415f2bd95SEwan Crawford 
168515f2bd95SEwan Crawford // JITs the RS runtime for information about the dimensions and type of an allocation
168615f2bd95SEwan Crawford // Then sets dimension and element_ptr members in Allocation with the result.
168715f2bd95SEwan Crawford // Returns true on success, false otherwise
168815f2bd95SEwan Crawford bool
168915f2bd95SEwan Crawford RenderScriptRuntime::JITTypePacked(AllocationDetails *allocation, StackFrame *frame_ptr)
169015f2bd95SEwan Crawford {
169115f2bd95SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
169215f2bd95SEwan Crawford 
169315f2bd95SEwan Crawford     if (!allocation->type_ptr.isValid() || !allocation->context.isValid())
169415f2bd95SEwan Crawford     {
169515f2bd95SEwan Crawford         if (log)
1696b3f7f69dSAidan Dodds             log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
169715f2bd95SEwan Crawford         return false;
169815f2bd95SEwan Crawford     }
169915f2bd95SEwan Crawford 
170015f2bd95SEwan Crawford     // Expression is different depending on if device is 32 or 64 bit
170115f2bd95SEwan Crawford     uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
1702b3f7f69dSAidan Dodds     const uint32_t bits = archByteSize == 4 ? 32 : 64;
170315f2bd95SEwan Crawford 
170415f2bd95SEwan Crawford     // We want 4 elements from packed data
1705b3f7f69dSAidan Dodds     const uint32_t num_exprs = 4;
170615f2bd95SEwan Crawford     assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) && "Invalid number of expressions");
170715f2bd95SEwan Crawford 
1708ea0636b5SEwan Crawford     char buffer[num_exprs][jit_max_expr_size];
170915f2bd95SEwan Crawford     uint64_t results[num_exprs];
171015f2bd95SEwan Crawford 
1711b3f7f69dSAidan Dodds     for (uint32_t i = 0; i < num_exprs; ++i)
171215f2bd95SEwan Crawford     {
1713ea0636b5SEwan Crawford         const char *expr_cstr = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
1714ea0636b5SEwan Crawford         int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, bits, *allocation->context.get(),
1715ea0636b5SEwan Crawford                                      *allocation->type_ptr.get());
171615f2bd95SEwan Crawford         if (chars_written < 0)
171715f2bd95SEwan Crawford         {
171815f2bd95SEwan Crawford             if (log)
1719b3f7f69dSAidan Dodds                 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
172015f2bd95SEwan Crawford             return false;
172115f2bd95SEwan Crawford         }
1722ea0636b5SEwan Crawford         else if (chars_written >= jit_max_expr_size)
172315f2bd95SEwan Crawford         {
172415f2bd95SEwan Crawford             if (log)
1725b3f7f69dSAidan Dodds                 log->Printf("%s - expression too long.", __FUNCTION__);
172615f2bd95SEwan Crawford             return false;
172715f2bd95SEwan Crawford         }
172815f2bd95SEwan Crawford 
172915f2bd95SEwan Crawford         // Perform expression evaluation
173015f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
173115f2bd95SEwan Crawford             return false;
173215f2bd95SEwan Crawford     }
173315f2bd95SEwan Crawford 
173415f2bd95SEwan Crawford     // Assign results to allocation members
173515f2bd95SEwan Crawford     AllocationDetails::Dimension dims;
173615f2bd95SEwan Crawford     dims.dim_1 = static_cast<uint32_t>(results[0]);
173715f2bd95SEwan Crawford     dims.dim_2 = static_cast<uint32_t>(results[1]);
173815f2bd95SEwan Crawford     dims.dim_3 = static_cast<uint32_t>(results[2]);
173915f2bd95SEwan Crawford     allocation->dimension = dims;
174015f2bd95SEwan Crawford 
174115f2bd95SEwan Crawford     addr_t elem_ptr = static_cast<lldb::addr_t>(results[3]);
17428b244e21SEwan Crawford     allocation->element.element_ptr = elem_ptr;
174315f2bd95SEwan Crawford 
174415f2bd95SEwan Crawford     if (log)
1745b3f7f69dSAidan Dodds         log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") Element*: 0x%" PRIx64 ".", __FUNCTION__,
174615f2bd95SEwan Crawford                     dims.dim_1, dims.dim_2, dims.dim_3, elem_ptr);
174715f2bd95SEwan Crawford 
174815f2bd95SEwan Crawford     return true;
174915f2bd95SEwan Crawford }
175015f2bd95SEwan Crawford 
175115f2bd95SEwan Crawford // JITs the RS runtime for information about the Element of an allocation
17528b244e21SEwan Crawford // Then sets type, type_vec_size, field_count and type_kind members in Element with the result.
175315f2bd95SEwan Crawford // Returns true on success, false otherwise
175415f2bd95SEwan Crawford bool
17558b244e21SEwan Crawford RenderScriptRuntime::JITElementPacked(Element &elem, const lldb::addr_t context, StackFrame *frame_ptr)
175615f2bd95SEwan Crawford {
175715f2bd95SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
175815f2bd95SEwan Crawford 
17598b244e21SEwan Crawford     if (!elem.element_ptr.isValid())
176015f2bd95SEwan Crawford     {
176115f2bd95SEwan Crawford         if (log)
1762b3f7f69dSAidan Dodds             log->Printf("%s - failed to find allocation details.", __FUNCTION__);
176315f2bd95SEwan Crawford         return false;
176415f2bd95SEwan Crawford     }
176515f2bd95SEwan Crawford 
17668b244e21SEwan Crawford     // We want 4 elements from packed data
1767b3f7f69dSAidan Dodds     const uint32_t num_exprs = 4;
17688b244e21SEwan Crawford     assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) && "Invalid number of expressions");
176915f2bd95SEwan Crawford 
1770ea0636b5SEwan Crawford     char buffer[num_exprs][jit_max_expr_size];
177115f2bd95SEwan Crawford     uint64_t results[num_exprs];
177215f2bd95SEwan Crawford 
1773b3f7f69dSAidan Dodds     for (uint32_t i = 0; i < num_exprs; i++)
177415f2bd95SEwan Crawford     {
1775ea0636b5SEwan Crawford         const char *expr_cstr = JITTemplate(ExpressionStrings(eExprElementType + i));
1776ea0636b5SEwan Crawford         int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, context, *elem.element_ptr.get());
177715f2bd95SEwan Crawford         if (chars_written < 0)
177815f2bd95SEwan Crawford         {
177915f2bd95SEwan Crawford             if (log)
1780b3f7f69dSAidan Dodds                 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
178115f2bd95SEwan Crawford             return false;
178215f2bd95SEwan Crawford         }
1783ea0636b5SEwan Crawford         else if (chars_written >= jit_max_expr_size)
178415f2bd95SEwan Crawford         {
178515f2bd95SEwan Crawford             if (log)
1786b3f7f69dSAidan Dodds                 log->Printf("%s - expression too long.", __FUNCTION__);
178715f2bd95SEwan Crawford             return false;
178815f2bd95SEwan Crawford         }
178915f2bd95SEwan Crawford 
179015f2bd95SEwan Crawford         // Perform expression evaluation
179115f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
179215f2bd95SEwan Crawford             return false;
179315f2bd95SEwan Crawford     }
179415f2bd95SEwan Crawford 
179515f2bd95SEwan Crawford     // Assign results to allocation members
17968b244e21SEwan Crawford     elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
17978b244e21SEwan Crawford     elem.type_kind = static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
17988b244e21SEwan Crawford     elem.type_vec_size = static_cast<uint32_t>(results[2]);
17998b244e21SEwan Crawford     elem.field_count = static_cast<uint32_t>(results[3]);
180015f2bd95SEwan Crawford 
180115f2bd95SEwan Crawford     if (log)
1802b3f7f69dSAidan Dodds         log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32 ", vector size %" PRIu32 ", field count %" PRIu32,
1803b3f7f69dSAidan Dodds                     __FUNCTION__, *elem.type.get(), *elem.type_kind.get(), *elem.type_vec_size.get(), *elem.field_count.get());
18048b244e21SEwan Crawford 
18058b244e21SEwan Crawford     // If this Element has subelements then JIT rsaElementGetSubElements() for details about its fields
18068b244e21SEwan Crawford     if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
18078b244e21SEwan Crawford         return false;
18088b244e21SEwan Crawford 
18098b244e21SEwan Crawford     return true;
18108b244e21SEwan Crawford }
18118b244e21SEwan Crawford 
18128b244e21SEwan Crawford // JITs the RS runtime for information about the subelements/fields of a struct allocation
18138b244e21SEwan Crawford // This is necessary for infering the struct type so we can pretty print the allocation's contents.
18148b244e21SEwan Crawford // Returns true on success, false otherwise
18158b244e21SEwan Crawford bool
18168b244e21SEwan Crawford RenderScriptRuntime::JITSubelements(Element &elem, const lldb::addr_t context, StackFrame *frame_ptr)
18178b244e21SEwan Crawford {
18188b244e21SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
18198b244e21SEwan Crawford 
18208b244e21SEwan Crawford     if (!elem.element_ptr.isValid() || !elem.field_count.isValid())
18218b244e21SEwan Crawford     {
18228b244e21SEwan Crawford         if (log)
1823b3f7f69dSAidan Dodds             log->Printf("%s - failed to find allocation details.", __FUNCTION__);
18248b244e21SEwan Crawford         return false;
18258b244e21SEwan Crawford     }
18268b244e21SEwan Crawford 
18278b244e21SEwan Crawford     const short num_exprs = 3;
18288b244e21SEwan Crawford     assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) && "Invalid number of expressions");
18298b244e21SEwan Crawford 
1830ea0636b5SEwan Crawford     char expr_buffer[jit_max_expr_size];
18318b244e21SEwan Crawford     uint64_t results;
18328b244e21SEwan Crawford 
18338b244e21SEwan Crawford     // Iterate over struct fields.
18348b244e21SEwan Crawford     const uint32_t field_count = *elem.field_count.get();
1835b3f7f69dSAidan Dodds     for (uint32_t field_index = 0; field_index < field_count; ++field_index)
18368b244e21SEwan Crawford     {
18378b244e21SEwan Crawford         Element child;
1838b3f7f69dSAidan Dodds         for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index)
18398b244e21SEwan Crawford         {
1840ea0636b5SEwan Crawford             const char *expr_cstr = JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
1841ea0636b5SEwan Crawford             int chars_written = snprintf(expr_buffer, jit_max_expr_size, expr_cstr,
18428b244e21SEwan Crawford                                          field_count, field_count, field_count,
18438b244e21SEwan Crawford                                          context, *elem.element_ptr.get(), field_count, field_index);
18448b244e21SEwan Crawford             if (chars_written < 0)
18458b244e21SEwan Crawford             {
18468b244e21SEwan Crawford                 if (log)
1847b3f7f69dSAidan Dodds                     log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
18488b244e21SEwan Crawford                 return false;
18498b244e21SEwan Crawford             }
1850ea0636b5SEwan Crawford             else if (chars_written >= jit_max_expr_size)
18518b244e21SEwan Crawford             {
18528b244e21SEwan Crawford                 if (log)
1853b3f7f69dSAidan Dodds                     log->Printf("%s - expression too long.", __FUNCTION__);
18548b244e21SEwan Crawford                 return false;
18558b244e21SEwan Crawford             }
18568b244e21SEwan Crawford 
18578b244e21SEwan Crawford             // Perform expression evaluation
18588b244e21SEwan Crawford             if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
18598b244e21SEwan Crawford                 return false;
18608b244e21SEwan Crawford 
18618b244e21SEwan Crawford             if (log)
1862b3f7f69dSAidan Dodds                 log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
18638b244e21SEwan Crawford 
18648b244e21SEwan Crawford             switch (expr_index)
18658b244e21SEwan Crawford             {
18668b244e21SEwan Crawford                 case 0: // Element* of child
18678b244e21SEwan Crawford                     child.element_ptr = static_cast<addr_t>(results);
18688b244e21SEwan Crawford                     break;
18698b244e21SEwan Crawford                 case 1: // Name of child
18708b244e21SEwan Crawford                 {
18718b244e21SEwan Crawford                     lldb::addr_t address = static_cast<addr_t>(results);
18728b244e21SEwan Crawford                     Error err;
18738b244e21SEwan Crawford                     std::string name;
18748b244e21SEwan Crawford                     GetProcess()->ReadCStringFromMemory(address, name, err);
18758b244e21SEwan Crawford                     if (!err.Fail())
18768b244e21SEwan Crawford                         child.type_name = ConstString(name);
18778b244e21SEwan Crawford                     else
18788b244e21SEwan Crawford                     {
18798b244e21SEwan Crawford                         if (log)
1880b3f7f69dSAidan Dodds                             log->Printf("%s - warning: Couldn't read field name.", __FUNCTION__);
18818b244e21SEwan Crawford                     }
18828b244e21SEwan Crawford                     break;
18838b244e21SEwan Crawford                 }
18848b244e21SEwan Crawford                 case 2: // Array size of child
18858b244e21SEwan Crawford                     child.array_size = static_cast<uint32_t>(results);
18868b244e21SEwan Crawford                     break;
18878b244e21SEwan Crawford             }
18888b244e21SEwan Crawford         }
18898b244e21SEwan Crawford 
18908b244e21SEwan Crawford         // We need to recursively JIT each Element field of the struct since
18918b244e21SEwan Crawford         // structs can be nested inside structs.
18928b244e21SEwan Crawford         if (!JITElementPacked(child, context, frame_ptr))
18938b244e21SEwan Crawford             return false;
18948b244e21SEwan Crawford         elem.children.push_back(child);
18958b244e21SEwan Crawford     }
18968b244e21SEwan Crawford 
18978b244e21SEwan Crawford     // Try to infer the name of the struct type so we can pretty print the allocation contents.
18988b244e21SEwan Crawford     FindStructTypeName(elem, frame_ptr);
189915f2bd95SEwan Crawford 
190015f2bd95SEwan Crawford     return true;
190115f2bd95SEwan Crawford }
190215f2bd95SEwan Crawford 
1903a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
190475500e72SEd Maste // The `elem_size` parameter represents the size of a single element, including padding.
1905a0f08674SEwan Crawford // Which is needed as an offset from the last element pointer.
1906a0f08674SEwan Crawford // Using this offset minus the starting address we can calculate the size of the allocation.
1907a0f08674SEwan Crawford // Returns true on success, false otherwise
1908a0f08674SEwan Crawford bool
19098b244e21SEwan Crawford RenderScriptRuntime::JITAllocationSize(AllocationDetails *allocation, StackFrame *frame_ptr)
1910a0f08674SEwan Crawford {
1911a0f08674SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1912a0f08674SEwan Crawford 
1913b3f7f69dSAidan Dodds     if (!allocation->address.isValid() || !allocation->dimension.isValid() || !allocation->data_ptr.isValid() ||
1914b3f7f69dSAidan Dodds         !allocation->element.datum_size.isValid())
1915a0f08674SEwan Crawford     {
1916a0f08674SEwan Crawford         if (log)
1917b3f7f69dSAidan Dodds             log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1918a0f08674SEwan Crawford         return false;
1919a0f08674SEwan Crawford     }
1920a0f08674SEwan Crawford 
1921a0f08674SEwan Crawford     // Find dimensions
1922b3f7f69dSAidan Dodds     uint32_t dim_x = allocation->dimension.get()->dim_1;
1923b3f7f69dSAidan Dodds     uint32_t dim_y = allocation->dimension.get()->dim_2;
1924b3f7f69dSAidan Dodds     uint32_t dim_z = allocation->dimension.get()->dim_3;
1925a0f08674SEwan Crawford 
19268b244e21SEwan Crawford     // Our plan of jitting the last element address doesn't seem to work for struct Allocations
19278b244e21SEwan Crawford     // Instead try to infer the size ourselves without any inter element padding.
19288b244e21SEwan Crawford     if (allocation->element.children.size() > 0)
19298b244e21SEwan Crawford     {
19308b244e21SEwan Crawford         if (dim_x == 0) dim_x = 1;
19318b244e21SEwan Crawford         if (dim_y == 0) dim_y = 1;
19328b244e21SEwan Crawford         if (dim_z == 0) dim_z = 1;
19338b244e21SEwan Crawford 
19348b244e21SEwan Crawford         allocation->size = dim_x * dim_y * dim_z * *allocation->element.datum_size.get();
19358b244e21SEwan Crawford 
19368b244e21SEwan Crawford         if (log)
193775500e72SEd Maste             log->Printf("%s - inferred size of struct allocation %" PRIu32 ".", __FUNCTION__,
1938b3f7f69dSAidan Dodds                         *allocation->size.get());
19398b244e21SEwan Crawford         return true;
19408b244e21SEwan Crawford     }
19418b244e21SEwan Crawford 
1942ea0636b5SEwan Crawford     const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1943ea0636b5SEwan Crawford     char buffer[jit_max_expr_size];
19448b244e21SEwan Crawford 
1945a0f08674SEwan Crawford     // Calculate last element
1946a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 0 : dim_x - 1;
1947a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 0 : dim_y - 1;
1948a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 0 : dim_z - 1;
1949a0f08674SEwan Crawford 
1950ea0636b5SEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), dim_x, dim_y, dim_z);
1951a0f08674SEwan Crawford     if (chars_written < 0)
1952a0f08674SEwan Crawford     {
1953a0f08674SEwan Crawford         if (log)
1954b3f7f69dSAidan Dodds             log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1955a0f08674SEwan Crawford         return false;
1956a0f08674SEwan Crawford     }
1957ea0636b5SEwan Crawford     else if (chars_written >= jit_max_expr_size)
1958a0f08674SEwan Crawford     {
1959a0f08674SEwan Crawford         if (log)
1960b3f7f69dSAidan Dodds             log->Printf("%s - expression too long.", __FUNCTION__);
1961a0f08674SEwan Crawford         return false;
1962a0f08674SEwan Crawford     }
1963a0f08674SEwan Crawford 
1964a0f08674SEwan Crawford     uint64_t result = 0;
1965a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1966a0f08674SEwan Crawford         return false;
1967a0f08674SEwan Crawford 
1968a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1969a0f08674SEwan Crawford     // Find pointer to last element and add on size of an element
1970b3f7f69dSAidan Dodds     allocation->size =
1971b3f7f69dSAidan Dodds         static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()) + *allocation->element.datum_size.get();
1972a0f08674SEwan Crawford 
1973a0f08674SEwan Crawford     return true;
1974a0f08674SEwan Crawford }
1975a0f08674SEwan Crawford 
1976a0f08674SEwan Crawford // JITs the RS runtime for information about the stride between rows in the allocation.
1977a0f08674SEwan Crawford // This is done to detect padding, since allocated memory is 16-byte aligned.
1978a0f08674SEwan Crawford // Returns true on success, false otherwise
1979a0f08674SEwan Crawford bool
1980a0f08674SEwan Crawford RenderScriptRuntime::JITAllocationStride(AllocationDetails *allocation, StackFrame *frame_ptr)
1981a0f08674SEwan Crawford {
1982a0f08674SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1983a0f08674SEwan Crawford 
1984a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->data_ptr.isValid())
1985a0f08674SEwan Crawford     {
1986a0f08674SEwan Crawford         if (log)
1987b3f7f69dSAidan Dodds             log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1988a0f08674SEwan Crawford         return false;
1989a0f08674SEwan Crawford     }
1990a0f08674SEwan Crawford 
1991ea0636b5SEwan Crawford     const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1992ea0636b5SEwan Crawford     char buffer[jit_max_expr_size];
1993a0f08674SEwan Crawford 
1994ea0636b5SEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), 0, 1, 0);
1995a0f08674SEwan Crawford     if (chars_written < 0)
1996a0f08674SEwan Crawford     {
1997a0f08674SEwan Crawford         if (log)
1998b3f7f69dSAidan Dodds             log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1999a0f08674SEwan Crawford         return false;
2000a0f08674SEwan Crawford     }
2001ea0636b5SEwan Crawford     else if (chars_written >= jit_max_expr_size)
2002a0f08674SEwan Crawford     {
2003a0f08674SEwan Crawford         if (log)
2004b3f7f69dSAidan Dodds             log->Printf("%s - expression too long.", __FUNCTION__);
2005a0f08674SEwan Crawford         return false;
2006a0f08674SEwan Crawford     }
2007a0f08674SEwan Crawford 
2008a0f08674SEwan Crawford     uint64_t result = 0;
2009a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
2010a0f08674SEwan Crawford         return false;
2011a0f08674SEwan Crawford 
2012a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2013a0f08674SEwan Crawford     allocation->stride = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get());
2014a0f08674SEwan Crawford 
2015a0f08674SEwan Crawford     return true;
2016a0f08674SEwan Crawford }
2017a0f08674SEwan Crawford 
201815f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
201915f2bd95SEwan Crawford bool
202015f2bd95SEwan Crawford RenderScriptRuntime::RefreshAllocation(AllocationDetails *allocation, StackFrame *frame_ptr)
202115f2bd95SEwan Crawford {
202215f2bd95SEwan Crawford     // GetOffsetPointer()
202315f2bd95SEwan Crawford     if (!JITDataPointer(allocation, frame_ptr))
202415f2bd95SEwan Crawford         return false;
202515f2bd95SEwan Crawford 
202615f2bd95SEwan Crawford     // rsaAllocationGetType()
202715f2bd95SEwan Crawford     if (!JITTypePointer(allocation, frame_ptr))
202815f2bd95SEwan Crawford         return false;
202915f2bd95SEwan Crawford 
203015f2bd95SEwan Crawford     // rsaTypeGetNativeData()
203115f2bd95SEwan Crawford     if (!JITTypePacked(allocation, frame_ptr))
203215f2bd95SEwan Crawford         return false;
203315f2bd95SEwan Crawford 
203415f2bd95SEwan Crawford     // rsaElementGetNativeData()
20358b244e21SEwan Crawford     if (!JITElementPacked(allocation->element, *allocation->context.get(), frame_ptr))
203615f2bd95SEwan Crawford         return false;
203715f2bd95SEwan Crawford 
20388b244e21SEwan Crawford     // Sets the datum_size member in Element
20398b244e21SEwan Crawford     SetElementSize(allocation->element);
20408b244e21SEwan Crawford 
204155232f09SEwan Crawford     // Use GetOffsetPointer() to infer size of the allocation
20428b244e21SEwan Crawford     if (!JITAllocationSize(allocation, frame_ptr))
204355232f09SEwan Crawford         return false;
204455232f09SEwan Crawford 
204555232f09SEwan Crawford     return true;
204655232f09SEwan Crawford }
204755232f09SEwan Crawford 
20488b244e21SEwan Crawford // Function attempts to set the type_name member of the paramaterised Element object.
20498b244e21SEwan Crawford // This string should be the name of the struct type the Element represents.
20508b244e21SEwan Crawford // We need this string for pretty printing the Element to users.
20518b244e21SEwan Crawford void
20528b244e21SEwan Crawford RenderScriptRuntime::FindStructTypeName(Element &elem, StackFrame *frame_ptr)
205355232f09SEwan Crawford {
20548b244e21SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
20558b244e21SEwan Crawford 
20568b244e21SEwan Crawford     if (!elem.type_name.IsEmpty()) // Name already set
20578b244e21SEwan Crawford         return;
20588b244e21SEwan Crawford     else
2059fe06b5adSAdrian McCarthy         elem.type_name = Element::GetFallbackStructName(); // Default type name if we don't succeed
20608b244e21SEwan Crawford 
20618b244e21SEwan Crawford     // Find all the global variables from the script rs modules
20628b244e21SEwan Crawford     VariableList variable_list;
20638b244e21SEwan Crawford     for (auto module_sp : m_rsmodules)
20648b244e21SEwan Crawford         module_sp->m_module->FindGlobalVariables(RegularExpression("."), true, UINT32_MAX, variable_list);
20658b244e21SEwan Crawford 
20668b244e21SEwan Crawford     // Iterate over all the global variables looking for one with a matching type to the Element.
20678b244e21SEwan Crawford     // We make the assumption a match exists since there needs to be a global variable to reflect the
20688b244e21SEwan Crawford     // struct type back into java host code.
20698b244e21SEwan Crawford     for (uint32_t var_index = 0; var_index < variable_list.GetSize(); ++var_index)
20708b244e21SEwan Crawford     {
20718b244e21SEwan Crawford         const VariableSP var_sp(variable_list.GetVariableAtIndex(var_index));
20728b244e21SEwan Crawford         if (!var_sp)
20738b244e21SEwan Crawford             continue;
20748b244e21SEwan Crawford 
20758b244e21SEwan Crawford         ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
20768b244e21SEwan Crawford         if (!valobj_sp)
20778b244e21SEwan Crawford             continue;
20788b244e21SEwan Crawford 
20798b244e21SEwan Crawford         // Find the number of variable fields.
20808b244e21SEwan Crawford         // If it has no fields, or more fields than our Element, then it can't be the struct we're looking for.
20818b244e21SEwan Crawford         // Don't check for equality since RS can add extra struct members for padding.
20828b244e21SEwan Crawford         size_t num_children = valobj_sp->GetNumChildren();
20838b244e21SEwan Crawford         if (num_children > elem.children.size() || num_children == 0)
20848b244e21SEwan Crawford             continue;
20858b244e21SEwan Crawford 
20868b244e21SEwan Crawford         // Iterate over children looking for members with matching field names.
20878b244e21SEwan Crawford         // If all the field names match, this is likely the struct we want.
20888b244e21SEwan Crawford         //
20898b244e21SEwan Crawford         //   TODO: This could be made more robust by also checking children data sizes, or array size
20908b244e21SEwan Crawford         bool found = true;
20918b244e21SEwan Crawford         for (size_t child_index = 0; child_index < num_children; ++child_index)
20928b244e21SEwan Crawford         {
20938b244e21SEwan Crawford             ValueObjectSP child = valobj_sp->GetChildAtIndex(child_index, true);
20948b244e21SEwan Crawford             if (!child || (child->GetName() != elem.children[child_index].type_name))
20958b244e21SEwan Crawford             {
20968b244e21SEwan Crawford                 found = false;
20978b244e21SEwan Crawford                 break;
20988b244e21SEwan Crawford             }
20998b244e21SEwan Crawford         }
21008b244e21SEwan Crawford 
21018b244e21SEwan Crawford         // RS can add extra struct members for padding in the format '#rs_padding_[0-9]+'
21028b244e21SEwan Crawford         if (found && num_children < elem.children.size())
21038b244e21SEwan Crawford         {
2104b3f7f69dSAidan Dodds             const uint32_t size_diff = elem.children.size() - num_children;
21058b244e21SEwan Crawford             if (log)
2106b3f7f69dSAidan Dodds                 log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__, size_diff);
21078b244e21SEwan Crawford 
2108b3f7f69dSAidan Dodds             for (uint32_t padding_index = 0; padding_index < size_diff; ++padding_index)
21098b244e21SEwan Crawford             {
21108b244e21SEwan Crawford                 const ConstString &name = elem.children[num_children + padding_index].type_name;
21118b244e21SEwan Crawford                 if (strcmp(name.AsCString(), "#rs_padding") < 0)
21128b244e21SEwan Crawford                     found = false;
21138b244e21SEwan Crawford             }
21148b244e21SEwan Crawford         }
21158b244e21SEwan Crawford 
21168b244e21SEwan Crawford         // We've found a global var with matching type
21178b244e21SEwan Crawford         if (found)
21188b244e21SEwan Crawford         {
21198b244e21SEwan Crawford             // Dereference since our Element type isn't a pointer.
21208b244e21SEwan Crawford             if (valobj_sp->IsPointerType())
21218b244e21SEwan Crawford             {
21228b244e21SEwan Crawford                 Error err;
21238b244e21SEwan Crawford                 ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
21248b244e21SEwan Crawford                 if (!err.Fail())
21258b244e21SEwan Crawford                     valobj_sp = deref_valobj;
21268b244e21SEwan Crawford             }
21278b244e21SEwan Crawford 
21288b244e21SEwan Crawford             // Save name of variable in Element.
21298b244e21SEwan Crawford             elem.type_name = valobj_sp->GetTypeName();
21308b244e21SEwan Crawford             if (log)
2131b3f7f69dSAidan Dodds                 log->Printf("%s - element name set to %s", __FUNCTION__, elem.type_name.AsCString());
21328b244e21SEwan Crawford 
21338b244e21SEwan Crawford             return;
21348b244e21SEwan Crawford         }
21358b244e21SEwan Crawford     }
21368b244e21SEwan Crawford }
21378b244e21SEwan Crawford 
21388b244e21SEwan Crawford // Function sets the datum_size member of Element. Representing the size of a single instance including padding.
21398b244e21SEwan Crawford // Assumes the relevant allocation information has already been jitted.
21408b244e21SEwan Crawford void
21418b244e21SEwan Crawford RenderScriptRuntime::SetElementSize(Element &elem)
21428b244e21SEwan Crawford {
21438b244e21SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
21448b244e21SEwan Crawford     const Element::DataType type = *elem.type.get();
2145b3f7f69dSAidan Dodds     assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT && "Invalid allocation type");
214655232f09SEwan Crawford 
2147b3f7f69dSAidan Dodds     const uint32_t vec_size = *elem.type_vec_size.get();
2148b3f7f69dSAidan Dodds     uint32_t data_size = 0;
2149b3f7f69dSAidan Dodds     uint32_t padding = 0;
215055232f09SEwan Crawford 
21518b244e21SEwan Crawford     // Element is of a struct type, calculate size recursively.
21528b244e21SEwan Crawford     if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0))
21538b244e21SEwan Crawford     {
21548b244e21SEwan Crawford         for (Element &child : elem.children)
21558b244e21SEwan Crawford         {
21568b244e21SEwan Crawford             SetElementSize(child);
2157b3f7f69dSAidan Dodds             const uint32_t array_size = child.array_size.isValid() ? *child.array_size.get() : 1;
21588b244e21SEwan Crawford             data_size += *child.datum_size.get() * array_size;
21598b244e21SEwan Crawford         }
21608b244e21SEwan Crawford     }
2161b3f7f69dSAidan Dodds     // These have been packed already
2162b3f7f69dSAidan Dodds     else if (type == Element::RS_TYPE_UNSIGNED_5_6_5   ||
2163b3f7f69dSAidan Dodds              type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2164b3f7f69dSAidan Dodds              type == Element::RS_TYPE_UNSIGNED_4_4_4_4)
21652e920715SEwan Crawford     {
21662e920715SEwan Crawford         data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
21672e920715SEwan Crawford     }
21682e920715SEwan Crawford     else if (type < Element::RS_TYPE_ELEMENT)
21692e920715SEwan Crawford     {
21708b244e21SEwan Crawford         data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
21712e920715SEwan Crawford         if (vec_size == 3)
21722e920715SEwan Crawford             padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
21732e920715SEwan Crawford     }
21742e920715SEwan Crawford     else
21752e920715SEwan Crawford         data_size = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
21768b244e21SEwan Crawford 
21778b244e21SEwan Crawford     elem.padding = padding;
21788b244e21SEwan Crawford     elem.datum_size = data_size + padding;
21798b244e21SEwan Crawford     if (log)
2180b3f7f69dSAidan Dodds         log->Printf("%s - element size set to %" PRIu32, __FUNCTION__, data_size + padding);
218155232f09SEwan Crawford }
218255232f09SEwan Crawford 
218355232f09SEwan Crawford // Given an allocation, this function copies the allocation contents from device into a buffer on the heap.
218455232f09SEwan Crawford // Returning a shared pointer to the buffer containing the data.
218555232f09SEwan Crawford std::shared_ptr<uint8_t>
218655232f09SEwan Crawford RenderScriptRuntime::GetAllocationData(AllocationDetails *allocation, StackFrame *frame_ptr)
218755232f09SEwan Crawford {
218855232f09SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
218955232f09SEwan Crawford 
219055232f09SEwan Crawford     // JIT all the allocation details
21918b59062aSEwan Crawford     if (allocation->shouldRefresh())
219255232f09SEwan Crawford     {
219355232f09SEwan Crawford         if (log)
2194b3f7f69dSAidan Dodds             log->Printf("%s - allocation details not calculated yet, jitting info", __FUNCTION__);
219555232f09SEwan Crawford 
219655232f09SEwan Crawford         if (!RefreshAllocation(allocation, frame_ptr))
219755232f09SEwan Crawford         {
219855232f09SEwan Crawford             if (log)
2199b3f7f69dSAidan Dodds                 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
220055232f09SEwan Crawford             return nullptr;
220155232f09SEwan Crawford         }
220255232f09SEwan Crawford     }
220355232f09SEwan Crawford 
2204b3f7f69dSAidan Dodds     assert(allocation->data_ptr.isValid() && allocation->element.type.isValid() &&
2205b3f7f69dSAidan Dodds            allocation->element.type_vec_size.isValid() && allocation->size.isValid() &&
2206b3f7f69dSAidan Dodds            "Allocation information not available");
220755232f09SEwan Crawford 
220855232f09SEwan Crawford     // Allocate a buffer to copy data into
2209b3f7f69dSAidan Dodds     const uint32_t size = *allocation->size.get();
221055232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
221155232f09SEwan Crawford     if (!buffer)
221255232f09SEwan Crawford     {
221355232f09SEwan Crawford         if (log)
2214b3f7f69dSAidan Dodds             log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer", __FUNCTION__, size);
221555232f09SEwan Crawford         return nullptr;
221655232f09SEwan Crawford     }
221755232f09SEwan Crawford 
221855232f09SEwan Crawford     // Read the inferior memory
221955232f09SEwan Crawford     Error error;
222055232f09SEwan Crawford     lldb::addr_t data_ptr = *allocation->data_ptr.get();
222155232f09SEwan Crawford     GetProcess()->ReadMemory(data_ptr, buffer.get(), size, error);
222255232f09SEwan Crawford     if (error.Fail())
222355232f09SEwan Crawford     {
222455232f09SEwan Crawford         if (log)
2225b3f7f69dSAidan Dodds             log->Printf("%s - '%s' Couldn't read %" PRIu32 " bytes of allocation data from 0x%" PRIx64,
2226b3f7f69dSAidan Dodds                         __FUNCTION__, error.AsCString(), size, data_ptr);
222755232f09SEwan Crawford         return nullptr;
222855232f09SEwan Crawford     }
222955232f09SEwan Crawford 
223055232f09SEwan Crawford     return buffer;
223155232f09SEwan Crawford }
223255232f09SEwan Crawford 
223355232f09SEwan Crawford // Function copies data from a binary file into an allocation.
223455232f09SEwan Crawford // There is a header at the start of the file, FileHeader, before the data content itself.
223575500e72SEd Maste // Information from this header is used to display warnings to the user about incompatibilities
223655232f09SEwan Crawford bool
223755232f09SEwan Crawford RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id, const char *filename, StackFrame *frame_ptr)
223855232f09SEwan Crawford {
223955232f09SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
224055232f09SEwan Crawford 
224155232f09SEwan Crawford     // Find allocation with the given id
224255232f09SEwan Crawford     AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
224355232f09SEwan Crawford     if (!alloc)
224455232f09SEwan Crawford         return false;
224555232f09SEwan Crawford 
224655232f09SEwan Crawford     if (log)
2247b3f7f69dSAidan Dodds         log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__, *alloc->address.get());
224855232f09SEwan Crawford 
224955232f09SEwan Crawford     // JIT all the allocation details
22508b59062aSEwan Crawford     if (alloc->shouldRefresh())
225155232f09SEwan Crawford     {
225255232f09SEwan Crawford         if (log)
2253b3f7f69dSAidan Dodds             log->Printf("%s - allocation details not calculated yet, jitting info.", __FUNCTION__);
225455232f09SEwan Crawford 
225555232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
225655232f09SEwan Crawford         {
225755232f09SEwan Crawford             if (log)
2258b3f7f69dSAidan Dodds                 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
22594cfc9198SSylvestre Ledru             return false;
226055232f09SEwan Crawford         }
226155232f09SEwan Crawford     }
226255232f09SEwan Crawford 
2263b3f7f69dSAidan Dodds     assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid() &&
2264b3f7f69dSAidan Dodds            alloc->size.isValid() && alloc->element.datum_size.isValid() && "Allocation information not available");
226555232f09SEwan Crawford 
226655232f09SEwan Crawford     // Check we can read from file
226755232f09SEwan Crawford     FileSpec file(filename, true);
226855232f09SEwan Crawford     if (!file.Exists())
226955232f09SEwan Crawford     {
227055232f09SEwan Crawford         strm.Printf("Error: File %s does not exist", filename);
227155232f09SEwan Crawford         strm.EOL();
227255232f09SEwan Crawford         return false;
227355232f09SEwan Crawford     }
227455232f09SEwan Crawford 
227555232f09SEwan Crawford     if (!file.Readable())
227655232f09SEwan Crawford     {
227755232f09SEwan Crawford         strm.Printf("Error: File %s does not have readable permissions", filename);
227855232f09SEwan Crawford         strm.EOL();
227955232f09SEwan Crawford         return false;
228055232f09SEwan Crawford     }
228155232f09SEwan Crawford 
228255232f09SEwan Crawford     // Read file into data buffer
228355232f09SEwan Crawford     DataBufferSP data_sp(file.ReadFileContents());
228455232f09SEwan Crawford 
228555232f09SEwan Crawford     // Cast start of buffer to FileHeader and use pointer to read metadata
228655232f09SEwan Crawford     void *file_buffer = data_sp->GetBytes();
2287b3f7f69dSAidan Dodds     if (file_buffer == nullptr ||
2288b3f7f69dSAidan Dodds         data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) + sizeof(AllocationDetails::ElementHeader)))
228926e52a70SEwan Crawford     {
229026e52a70SEwan Crawford         strm.Printf("Error: File %s does not contain enough data for header", filename);
229126e52a70SEwan Crawford         strm.EOL();
229226e52a70SEwan Crawford         return false;
229326e52a70SEwan Crawford     }
229426e52a70SEwan Crawford     const AllocationDetails::FileHeader *file_header = static_cast<AllocationDetails::FileHeader *>(file_buffer);
229555232f09SEwan Crawford 
229626e52a70SEwan Crawford     // Check file starts with ascii characters "RSAD"
2297b3f7f69dSAidan Dodds     if (memcmp(file_header->ident, "RSAD", 4))
229826e52a70SEwan Crawford     {
229926e52a70SEwan Crawford         strm.Printf("Error: File doesn't contain identifier for an RS allocation dump. Are you sure this is the correct file?");
230026e52a70SEwan Crawford         strm.EOL();
230126e52a70SEwan Crawford         return false;
230226e52a70SEwan Crawford     }
230326e52a70SEwan Crawford 
230426e52a70SEwan Crawford     // Look at the type of the root element in the header
230526e52a70SEwan Crawford     AllocationDetails::ElementHeader root_element_header;
230626e52a70SEwan Crawford     memcpy(&root_element_header, static_cast<uint8_t *>(file_buffer) + sizeof(AllocationDetails::FileHeader),
230726e52a70SEwan Crawford            sizeof(AllocationDetails::ElementHeader));
230855232f09SEwan Crawford 
230955232f09SEwan Crawford     if (log)
2310b3f7f69dSAidan Dodds         log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32, __FUNCTION__,
231126e52a70SEwan Crawford                     root_element_header.type, root_element_header.element_size);
231255232f09SEwan Crawford 
231355232f09SEwan Crawford     // Check if the target allocation and file both have the same number of bytes for an Element
231426e52a70SEwan Crawford     if (*alloc->element.datum_size.get() != root_element_header.element_size)
231555232f09SEwan Crawford     {
2316b3f7f69dSAidan Dodds         strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32 " bytes, allocation %" PRIu32 " bytes",
231726e52a70SEwan Crawford                     root_element_header.element_size, *alloc->element.datum_size.get());
231855232f09SEwan Crawford         strm.EOL();
231955232f09SEwan Crawford     }
232055232f09SEwan Crawford 
232126e52a70SEwan Crawford     // Check if the target allocation and file both have the same type
2322b3f7f69dSAidan Dodds     const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
2323b3f7f69dSAidan Dodds     const uint32_t file_type = root_element_header.type;
232426e52a70SEwan Crawford 
232526e52a70SEwan Crawford     if (file_type > Element::RS_TYPE_FONT)
232626e52a70SEwan Crawford     {
232726e52a70SEwan Crawford         strm.Printf("Warning: File has unknown allocation type");
232826e52a70SEwan Crawford         strm.EOL();
232926e52a70SEwan Crawford     }
233026e52a70SEwan Crawford     else if (alloc_type != file_type)
233155232f09SEwan Crawford     {
23322e920715SEwan Crawford         // Enum value isn't monotonous, so doesn't always index RsDataTypeToString array
2333b3f7f69dSAidan Dodds         uint32_t printable_target_type_index = alloc_type;
2334b3f7f69dSAidan Dodds         uint32_t printable_head_type_index = file_type;
233526e52a70SEwan Crawford         if (alloc_type >= Element::RS_TYPE_ELEMENT && alloc_type <= Element::RS_TYPE_FONT)
2336b3f7f69dSAidan Dodds             printable_target_type_index = static_cast<Element::DataType>((alloc_type - Element::RS_TYPE_ELEMENT) +
2337b3f7f69dSAidan Dodds                                                                          Element::RS_TYPE_MATRIX_2X2 + 1);
23382e920715SEwan Crawford 
233926e52a70SEwan Crawford         if (file_type >= Element::RS_TYPE_ELEMENT && file_type <= Element::RS_TYPE_FONT)
2340b3f7f69dSAidan Dodds             printable_head_type_index = static_cast<Element::DataType>((file_type - Element::RS_TYPE_ELEMENT) +
2341b3f7f69dSAidan Dodds                                                                        Element::RS_TYPE_MATRIX_2X2 + 1);
23422e920715SEwan Crawford 
23432e920715SEwan Crawford         const char *file_type_cstr = AllocationDetails::RsDataTypeToString[printable_head_type_index][0];
23442e920715SEwan Crawford         const char *target_type_cstr = AllocationDetails::RsDataTypeToString[printable_target_type_index][0];
234555232f09SEwan Crawford 
2346b3f7f69dSAidan Dodds         strm.Printf("Warning: Mismatched Types - file '%s' type, allocation '%s' type", file_type_cstr,
2347b3f7f69dSAidan Dodds                     target_type_cstr);
234855232f09SEwan Crawford         strm.EOL();
234955232f09SEwan Crawford     }
235055232f09SEwan Crawford 
235126e52a70SEwan Crawford     // Advance buffer past header
235226e52a70SEwan Crawford     file_buffer = static_cast<uint8_t *>(file_buffer) + file_header->hdr_size;
235326e52a70SEwan Crawford 
235455232f09SEwan Crawford     // Calculate size of allocation data in file
235526e52a70SEwan Crawford     size_t length = data_sp->GetByteSize() - file_header->hdr_size;
235655232f09SEwan Crawford 
235755232f09SEwan Crawford     // Check if the target allocation and file both have the same total data size.
2358b3f7f69dSAidan Dodds     const uint32_t alloc_size = *alloc->size.get();
235955232f09SEwan Crawford     if (alloc_size != length)
236055232f09SEwan Crawford     {
2361b3f7f69dSAidan Dodds         strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64 " bytes, allocation 0x%" PRIx32 " bytes",
2362eba832beSJason Molenda                     (uint64_t)length, alloc_size);
236355232f09SEwan Crawford         strm.EOL();
236455232f09SEwan Crawford         length = alloc_size < length ? alloc_size : length; // Set length to copy to minimum
236555232f09SEwan Crawford     }
236655232f09SEwan Crawford 
236755232f09SEwan Crawford     // Copy file data from our buffer into the target allocation.
236855232f09SEwan Crawford     lldb::addr_t alloc_data = *alloc->data_ptr.get();
236955232f09SEwan Crawford     Error error;
237055232f09SEwan Crawford     size_t bytes_written = GetProcess()->WriteMemory(alloc_data, file_buffer, length, error);
237155232f09SEwan Crawford     if (!error.Success() || bytes_written != length)
237255232f09SEwan Crawford     {
237355232f09SEwan Crawford         strm.Printf("Error: Couldn't write data to allocation %s", error.AsCString());
237455232f09SEwan Crawford         strm.EOL();
237555232f09SEwan Crawford         return false;
237655232f09SEwan Crawford     }
237755232f09SEwan Crawford 
2378b3f7f69dSAidan Dodds     strm.Printf("Contents of file '%s' read into allocation %" PRIu32, filename, alloc->id);
237955232f09SEwan Crawford     strm.EOL();
238055232f09SEwan Crawford 
238155232f09SEwan Crawford     return true;
238255232f09SEwan Crawford }
238355232f09SEwan Crawford 
238426e52a70SEwan Crawford // Function takes as parameters a byte buffer, which will eventually be written to file as the element header,
238526e52a70SEwan Crawford // an offset into that buffer, and an Element that will be saved into the buffer at the parametrised offset.
238626e52a70SEwan Crawford // Return value is the new offset after writing the element into the buffer.
2387b3f7f69dSAidan Dodds // Elements are saved to the file as the ElementHeader struct followed by offsets to the structs of all the element's
2388b3f7f69dSAidan Dodds // children.
238926e52a70SEwan Crawford size_t
2390b3f7f69dSAidan Dodds RenderScriptRuntime::PopulateElementHeaders(const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2391b3f7f69dSAidan Dodds                                             const Element &elem)
239226e52a70SEwan Crawford {
239326e52a70SEwan Crawford     // File struct for an element header with all the relevant details copied from elem.
239426e52a70SEwan Crawford     // We assume members are valid already.
239526e52a70SEwan Crawford     AllocationDetails::ElementHeader elem_header;
239626e52a70SEwan Crawford     elem_header.type = *elem.type.get();
239726e52a70SEwan Crawford     elem_header.kind = *elem.type_kind.get();
239826e52a70SEwan Crawford     elem_header.element_size = *elem.datum_size.get();
239926e52a70SEwan Crawford     elem_header.vector_size = *elem.type_vec_size.get();
240026e52a70SEwan Crawford     elem_header.array_size = elem.array_size.isValid() ? *elem.array_size.get() : 0;
240126e52a70SEwan Crawford     const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
240226e52a70SEwan Crawford 
240326e52a70SEwan Crawford     // Copy struct into buffer and advance offset
2404b3f7f69dSAidan Dodds     // We assume that header_buffer has been checked for nullptr before this method is called
240526e52a70SEwan Crawford     memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
240626e52a70SEwan Crawford     offset += elem_header_size;
240726e52a70SEwan Crawford 
240826e52a70SEwan Crawford     // Starting offset of child ElementHeader struct
240926e52a70SEwan Crawford     size_t child_offset = offset + ((elem.children.size() + 1) * sizeof(uint32_t));
241026e52a70SEwan Crawford     for (const RenderScriptRuntime::Element &child : elem.children)
241126e52a70SEwan Crawford     {
241226e52a70SEwan Crawford         // Recursively populate the buffer with the element header structs of children.
241326e52a70SEwan Crawford         // Then save the offsets where they were set after the parent element header.
241426e52a70SEwan Crawford         memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
241526e52a70SEwan Crawford         offset += sizeof(uint32_t);
241626e52a70SEwan Crawford 
241726e52a70SEwan Crawford         child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
241826e52a70SEwan Crawford     }
241926e52a70SEwan Crawford 
242026e52a70SEwan Crawford     // Zero indicates no more children
242126e52a70SEwan Crawford     memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
242226e52a70SEwan Crawford 
242326e52a70SEwan Crawford     return child_offset;
242426e52a70SEwan Crawford }
242526e52a70SEwan Crawford 
2426b3f7f69dSAidan Dodds // Given an Element object this function returns the total size needed in the file header to store the element's
2427b3f7f69dSAidan Dodds // details.
242826e52a70SEwan Crawford // Taking into account the size of the element header struct, plus the offsets to all the element's children.
242926e52a70SEwan Crawford // Function is recursive so that the size of all ancestors is taken into account.
243026e52a70SEwan Crawford size_t
243126e52a70SEwan Crawford RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem)
243226e52a70SEwan Crawford {
243326e52a70SEwan Crawford     size_t size = (elem.children.size() + 1) * sizeof(uint32_t); // Offsets to children plus zero terminator
243426e52a70SEwan Crawford     size += sizeof(AllocationDetails::ElementHeader);            // Size of header struct with type details
243526e52a70SEwan Crawford 
243626e52a70SEwan Crawford     // Calculate recursively for all descendants
243726e52a70SEwan Crawford     for (const Element &child : elem.children)
243826e52a70SEwan Crawford         size += CalculateElementHeaderSize(child);
243926e52a70SEwan Crawford 
244026e52a70SEwan Crawford     return size;
244126e52a70SEwan Crawford }
244226e52a70SEwan Crawford 
244355232f09SEwan Crawford // Function copies allocation contents into a binary file.
244455232f09SEwan Crawford // This file can then be loaded later into a different allocation.
244555232f09SEwan Crawford // There is a header, FileHeader, before the allocation data containing meta-data.
244655232f09SEwan Crawford bool
244755232f09SEwan Crawford RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id, const char *filename, StackFrame *frame_ptr)
244855232f09SEwan Crawford {
244955232f09SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
245055232f09SEwan Crawford 
245155232f09SEwan Crawford     // Find allocation with the given id
245255232f09SEwan Crawford     AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
245355232f09SEwan Crawford     if (!alloc)
245455232f09SEwan Crawford         return false;
245555232f09SEwan Crawford 
245655232f09SEwan Crawford     if (log)
2457b3f7f69dSAidan Dodds         log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__, *alloc->address.get());
245855232f09SEwan Crawford 
245955232f09SEwan Crawford     // JIT all the allocation details
24608b59062aSEwan Crawford     if (alloc->shouldRefresh())
246155232f09SEwan Crawford     {
246255232f09SEwan Crawford         if (log)
2463b3f7f69dSAidan Dodds             log->Printf("%s - allocation details not calculated yet, jitting info.", __FUNCTION__);
246455232f09SEwan Crawford 
246555232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
246655232f09SEwan Crawford         {
246755232f09SEwan Crawford             if (log)
2468b3f7f69dSAidan Dodds                 log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
24694cfc9198SSylvestre Ledru             return false;
247055232f09SEwan Crawford         }
247155232f09SEwan Crawford     }
247255232f09SEwan Crawford 
2473b3f7f69dSAidan Dodds     assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid() &&
2474b3f7f69dSAidan Dodds            alloc->element.datum_size.get() && alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2475b3f7f69dSAidan Dodds            "Allocation information not available");
247655232f09SEwan Crawford 
247755232f09SEwan Crawford     // Check we can create writable file
247855232f09SEwan Crawford     FileSpec file_spec(filename, true);
247955232f09SEwan Crawford     File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionTruncate);
248055232f09SEwan Crawford     if (!file)
248155232f09SEwan Crawford     {
248255232f09SEwan Crawford         strm.Printf("Error: Failed to open '%s' for writing", filename);
248355232f09SEwan Crawford         strm.EOL();
248455232f09SEwan Crawford         return false;
248555232f09SEwan Crawford     }
248655232f09SEwan Crawford 
248755232f09SEwan Crawford     // Read allocation into buffer of heap memory
248855232f09SEwan Crawford     const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
248955232f09SEwan Crawford     if (!buffer)
249055232f09SEwan Crawford     {
249155232f09SEwan Crawford         strm.Printf("Error: Couldn't read allocation data into buffer");
249255232f09SEwan Crawford         strm.EOL();
249355232f09SEwan Crawford         return false;
249455232f09SEwan Crawford     }
249555232f09SEwan Crawford 
249655232f09SEwan Crawford     // Create the file header
249755232f09SEwan Crawford     AllocationDetails::FileHeader head;
2498b3f7f69dSAidan Dodds     memcpy(head.ident, "RSAD", 4);
24992d62328aSEwan Crawford     head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
25002d62328aSEwan Crawford     head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
25012d62328aSEwan Crawford     head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
250226e52a70SEwan Crawford 
250326e52a70SEwan Crawford     const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
250426e52a70SEwan Crawford     assert((sizeof(AllocationDetails::FileHeader) + element_header_size) < UINT16_MAX && "Element header too large");
250526e52a70SEwan Crawford     head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) + element_header_size);
250655232f09SEwan Crawford 
250755232f09SEwan Crawford     // Write the file header
250855232f09SEwan Crawford     size_t num_bytes = sizeof(AllocationDetails::FileHeader);
250926e52a70SEwan Crawford     if (log)
2510cec91ef9SGreg Clayton         log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__, (uint64_t)num_bytes);
251126e52a70SEwan Crawford 
251226e52a70SEwan Crawford     Error err = file.Write(&head, num_bytes);
251326e52a70SEwan Crawford     if (!err.Success())
251426e52a70SEwan Crawford     {
251526e52a70SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
251626e52a70SEwan Crawford         strm.EOL();
251726e52a70SEwan Crawford         return false;
251826e52a70SEwan Crawford     }
251926e52a70SEwan Crawford 
252026e52a70SEwan Crawford     // Create the headers describing the element type of the allocation.
252126e52a70SEwan Crawford     std::shared_ptr<uint8_t> element_header_buffer(new uint8_t[element_header_size]);
252226e52a70SEwan Crawford     if (element_header_buffer == nullptr)
252326e52a70SEwan Crawford     {
2524cec91ef9SGreg Clayton         strm.Printf("Internal Error: Couldn't allocate %" PRIu64 " bytes on the heap", (uint64_t)element_header_size);
252526e52a70SEwan Crawford         strm.EOL();
252626e52a70SEwan Crawford         return false;
252726e52a70SEwan Crawford     }
252826e52a70SEwan Crawford 
252926e52a70SEwan Crawford     PopulateElementHeaders(element_header_buffer, 0, alloc->element);
253026e52a70SEwan Crawford 
253126e52a70SEwan Crawford     // Write headers for allocation element type to file
253226e52a70SEwan Crawford     num_bytes = element_header_size;
253326e52a70SEwan Crawford     if (log)
2534cec91ef9SGreg Clayton         log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.", __FUNCTION__, (uint64_t)num_bytes);
253526e52a70SEwan Crawford 
253626e52a70SEwan Crawford     err = file.Write(element_header_buffer.get(), num_bytes);
253755232f09SEwan Crawford     if (!err.Success())
253855232f09SEwan Crawford     {
253955232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
254055232f09SEwan Crawford         strm.EOL();
254155232f09SEwan Crawford         return false;
254255232f09SEwan Crawford     }
254355232f09SEwan Crawford 
254455232f09SEwan Crawford     // Write allocation data to file
254555232f09SEwan Crawford     num_bytes = static_cast<size_t>(*alloc->size.get());
254655232f09SEwan Crawford     if (log)
2547cec91ef9SGreg Clayton         log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__, (uint64_t)num_bytes);
254855232f09SEwan Crawford 
254955232f09SEwan Crawford     err = file.Write(buffer.get(), num_bytes);
255055232f09SEwan Crawford     if (!err.Success())
255155232f09SEwan Crawford     {
255255232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
255355232f09SEwan Crawford         strm.EOL();
255455232f09SEwan Crawford         return false;
255555232f09SEwan Crawford     }
255655232f09SEwan Crawford 
255755232f09SEwan Crawford     strm.Printf("Allocation written to file '%s'", filename);
255855232f09SEwan Crawford     strm.EOL();
255915f2bd95SEwan Crawford     return true;
256015f2bd95SEwan Crawford }
256115f2bd95SEwan Crawford 
25625ec532a9SColin Riley bool
25635ec532a9SColin Riley RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp)
25645ec532a9SColin Riley {
25654640cde1SColin Riley     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
25664640cde1SColin Riley 
25675ec532a9SColin Riley     if (module_sp)
25685ec532a9SColin Riley     {
25695ec532a9SColin Riley         for (const auto &rs_module : m_rsmodules)
25705ec532a9SColin Riley         {
25714640cde1SColin Riley             if (rs_module->m_module == module_sp)
25727dc7771cSEwan Crawford             {
25737dc7771cSEwan Crawford                 // Check if the user has enabled automatically breaking on
25747dc7771cSEwan Crawford                 // all RS kernels.
25757dc7771cSEwan Crawford                 if (m_breakAllKernels)
25767dc7771cSEwan Crawford                     BreakOnModuleKernels(rs_module);
25777dc7771cSEwan Crawford 
25785ec532a9SColin Riley                 return false;
25795ec532a9SColin Riley             }
25807dc7771cSEwan Crawford         }
2581ef20b08fSColin Riley         bool module_loaded = false;
2582ef20b08fSColin Riley         switch (GetModuleKind(module_sp))
2583ef20b08fSColin Riley         {
2584ef20b08fSColin Riley             case eModuleKindKernelObj:
2585ef20b08fSColin Riley             {
25864640cde1SColin Riley                 RSModuleDescriptorSP module_desc;
25874640cde1SColin Riley                 module_desc.reset(new RSModuleDescriptor(module_sp));
25884640cde1SColin Riley                 if (module_desc->ParseRSInfo())
25895ec532a9SColin Riley                 {
25905ec532a9SColin Riley                     m_rsmodules.push_back(module_desc);
2591ef20b08fSColin Riley                     module_loaded = true;
25925ec532a9SColin Riley                 }
25934640cde1SColin Riley                 if (module_loaded)
25944640cde1SColin Riley                 {
25954640cde1SColin Riley                     FixupScriptDetails(module_desc);
25964640cde1SColin Riley                 }
2597ef20b08fSColin Riley                 break;
2598ef20b08fSColin Riley             }
2599ef20b08fSColin Riley             case eModuleKindDriver:
26004640cde1SColin Riley             {
26014640cde1SColin Riley                 if (!m_libRSDriver)
26024640cde1SColin Riley                 {
26034640cde1SColin Riley                     m_libRSDriver = module_sp;
26044640cde1SColin Riley                     LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
26054640cde1SColin Riley                 }
26064640cde1SColin Riley                 break;
26074640cde1SColin Riley             }
2608ef20b08fSColin Riley             case eModuleKindImpl:
26094640cde1SColin Riley             {
26104640cde1SColin Riley                 m_libRSCpuRef = module_sp;
26114640cde1SColin Riley                 break;
26124640cde1SColin Riley             }
2613ef20b08fSColin Riley             case eModuleKindLibRS:
26144640cde1SColin Riley             {
26154640cde1SColin Riley                 if (!m_libRS)
26164640cde1SColin Riley                 {
26174640cde1SColin Riley                     m_libRS = module_sp;
26184640cde1SColin Riley                     static ConstString gDbgPresentStr("gDebuggerPresent");
2619b3f7f69dSAidan Dodds                     const Symbol *debug_present =
2620b3f7f69dSAidan Dodds                         m_libRS->FindFirstSymbolWithNameAndType(gDbgPresentStr, eSymbolTypeData);
26214640cde1SColin Riley                     if (debug_present)
26224640cde1SColin Riley                     {
26234640cde1SColin Riley                         Error error;
26244640cde1SColin Riley                         uint32_t flag = 0x00000001U;
26254640cde1SColin Riley                         Target &target = GetProcess()->GetTarget();
2626358cf1eaSGreg Clayton                         addr_t addr = debug_present->GetLoadAddress(&target);
26274640cde1SColin Riley                         GetProcess()->WriteMemory(addr, &flag, sizeof(flag), error);
26284640cde1SColin Riley                         if (error.Success())
26294640cde1SColin Riley                         {
26304640cde1SColin Riley                             if (log)
2631b3f7f69dSAidan Dodds                                 log->Printf("%s - debugger present flag set on debugee.", __FUNCTION__);
26324640cde1SColin Riley 
26334640cde1SColin Riley                             m_debuggerPresentFlagged = true;
26344640cde1SColin Riley                         }
26354640cde1SColin Riley                         else if (log)
26364640cde1SColin Riley                         {
2637b3f7f69dSAidan Dodds                             log->Printf("%s - error writing debugger present flags '%s' ", __FUNCTION__,
2638b3f7f69dSAidan Dodds                                         error.AsCString());
26394640cde1SColin Riley                         }
26404640cde1SColin Riley                     }
26414640cde1SColin Riley                     else if (log)
26424640cde1SColin Riley                     {
2643b3f7f69dSAidan Dodds                         log->Printf("%s - error writing debugger present flags - symbol not found", __FUNCTION__);
26444640cde1SColin Riley                     }
26454640cde1SColin Riley                 }
26464640cde1SColin Riley                 break;
26474640cde1SColin Riley             }
2648ef20b08fSColin Riley             default:
2649ef20b08fSColin Riley                 break;
2650ef20b08fSColin Riley         }
2651ef20b08fSColin Riley         if (module_loaded)
2652ef20b08fSColin Riley             Update();
2653ef20b08fSColin Riley         return module_loaded;
26545ec532a9SColin Riley     }
26555ec532a9SColin Riley     return false;
26565ec532a9SColin Riley }
26575ec532a9SColin Riley 
2658ef20b08fSColin Riley void
2659ef20b08fSColin Riley RenderScriptRuntime::Update()
2660ef20b08fSColin Riley {
2661ef20b08fSColin Riley     if (m_rsmodules.size() > 0)
2662ef20b08fSColin Riley     {
2663ef20b08fSColin Riley         if (!m_initiated)
2664ef20b08fSColin Riley         {
2665ef20b08fSColin Riley             Initiate();
2666ef20b08fSColin Riley         }
2667ef20b08fSColin Riley     }
2668ef20b08fSColin Riley }
2669ef20b08fSColin Riley 
26705ec532a9SColin Riley // The maximum line length of an .rs.info packet
26715ec532a9SColin Riley #define MAXLINE 500
2672b0be30f7SAidan Dodds #define STRINGIFY(x) #x
2673b0be30f7SAidan Dodds #define MAXLINESTR_(x) "%" STRINGIFY(x) "s"
2674b0be30f7SAidan Dodds #define MAXLINESTR MAXLINESTR_(MAXLINE)
26755ec532a9SColin Riley 
26765ec532a9SColin Riley // The .rs.info symbol in renderscript modules contains a string which needs to be parsed.
26775ec532a9SColin Riley // The string is basic and is parsed on a line by line basis.
26785ec532a9SColin Riley bool
26795ec532a9SColin Riley RSModuleDescriptor::ParseRSInfo()
26805ec532a9SColin Riley {
2681b0be30f7SAidan Dodds     assert(m_module);
26825ec532a9SColin Riley     const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
2683b0be30f7SAidan Dodds     if (!info_sym)
2684b0be30f7SAidan Dodds         return false;
2685b0be30f7SAidan Dodds 
2686358cf1eaSGreg Clayton     const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
2687b0be30f7SAidan Dodds     if (addr == LLDB_INVALID_ADDRESS)
2688b0be30f7SAidan Dodds         return false;
2689b0be30f7SAidan Dodds 
26905ec532a9SColin Riley     const addr_t size = info_sym->GetByteSize();
26915ec532a9SColin Riley     const FileSpec fs = m_module->GetFileSpec();
26925ec532a9SColin Riley 
2693b0be30f7SAidan Dodds     const DataBufferSP buffer = fs.ReadFileContents(addr, size);
26945ec532a9SColin Riley     if (!buffer)
26955ec532a9SColin Riley         return false;
26965ec532a9SColin Riley 
2697b0be30f7SAidan Dodds     // split rs.info. contents into lines
26985ec532a9SColin Riley     std::vector<std::string> info_lines;
26995ec532a9SColin Riley     {
2700b0be30f7SAidan Dodds         const std::string info((const char *)buffer->GetBytes());
2701b0be30f7SAidan Dodds         for (size_t tail = 0; tail < info.size();)
2702b0be30f7SAidan Dodds         {
2703b0be30f7SAidan Dodds             // find next new line or end of string
2704b0be30f7SAidan Dodds             size_t head = info.find('\n', tail);
2705b0be30f7SAidan Dodds             head = (head == std::string::npos) ? info.size() : head;
2706b0be30f7SAidan Dodds             std::string line = info.substr(tail, head - tail);
2707b0be30f7SAidan Dodds             // add to line list
2708b0be30f7SAidan Dodds             info_lines.push_back(line);
2709b0be30f7SAidan Dodds             tail = head + 1;
27105ec532a9SColin Riley         }
2711b0be30f7SAidan Dodds     }
2712b0be30f7SAidan Dodds 
27137ccf1373SSaleem Abdulrasool     std::array<char, MAXLINE> name{{'\0'}};
27147ccf1373SSaleem Abdulrasool     std::array<char, MAXLINE> value{{'\0'}};
2715b0be30f7SAidan Dodds 
2716b0be30f7SAidan Dodds     // parse all text lines of .rs.info
2717b0be30f7SAidan Dodds     for (auto line = info_lines.begin(); line != info_lines.end(); ++line)
27185ec532a9SColin Riley     {
27195ec532a9SColin Riley         uint32_t numDefns = 0;
2720b0be30f7SAidan Dodds         if (sscanf(line->c_str(), "exportVarCount: %" PRIu32 "", &numDefns) == 1)
27215ec532a9SColin Riley         {
27225ec532a9SColin Riley             while (numDefns--)
2723b0be30f7SAidan Dodds                 m_globals.push_back(RSGlobalDescriptor(this, (++line)->c_str()));
27245ec532a9SColin Riley         }
2725b0be30f7SAidan Dodds         else if (sscanf(line->c_str(), "exportForEachCount: %" PRIu32 "", &numDefns) == 1)
27265ec532a9SColin Riley         {
27275ec532a9SColin Riley             while (numDefns--)
27285ec532a9SColin Riley             {
27295ec532a9SColin Riley                 uint32_t slot = 0;
27305ec532a9SColin Riley                 name[0] = '\0';
2731b0be30f7SAidan Dodds                 static const char *fmt_s = "%" PRIu32 " - " MAXLINESTR;
2732b0be30f7SAidan Dodds                 if (sscanf((++line)->c_str(), fmt_s, &slot, name.data()) == 2)
27335ec532a9SColin Riley                 {
2734b0be30f7SAidan Dodds                     if (name[0] != '\0')
2735b0be30f7SAidan Dodds                         m_kernels.push_back(RSKernelDescriptor(this, name.data(), slot));
27364640cde1SColin Riley                 }
27374640cde1SColin Riley             }
27384640cde1SColin Riley         }
2739b0be30f7SAidan Dodds         else if (sscanf(line->c_str(), "pragmaCount: %" PRIu32 "", &numDefns) == 1)
27404640cde1SColin Riley         {
27414640cde1SColin Riley             while (numDefns--)
27424640cde1SColin Riley             {
2743b0be30f7SAidan Dodds                 name[0] = value[0] = '\0';
2744b0be30f7SAidan Dodds                 static const char *fmt_s = MAXLINESTR " - " MAXLINESTR;
2745b0be30f7SAidan Dodds                 if (sscanf((++line)->c_str(), fmt_s, name.data(), value.data()) != 0)
27464640cde1SColin Riley                 {
2747b0be30f7SAidan Dodds                     if (name[0] != '\0')
2748b0be30f7SAidan Dodds                         m_pragmas[std::string(name.data())] = value.data();
27495ec532a9SColin Riley                 }
27505ec532a9SColin Riley             }
27515ec532a9SColin Riley         }
2752b0be30f7SAidan Dodds         else
27535ec532a9SColin Riley         {
2754b0be30f7SAidan Dodds             Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2755b0be30f7SAidan Dodds             if (log)
2756b0be30f7SAidan Dodds             {
2757b0be30f7SAidan Dodds                 log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__, line->c_str());
2758b0be30f7SAidan Dodds             }
2759b0be30f7SAidan Dodds         }
27605ec532a9SColin Riley     }
27615ec532a9SColin Riley 
2762b0be30f7SAidan Dodds     // 'root' kernel should always be present
27635ec532a9SColin Riley     return m_kernels.size() > 0;
27645ec532a9SColin Riley }
27655ec532a9SColin Riley 
27665ec532a9SColin Riley void
27674640cde1SColin Riley RenderScriptRuntime::Status(Stream &strm) const
27684640cde1SColin Riley {
27694640cde1SColin Riley     if (m_libRS)
27704640cde1SColin Riley     {
27714640cde1SColin Riley         strm.Printf("Runtime Library discovered.");
27724640cde1SColin Riley         strm.EOL();
27734640cde1SColin Riley     }
27744640cde1SColin Riley     if (m_libRSDriver)
27754640cde1SColin Riley     {
27764640cde1SColin Riley         strm.Printf("Runtime Driver discovered.");
27774640cde1SColin Riley         strm.EOL();
27784640cde1SColin Riley     }
27794640cde1SColin Riley     if (m_libRSCpuRef)
27804640cde1SColin Riley     {
27814640cde1SColin Riley         strm.Printf("CPU Reference Implementation discovered.");
27824640cde1SColin Riley         strm.EOL();
27834640cde1SColin Riley     }
27844640cde1SColin Riley 
27854640cde1SColin Riley     if (m_runtimeHooks.size())
27864640cde1SColin Riley     {
27874640cde1SColin Riley         strm.Printf("Runtime functions hooked:");
27884640cde1SColin Riley         strm.EOL();
27894640cde1SColin Riley         for (auto b : m_runtimeHooks)
27904640cde1SColin Riley         {
27914640cde1SColin Riley             strm.Indent(b.second->defn->name);
27924640cde1SColin Riley             strm.EOL();
27934640cde1SColin Riley         }
27944640cde1SColin Riley     }
27954640cde1SColin Riley     else
27964640cde1SColin Riley     {
27974640cde1SColin Riley         strm.Printf("Runtime is not hooked.");
27984640cde1SColin Riley         strm.EOL();
27994640cde1SColin Riley     }
28004640cde1SColin Riley }
28014640cde1SColin Riley 
28024640cde1SColin Riley void
28034640cde1SColin Riley RenderScriptRuntime::DumpContexts(Stream &strm) const
28044640cde1SColin Riley {
28054640cde1SColin Riley     strm.Printf("Inferred RenderScript Contexts:");
28064640cde1SColin Riley     strm.EOL();
28074640cde1SColin Riley     strm.IndentMore();
28084640cde1SColin Riley 
28094640cde1SColin Riley     std::map<addr_t, uint64_t> contextReferences;
28104640cde1SColin Riley 
281178f339d1SEwan Crawford     // Iterate over all of the currently discovered scripts.
281278f339d1SEwan Crawford     // Note: We cant push or pop from m_scripts inside this loop or it may invalidate script.
28134640cde1SColin Riley     for (const auto &script : m_scripts)
28144640cde1SColin Riley     {
281578f339d1SEwan Crawford         if (!script->context.isValid())
281678f339d1SEwan Crawford             continue;
281778f339d1SEwan Crawford         lldb::addr_t context = *script->context;
281878f339d1SEwan Crawford 
281978f339d1SEwan Crawford         if (contextReferences.find(context) != contextReferences.end())
28204640cde1SColin Riley         {
282178f339d1SEwan Crawford             contextReferences[context]++;
28224640cde1SColin Riley         }
28234640cde1SColin Riley         else
28244640cde1SColin Riley         {
282578f339d1SEwan Crawford             contextReferences[context] = 1;
28264640cde1SColin Riley         }
28274640cde1SColin Riley     }
28284640cde1SColin Riley 
28294640cde1SColin Riley     for (const auto &cRef : contextReferences)
28304640cde1SColin Riley     {
28314640cde1SColin Riley         strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances", cRef.first, cRef.second);
28324640cde1SColin Riley         strm.EOL();
28334640cde1SColin Riley     }
28344640cde1SColin Riley     strm.IndentLess();
28354640cde1SColin Riley }
28364640cde1SColin Riley 
28374640cde1SColin Riley void
28384640cde1SColin Riley RenderScriptRuntime::DumpKernels(Stream &strm) const
28394640cde1SColin Riley {
28404640cde1SColin Riley     strm.Printf("RenderScript Kernels:");
28414640cde1SColin Riley     strm.EOL();
28424640cde1SColin Riley     strm.IndentMore();
28434640cde1SColin Riley     for (const auto &module : m_rsmodules)
28444640cde1SColin Riley     {
28454640cde1SColin Riley         strm.Printf("Resource '%s':", module->m_resname.c_str());
28464640cde1SColin Riley         strm.EOL();
28474640cde1SColin Riley         for (const auto &kernel : module->m_kernels)
28484640cde1SColin Riley         {
28494640cde1SColin Riley             strm.Indent(kernel.m_name.AsCString());
28504640cde1SColin Riley             strm.EOL();
28514640cde1SColin Riley         }
28524640cde1SColin Riley     }
28534640cde1SColin Riley     strm.IndentLess();
28544640cde1SColin Riley }
28554640cde1SColin Riley 
2856a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails *
2857a0f08674SEwan Crawford RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id)
2858a0f08674SEwan Crawford {
2859a0f08674SEwan Crawford     AllocationDetails *alloc = nullptr;
2860a0f08674SEwan Crawford 
2861a0f08674SEwan Crawford     // See if we can find allocation using id as an index;
2862b3f7f69dSAidan Dodds     if (alloc_id <= m_allocations.size() && alloc_id != 0 && m_allocations[alloc_id - 1]->id == alloc_id)
2863a0f08674SEwan Crawford     {
2864a0f08674SEwan Crawford         alloc = m_allocations[alloc_id - 1].get();
2865a0f08674SEwan Crawford         return alloc;
2866a0f08674SEwan Crawford     }
2867a0f08674SEwan Crawford 
2868a0f08674SEwan Crawford     // Fallback to searching
2869a0f08674SEwan Crawford     for (const auto &a : m_allocations)
2870a0f08674SEwan Crawford     {
2871a0f08674SEwan Crawford         if (a->id == alloc_id)
2872a0f08674SEwan Crawford         {
2873a0f08674SEwan Crawford             alloc = a.get();
2874a0f08674SEwan Crawford             break;
2875a0f08674SEwan Crawford         }
2876a0f08674SEwan Crawford     }
2877a0f08674SEwan Crawford 
2878a0f08674SEwan Crawford     if (alloc == nullptr)
2879a0f08674SEwan Crawford     {
2880b3f7f69dSAidan Dodds         strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32, alloc_id);
2881a0f08674SEwan Crawford         strm.EOL();
2882a0f08674SEwan Crawford     }
2883a0f08674SEwan Crawford 
2884a0f08674SEwan Crawford     return alloc;
2885a0f08674SEwan Crawford }
2886a0f08674SEwan Crawford 
2887a0f08674SEwan Crawford // Prints the contents of an allocation to the output stream, which may be a file
2888a0f08674SEwan Crawford bool
2889a0f08674SEwan Crawford RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr, const uint32_t id)
2890a0f08674SEwan Crawford {
2891a0f08674SEwan Crawford     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2892a0f08674SEwan Crawford 
2893a0f08674SEwan Crawford     // Check we can find the desired allocation
2894a0f08674SEwan Crawford     AllocationDetails *alloc = FindAllocByID(strm, id);
2895a0f08674SEwan Crawford     if (!alloc)
2896a0f08674SEwan Crawford         return false; // FindAllocByID() will print error message for us here
2897a0f08674SEwan Crawford 
2898a0f08674SEwan Crawford     if (log)
2899b3f7f69dSAidan Dodds         log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__, *alloc->address.get());
2900a0f08674SEwan Crawford 
2901a0f08674SEwan Crawford     // Check we have information about the allocation, if not calculate it
29028b59062aSEwan Crawford     if (alloc->shouldRefresh())
2903a0f08674SEwan Crawford     {
2904a0f08674SEwan Crawford         if (log)
2905b3f7f69dSAidan Dodds             log->Printf("%s - allocation details not calculated yet, jitting info.", __FUNCTION__);
2906a0f08674SEwan Crawford 
2907a0f08674SEwan Crawford         // JIT all the allocation information
2908a0f08674SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
2909a0f08674SEwan Crawford         {
2910a0f08674SEwan Crawford             strm.Printf("Error: Couldn't JIT allocation details");
2911a0f08674SEwan Crawford             strm.EOL();
2912a0f08674SEwan Crawford             return false;
2913a0f08674SEwan Crawford         }
2914a0f08674SEwan Crawford     }
2915a0f08674SEwan Crawford 
2916a0f08674SEwan Crawford     // Establish format and size of each data element
2917b3f7f69dSAidan Dodds     const uint32_t vec_size = *alloc->element.type_vec_size.get();
29188b244e21SEwan Crawford     const Element::DataType type = *alloc->element.type.get();
2919a0f08674SEwan Crawford 
2920b3f7f69dSAidan Dodds     assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT && "Invalid allocation type");
2921a0f08674SEwan Crawford 
29222e920715SEwan Crawford     lldb::Format format;
29232e920715SEwan Crawford     if (type >= Element::RS_TYPE_ELEMENT)
29242e920715SEwan Crawford         format = eFormatHex;
29252e920715SEwan Crawford     else
29262e920715SEwan Crawford         format = vec_size == 1 ? static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatSingle])
2927a0f08674SEwan Crawford                                : static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatVector]);
2928a0f08674SEwan Crawford 
2929b3f7f69dSAidan Dodds     const uint32_t data_size = *alloc->element.datum_size.get();
2930a0f08674SEwan Crawford 
2931a0f08674SEwan Crawford     if (log)
2932b3f7f69dSAidan Dodds         log->Printf("%s - element size %" PRIu32 " bytes, including padding", __FUNCTION__, data_size);
2933a0f08674SEwan Crawford 
293455232f09SEwan Crawford     // Allocate a buffer to copy data into
293555232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
293655232f09SEwan Crawford     if (!buffer)
293755232f09SEwan Crawford     {
29382e920715SEwan Crawford         strm.Printf("Error: Couldn't read allocation data");
293955232f09SEwan Crawford         strm.EOL();
294055232f09SEwan Crawford         return false;
294155232f09SEwan Crawford     }
294255232f09SEwan Crawford 
2943a0f08674SEwan Crawford     // Calculate stride between rows as there may be padding at end of rows since
2944a0f08674SEwan Crawford     // allocated memory is 16-byte aligned
2945a0f08674SEwan Crawford     if (!alloc->stride.isValid())
2946a0f08674SEwan Crawford     {
2947a0f08674SEwan Crawford         if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
2948a0f08674SEwan Crawford             alloc->stride = 0;
2949a0f08674SEwan Crawford         else if (!JITAllocationStride(alloc, frame_ptr))
2950a0f08674SEwan Crawford         {
2951a0f08674SEwan Crawford             strm.Printf("Error: Couldn't calculate allocation row stride");
2952a0f08674SEwan Crawford             strm.EOL();
2953a0f08674SEwan Crawford             return false;
2954a0f08674SEwan Crawford         }
2955a0f08674SEwan Crawford     }
2956b3f7f69dSAidan Dodds     const uint32_t stride = *alloc->stride.get();
2957b3f7f69dSAidan Dodds     const uint32_t size = *alloc->size.get(); // Size of whole allocation
2958b3f7f69dSAidan Dodds     const uint32_t padding = alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
2959a0f08674SEwan Crawford     if (log)
2960b3f7f69dSAidan Dodds         log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32 " bytes, padding %" PRIu32,
2961b3f7f69dSAidan Dodds                     __FUNCTION__, stride, size, padding);
2962a0f08674SEwan Crawford 
2963a0f08674SEwan Crawford     // Find dimensions used to index loops, so need to be non-zero
2964b3f7f69dSAidan Dodds     uint32_t dim_x = alloc->dimension.get()->dim_1;
2965a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 1 : dim_x;
2966a0f08674SEwan Crawford 
2967b3f7f69dSAidan Dodds     uint32_t dim_y = alloc->dimension.get()->dim_2;
2968a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 1 : dim_y;
2969a0f08674SEwan Crawford 
2970b3f7f69dSAidan Dodds     uint32_t dim_z = alloc->dimension.get()->dim_3;
2971a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 1 : dim_z;
2972a0f08674SEwan Crawford 
297355232f09SEwan Crawford     // Use data extractor to format output
297455232f09SEwan Crawford     const uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
297555232f09SEwan Crawford     DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(), archByteSize);
297655232f09SEwan Crawford 
2977b3f7f69dSAidan Dodds     uint32_t offset = 0;   // Offset in buffer to next element to be printed
2978b3f7f69dSAidan Dodds     uint32_t prev_row = 0; // Offset to the start of the previous row
2979a0f08674SEwan Crawford 
2980a0f08674SEwan Crawford     // Iterate over allocation dimensions, printing results to user
2981a0f08674SEwan Crawford     strm.Printf("Data (X, Y, Z):");
2982b3f7f69dSAidan Dodds     for (uint32_t z = 0; z < dim_z; ++z)
2983a0f08674SEwan Crawford     {
2984b3f7f69dSAidan Dodds         for (uint32_t y = 0; y < dim_y; ++y)
2985a0f08674SEwan Crawford         {
2986a0f08674SEwan Crawford             // Use stride to index start of next row.
2987a0f08674SEwan Crawford             if (!(y == 0 && z == 0))
2988a0f08674SEwan Crawford                 offset = prev_row + stride;
2989a0f08674SEwan Crawford             prev_row = offset;
2990a0f08674SEwan Crawford 
2991a0f08674SEwan Crawford             // Print each element in the row individually
2992b3f7f69dSAidan Dodds             for (uint32_t x = 0; x < dim_x; ++x)
2993a0f08674SEwan Crawford             {
2994b3f7f69dSAidan Dodds                 strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
29958b244e21SEwan Crawford                 if ((type == Element::RS_TYPE_NONE) && (alloc->element.children.size() > 0) &&
2996fe06b5adSAdrian McCarthy                     (alloc->element.type_name != Element::GetFallbackStructName()))
29978b244e21SEwan Crawford                 {
29988b244e21SEwan Crawford                     // Here we are dumping an Element of struct type.
29998b244e21SEwan Crawford                     // This is done using expression evaluation with the name of the struct type and pointer to element.
30008b244e21SEwan Crawford 
30018b244e21SEwan Crawford                     // Don't print the name of the resulting expression, since this will be '$[0-9]+'
30028b244e21SEwan Crawford                     DumpValueObjectOptions expr_options;
30038b244e21SEwan Crawford                     expr_options.SetHideName(true);
30048b244e21SEwan Crawford 
30058b244e21SEwan Crawford                     // Setup expression as derefrencing a pointer cast to element address.
3006ea0636b5SEwan Crawford                     char expr_char_buffer[jit_max_expr_size];
3007ea0636b5SEwan Crawford                     int chars_written = snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
30088b244e21SEwan Crawford                                                  alloc->element.type_name.AsCString(), *alloc->data_ptr.get() + offset);
30098b244e21SEwan Crawford 
3010ea0636b5SEwan Crawford                     if (chars_written < 0 || chars_written >= jit_max_expr_size)
30118b244e21SEwan Crawford                     {
30128b244e21SEwan Crawford                         if (log)
3013b3f7f69dSAidan Dodds                             log->Printf("%s - error in snprintf().", __FUNCTION__);
30148b244e21SEwan Crawford                         continue;
30158b244e21SEwan Crawford                     }
30168b244e21SEwan Crawford 
30178b244e21SEwan Crawford                     // Evaluate expression
30188b244e21SEwan Crawford                     ValueObjectSP expr_result;
30198b244e21SEwan Crawford                     GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer, frame_ptr, expr_result);
30208b244e21SEwan Crawford 
30218b244e21SEwan Crawford                     // Print the results to our stream.
30228b244e21SEwan Crawford                     expr_result->Dump(strm, expr_options);
30238b244e21SEwan Crawford                 }
30248b244e21SEwan Crawford                 else
30258b244e21SEwan Crawford                 {
30268b244e21SEwan Crawford                     alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0, 0);
30278b244e21SEwan Crawford                 }
30288b244e21SEwan Crawford                 offset += data_size;
3029a0f08674SEwan Crawford             }
3030a0f08674SEwan Crawford         }
3031a0f08674SEwan Crawford     }
3032a0f08674SEwan Crawford     strm.EOL();
3033a0f08674SEwan Crawford 
3034a0f08674SEwan Crawford     return true;
3035a0f08674SEwan Crawford }
3036a0f08674SEwan Crawford 
30370d2bfcfbSEwan Crawford // Function recalculates all our cached information about allocations by jitting the
30380d2bfcfbSEwan Crawford // RS runtime regarding each allocation we know about.
30390d2bfcfbSEwan Crawford // Returns true if all allocations could be recomputed, false otherwise.
30400d2bfcfbSEwan Crawford bool
30410d2bfcfbSEwan Crawford RenderScriptRuntime::RecomputeAllAllocations(Stream &strm, StackFrame *frame_ptr)
30420d2bfcfbSEwan Crawford {
30430d2bfcfbSEwan Crawford     bool success = true;
30440d2bfcfbSEwan Crawford     for (auto &alloc : m_allocations)
30450d2bfcfbSEwan Crawford     {
30460d2bfcfbSEwan Crawford         // JIT current allocation information
30470d2bfcfbSEwan Crawford         if (!RefreshAllocation(alloc.get(), frame_ptr))
30480d2bfcfbSEwan Crawford         {
30490d2bfcfbSEwan Crawford             strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32 "\n", alloc->id);
30500d2bfcfbSEwan Crawford             success = false;
30510d2bfcfbSEwan Crawford         }
30520d2bfcfbSEwan Crawford     }
30530d2bfcfbSEwan Crawford 
30540d2bfcfbSEwan Crawford     if (success)
30550d2bfcfbSEwan Crawford         strm.Printf("All allocations successfully recomputed");
30560d2bfcfbSEwan Crawford     strm.EOL();
30570d2bfcfbSEwan Crawford 
30580d2bfcfbSEwan Crawford     return success;
30590d2bfcfbSEwan Crawford }
30600d2bfcfbSEwan Crawford 
3061b649b005SEwan Crawford // Prints information regarding currently loaded allocations.
306215f2bd95SEwan Crawford // These details are gathered by jitting the runtime, which has as latency.
3063b649b005SEwan Crawford // Index parameter specifies a single allocation ID to print, or a zero value to print them all
306415f2bd95SEwan Crawford void
3065b649b005SEwan Crawford RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr, const uint32_t index)
306615f2bd95SEwan Crawford {
306715f2bd95SEwan Crawford     strm.Printf("RenderScript Allocations:");
306815f2bd95SEwan Crawford     strm.EOL();
306915f2bd95SEwan Crawford     strm.IndentMore();
307015f2bd95SEwan Crawford 
307115f2bd95SEwan Crawford     for (auto &alloc : m_allocations)
307215f2bd95SEwan Crawford     {
3073b649b005SEwan Crawford         // index will only be zero if we want to print all allocations
3074b649b005SEwan Crawford         if (index != 0 && index != alloc->id)
3075b649b005SEwan Crawford             continue;
307615f2bd95SEwan Crawford 
307715f2bd95SEwan Crawford         // JIT current allocation information
3078b649b005SEwan Crawford         if (alloc->shouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr))
307915f2bd95SEwan Crawford         {
3080b3f7f69dSAidan Dodds             strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32, alloc->id);
3081b3f7f69dSAidan Dodds             strm.EOL();
308215f2bd95SEwan Crawford             continue;
308315f2bd95SEwan Crawford         }
308415f2bd95SEwan Crawford 
3085b3f7f69dSAidan Dodds         strm.Printf("%" PRIu32 ":", alloc->id);
3086b3f7f69dSAidan Dodds         strm.EOL();
308715f2bd95SEwan Crawford         strm.IndentMore();
308815f2bd95SEwan Crawford 
308915f2bd95SEwan Crawford         strm.Indent("Context: ");
309015f2bd95SEwan Crawford         if (!alloc->context.isValid())
309115f2bd95SEwan Crawford             strm.Printf("unknown\n");
309215f2bd95SEwan Crawford         else
309315f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
309415f2bd95SEwan Crawford 
309515f2bd95SEwan Crawford         strm.Indent("Address: ");
309615f2bd95SEwan Crawford         if (!alloc->address.isValid())
309715f2bd95SEwan Crawford             strm.Printf("unknown\n");
309815f2bd95SEwan Crawford         else
309915f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
310015f2bd95SEwan Crawford 
310115f2bd95SEwan Crawford         strm.Indent("Data pointer: ");
310215f2bd95SEwan Crawford         if (!alloc->data_ptr.isValid())
310315f2bd95SEwan Crawford             strm.Printf("unknown\n");
310415f2bd95SEwan Crawford         else
310515f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
310615f2bd95SEwan Crawford 
310715f2bd95SEwan Crawford         strm.Indent("Dimensions: ");
310815f2bd95SEwan Crawford         if (!alloc->dimension.isValid())
310915f2bd95SEwan Crawford             strm.Printf("unknown\n");
311015f2bd95SEwan Crawford         else
3111b3f7f69dSAidan Dodds             strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3112b3f7f69dSAidan Dodds                         alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2, alloc->dimension.get()->dim_3);
311315f2bd95SEwan Crawford 
311415f2bd95SEwan Crawford         strm.Indent("Data Type: ");
31158b244e21SEwan Crawford         if (!alloc->element.type.isValid() || !alloc->element.type_vec_size.isValid())
311615f2bd95SEwan Crawford             strm.Printf("unknown\n");
311715f2bd95SEwan Crawford         else
311815f2bd95SEwan Crawford         {
31198b244e21SEwan Crawford             const int vector_size = *alloc->element.type_vec_size.get();
31202e920715SEwan Crawford             Element::DataType type = *alloc->element.type.get();
312115f2bd95SEwan Crawford 
31228b244e21SEwan Crawford             if (!alloc->element.type_name.IsEmpty())
31238b244e21SEwan Crawford                 strm.Printf("%s\n", alloc->element.type_name.AsCString());
31242e920715SEwan Crawford             else
31252e920715SEwan Crawford             {
31262e920715SEwan Crawford                 // Enum value isn't monotonous, so doesn't always index RsDataTypeToString array
31272e920715SEwan Crawford                 if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3128b3f7f69dSAidan Dodds                     type = static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3129b3f7f69dSAidan Dodds                                                           Element::RS_TYPE_MATRIX_2X2 + 1);
31302e920715SEwan Crawford 
3131b3f7f69dSAidan Dodds                 if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3132b3f7f69dSAidan Dodds                              sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3133b3f7f69dSAidan Dodds                     vector_size > 4 || vector_size < 1)
313415f2bd95SEwan Crawford                     strm.Printf("invalid type\n");
313515f2bd95SEwan Crawford                 else
3136b3f7f69dSAidan Dodds                     strm.Printf("%s\n", AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3137b3f7f69dSAidan Dodds                                                                              [vector_size - 1]);
313815f2bd95SEwan Crawford             }
31392e920715SEwan Crawford         }
314015f2bd95SEwan Crawford 
314115f2bd95SEwan Crawford         strm.Indent("Data Kind: ");
31428b244e21SEwan Crawford         if (!alloc->element.type_kind.isValid())
314315f2bd95SEwan Crawford             strm.Printf("unknown\n");
314415f2bd95SEwan Crawford         else
314515f2bd95SEwan Crawford         {
31468b244e21SEwan Crawford             const Element::DataKind kind = *alloc->element.type_kind.get();
31478b244e21SEwan Crawford             if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
314815f2bd95SEwan Crawford                 strm.Printf("invalid kind\n");
314915f2bd95SEwan Crawford             else
3150b3f7f69dSAidan Dodds                 strm.Printf("%s\n", AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
315115f2bd95SEwan Crawford         }
315215f2bd95SEwan Crawford 
315315f2bd95SEwan Crawford         strm.EOL();
315415f2bd95SEwan Crawford         strm.IndentLess();
315515f2bd95SEwan Crawford     }
315615f2bd95SEwan Crawford     strm.IndentLess();
315715f2bd95SEwan Crawford }
315815f2bd95SEwan Crawford 
31597dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
31607dc7771cSEwan Crawford void
31617dc7771cSEwan Crawford RenderScriptRuntime::BreakOnModuleKernels(const RSModuleDescriptorSP rsmodule_sp)
31627dc7771cSEwan Crawford {
31637dc7771cSEwan Crawford     for (const auto &kernel : rsmodule_sp->m_kernels)
31647dc7771cSEwan Crawford     {
31657dc7771cSEwan Crawford         // Don't set breakpoint on 'root' kernel
31667dc7771cSEwan Crawford         if (strcmp(kernel.m_name.AsCString(), "root") == 0)
31677dc7771cSEwan Crawford             continue;
31687dc7771cSEwan Crawford 
31697dc7771cSEwan Crawford         CreateKernelBreakpoint(kernel.m_name);
31707dc7771cSEwan Crawford     }
31717dc7771cSEwan Crawford }
31727dc7771cSEwan Crawford 
31737dc7771cSEwan Crawford // Method is internally called by the 'kernel breakpoint all' command to
31747dc7771cSEwan Crawford // enable or disable breaking on all kernels.
31757dc7771cSEwan Crawford //
31767dc7771cSEwan Crawford // When do_break is true we want to enable this functionality.
31777dc7771cSEwan Crawford // When do_break is false we want to disable it.
31787dc7771cSEwan Crawford void
31797dc7771cSEwan Crawford RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target)
31807dc7771cSEwan Crawford {
318154782db7SEwan Crawford     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
31827dc7771cSEwan Crawford 
31837dc7771cSEwan Crawford     InitSearchFilter(target);
31847dc7771cSEwan Crawford 
31857dc7771cSEwan Crawford     // Set breakpoints on all the kernels
31867dc7771cSEwan Crawford     if (do_break && !m_breakAllKernels)
31877dc7771cSEwan Crawford     {
31887dc7771cSEwan Crawford         m_breakAllKernels = true;
31897dc7771cSEwan Crawford 
31907dc7771cSEwan Crawford         for (const auto &module : m_rsmodules)
31917dc7771cSEwan Crawford             BreakOnModuleKernels(module);
31927dc7771cSEwan Crawford 
31937dc7771cSEwan Crawford         if (log)
3194b3f7f69dSAidan Dodds             log->Printf("%s(True) - breakpoints set on all currently loaded kernels.", __FUNCTION__);
31957dc7771cSEwan Crawford     }
31967dc7771cSEwan Crawford     else if (!do_break && m_breakAllKernels) // Breakpoints won't be set on any new kernels.
31977dc7771cSEwan Crawford     {
31987dc7771cSEwan Crawford         m_breakAllKernels = false;
31997dc7771cSEwan Crawford 
32007dc7771cSEwan Crawford         if (log)
3201b3f7f69dSAidan Dodds             log->Printf("%s(False) - breakpoints no longer automatically set.", __FUNCTION__);
32027dc7771cSEwan Crawford     }
32037dc7771cSEwan Crawford }
32047dc7771cSEwan Crawford 
32057dc7771cSEwan Crawford // Given the name of a kernel this function creates a breakpoint using our
32067dc7771cSEwan Crawford // own breakpoint resolver, and returns the Breakpoint shared pointer.
32077dc7771cSEwan Crawford BreakpointSP
32087dc7771cSEwan Crawford RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name)
32097dc7771cSEwan Crawford {
321054782db7SEwan Crawford     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
32117dc7771cSEwan Crawford 
32127dc7771cSEwan Crawford     if (!m_filtersp)
32137dc7771cSEwan Crawford     {
32147dc7771cSEwan Crawford         if (log)
3215b3f7f69dSAidan Dodds             log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
32167dc7771cSEwan Crawford         return nullptr;
32177dc7771cSEwan Crawford     }
32187dc7771cSEwan Crawford 
32197dc7771cSEwan Crawford     BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
32207dc7771cSEwan Crawford     BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(m_filtersp, resolver_sp, false, false, false);
32217dc7771cSEwan Crawford 
322254782db7SEwan Crawford     // Give RS breakpoints a specific name, so the user can manipulate them as a group.
322354782db7SEwan Crawford     Error err;
322454782db7SEwan Crawford     if (!bp->AddName("RenderScriptKernel", err) && log)
3225b3f7f69dSAidan Dodds         log->Printf("%s - error setting break name, '%s'.", __FUNCTION__, err.AsCString());
322654782db7SEwan Crawford 
32277dc7771cSEwan Crawford     return bp;
32287dc7771cSEwan Crawford }
32297dc7771cSEwan Crawford 
3230018f5a7eSEwan Crawford // Given an expression for a variable this function tries to calculate the variable's value.
3231018f5a7eSEwan Crawford // If this is possible it returns true and sets the uint64_t parameter to the variables unsigned value.
3232018f5a7eSEwan Crawford // Otherwise function returns false.
3233018f5a7eSEwan Crawford bool
3234018f5a7eSEwan Crawford RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp, const char *var_name, uint64_t &val)
3235018f5a7eSEwan Crawford {
3236018f5a7eSEwan Crawford     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3237018f5a7eSEwan Crawford     Error error;
3238018f5a7eSEwan Crawford     VariableSP var_sp;
3239018f5a7eSEwan Crawford 
3240018f5a7eSEwan Crawford     // Find variable in stack frame
3241b3f7f69dSAidan Dodds     ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3242b3f7f69dSAidan Dodds         var_name, eNoDynamicValues,
3243b3f7f69dSAidan Dodds         StackFrame::eExpressionPathOptionCheckPtrVsMember | StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3244b3f7f69dSAidan Dodds         var_sp, error));
3245018f5a7eSEwan Crawford     if (!error.Success())
3246018f5a7eSEwan Crawford     {
3247018f5a7eSEwan Crawford         if (log)
3248b3f7f69dSAidan Dodds             log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__, var_name);
3249018f5a7eSEwan Crawford         return false;
3250018f5a7eSEwan Crawford     }
3251018f5a7eSEwan Crawford 
3252b3f7f69dSAidan Dodds     // Find the uint32_t value for the variable
3253018f5a7eSEwan Crawford     bool success = false;
3254018f5a7eSEwan Crawford     val = value_sp->GetValueAsUnsigned(0, &success);
3255018f5a7eSEwan Crawford     if (!success)
3256018f5a7eSEwan Crawford     {
3257018f5a7eSEwan Crawford         if (log)
3258b3f7f69dSAidan Dodds             log->Printf("%s - error, couldn't parse '%s' as an uint32_t.", __FUNCTION__, var_name);
3259018f5a7eSEwan Crawford         return false;
3260018f5a7eSEwan Crawford     }
3261018f5a7eSEwan Crawford 
3262018f5a7eSEwan Crawford     return true;
3263018f5a7eSEwan Crawford }
3264018f5a7eSEwan Crawford 
32654f8817c2SEwan Crawford // Function attempts to find the current coordinate of a kernel invocation by investigating the
32664f8817c2SEwan Crawford // values of frame variables in the .expand function. These coordinates are returned via the coord
32674f8817c2SEwan Crawford // array reference parameter. Returns true if the coordinates could be found, and false otherwise.
32684f8817c2SEwan Crawford bool
32694f8817c2SEwan Crawford RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord, Thread *thread_ptr)
32704f8817c2SEwan Crawford {
32711e05c3bcSGreg Clayton     static const std::string s_runtimeExpandSuffix(".expand");
32721e05c3bcSGreg Clayton     static const std::array<const char *, 3> s_runtimeCoordVars{{"rsIndex", "p->current.y", "p->current.z"}};
32731e05c3bcSGreg Clayton 
32744f8817c2SEwan Crawford     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
32754f8817c2SEwan Crawford 
32764f8817c2SEwan Crawford     if (!thread_ptr)
32774f8817c2SEwan Crawford     {
32784f8817c2SEwan Crawford         if (log)
32794f8817c2SEwan Crawford             log->Printf("%s - Error, No thread pointer", __FUNCTION__);
32804f8817c2SEwan Crawford 
32814f8817c2SEwan Crawford         return false;
32824f8817c2SEwan Crawford     }
32834f8817c2SEwan Crawford 
32844f8817c2SEwan Crawford     // Walk the call stack looking for a function whose name has the suffix '.expand'
32854f8817c2SEwan Crawford     // and contains the variables we're looking for.
32864f8817c2SEwan Crawford     for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i)
32874f8817c2SEwan Crawford     {
32884f8817c2SEwan Crawford         if (!thread_ptr->SetSelectedFrameByIndex(i))
32894f8817c2SEwan Crawford             continue;
32904f8817c2SEwan Crawford 
32914f8817c2SEwan Crawford         StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
32924f8817c2SEwan Crawford         if (!frame_sp)
32934f8817c2SEwan Crawford             continue;
32944f8817c2SEwan Crawford 
32954f8817c2SEwan Crawford         // Find the function name
32964f8817c2SEwan Crawford         const SymbolContext sym_ctx = frame_sp->GetSymbolContext(false);
32974f8817c2SEwan Crawford         const char *func_name_cstr = sym_ctx.GetFunctionName().AsCString();
32984f8817c2SEwan Crawford         if (!func_name_cstr)
32994f8817c2SEwan Crawford             continue;
33004f8817c2SEwan Crawford 
33014f8817c2SEwan Crawford         if (log)
33024f8817c2SEwan Crawford             log->Printf("%s - Inspecting function '%s'", __FUNCTION__, func_name_cstr);
33034f8817c2SEwan Crawford 
33044f8817c2SEwan Crawford         // Check if function name has .expand suffix
33054f8817c2SEwan Crawford         std::string func_name(func_name_cstr);
33061e05c3bcSGreg Clayton         const int length_difference = func_name.length() - s_runtimeExpandSuffix.length();
33074f8817c2SEwan Crawford         if (length_difference <= 0)
33084f8817c2SEwan Crawford             continue;
33094f8817c2SEwan Crawford 
33104f8817c2SEwan Crawford         const int32_t has_expand_suffix = func_name.compare(length_difference,
33111e05c3bcSGreg Clayton                                                             s_runtimeExpandSuffix.length(),
33121e05c3bcSGreg Clayton                                                             s_runtimeExpandSuffix);
33134f8817c2SEwan Crawford 
33144f8817c2SEwan Crawford         if (has_expand_suffix != 0)
33154f8817c2SEwan Crawford             continue;
33164f8817c2SEwan Crawford 
33174f8817c2SEwan Crawford         if (log)
33184f8817c2SEwan Crawford             log->Printf("%s - Found .expand function '%s'", __FUNCTION__, func_name_cstr);
33194f8817c2SEwan Crawford 
33204f8817c2SEwan Crawford         // Get values for variables in .expand frame that tell us the current kernel invocation
33214f8817c2SEwan Crawford         bool found_coord_variables = true;
33221e05c3bcSGreg Clayton         assert(s_runtimeCoordVars.size() == coord.size());
33234f8817c2SEwan Crawford 
33244f8817c2SEwan Crawford         for (uint32_t i = 0; i < coord.size(); ++i)
33254f8817c2SEwan Crawford         {
33264f8817c2SEwan Crawford             uint64_t value = 0;
33271e05c3bcSGreg Clayton             if (!GetFrameVarAsUnsigned(frame_sp, s_runtimeCoordVars[i], value))
33284f8817c2SEwan Crawford             {
33294f8817c2SEwan Crawford                 found_coord_variables = false;
33304f8817c2SEwan Crawford                 break;
33314f8817c2SEwan Crawford             }
33324f8817c2SEwan Crawford             coord[i] = value;
33334f8817c2SEwan Crawford         }
33344f8817c2SEwan Crawford 
33354f8817c2SEwan Crawford         if (found_coord_variables)
33364f8817c2SEwan Crawford             return true;
33374f8817c2SEwan Crawford     }
33384f8817c2SEwan Crawford     return false;
33394f8817c2SEwan Crawford }
33404f8817c2SEwan Crawford 
3341018f5a7eSEwan Crawford // Callback when a kernel breakpoint hits and we're looking for a specific coordinate.
3342018f5a7eSEwan Crawford // Baton parameter contains a pointer to the target coordinate we want to break on.
3343018f5a7eSEwan Crawford // Function then checks the .expand frame for the current coordinate and breaks to user if it matches.
3344018f5a7eSEwan Crawford // Parameter 'break_id' is the id of the Breakpoint which made the callback.
3345018f5a7eSEwan Crawford // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
3346018f5a7eSEwan Crawford // a single logical breakpoint can have multiple addresses.
3347018f5a7eSEwan Crawford bool
3348b3f7f69dSAidan Dodds RenderScriptRuntime::KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx, user_id_t break_id,
3349b3f7f69dSAidan Dodds                                          user_id_t break_loc_id)
3350018f5a7eSEwan Crawford {
3351018f5a7eSEwan Crawford     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3352018f5a7eSEwan Crawford 
3353018f5a7eSEwan Crawford     assert(baton && "Error: null baton in conditional kernel breakpoint callback");
3354018f5a7eSEwan Crawford 
3355018f5a7eSEwan Crawford     // Coordinate we want to stop on
33564f8817c2SEwan Crawford     const uint32_t *target_coord = static_cast<const uint32_t *>(baton);
3357018f5a7eSEwan Crawford 
3358018f5a7eSEwan Crawford     if (log)
33594f8817c2SEwan Crawford         log->Printf("%s - Break ID %" PRIu64 ", (%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")", __FUNCTION__, break_id,
33604f8817c2SEwan Crawford                     target_coord[0], target_coord[1], target_coord[2]);
3361018f5a7eSEwan Crawford 
33624f8817c2SEwan Crawford     // Select current thread
3363018f5a7eSEwan Crawford     ExecutionContext context(ctx->exe_ctx_ref);
33644f8817c2SEwan Crawford     Thread *thread_ptr = context.GetThreadPtr();
33654f8817c2SEwan Crawford     assert(thread_ptr && "Null thread pointer");
33664f8817c2SEwan Crawford 
33674f8817c2SEwan Crawford     // Find current kernel invocation from .expand frame variables
33684f8817c2SEwan Crawford     RSCoordinate current_coord{}; // Zero initialise array
33694f8817c2SEwan Crawford     if (!GetKernelCoordinate(current_coord, thread_ptr))
3370018f5a7eSEwan Crawford     {
3371018f5a7eSEwan Crawford         if (log)
33724f8817c2SEwan Crawford             log->Printf("%s - Error, couldn't select .expand stack frame", __FUNCTION__);
3373018f5a7eSEwan Crawford         return false;
3374018f5a7eSEwan Crawford     }
3375018f5a7eSEwan Crawford 
3376018f5a7eSEwan Crawford     if (log)
33774f8817c2SEwan Crawford         log->Printf("%s - (%" PRIu32 ",%" PRIu32 ",%" PRIu32 ")", __FUNCTION__, current_coord[0], current_coord[1],
33784f8817c2SEwan Crawford                     current_coord[2]);
3379018f5a7eSEwan Crawford 
3380018f5a7eSEwan Crawford     // Check if the current kernel invocation coordinate matches our target coordinate
3381b3f7f69dSAidan Dodds     if (current_coord[0] == target_coord[0] &&
3382b3f7f69dSAidan Dodds         current_coord[1] == target_coord[1] &&
33834f8817c2SEwan Crawford         current_coord[2] == target_coord[2])
3384018f5a7eSEwan Crawford     {
3385018f5a7eSEwan Crawford         if (log)
33864f8817c2SEwan Crawford             log->Printf("%s, BREAKING (%" PRIu32 ",%" PRIu32 ",%" PRIu32 ")", __FUNCTION__, current_coord[0],
33874f8817c2SEwan Crawford                         current_coord[1], current_coord[2]);
3388018f5a7eSEwan Crawford 
3389018f5a7eSEwan Crawford         BreakpointSP breakpoint_sp = context.GetTargetPtr()->GetBreakpointByID(break_id);
3390018f5a7eSEwan Crawford         assert(breakpoint_sp != nullptr && "Error: Couldn't find breakpoint matching break id for callback");
3391018f5a7eSEwan Crawford         breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint should only be hit once.
3392018f5a7eSEwan Crawford         return true;
3393018f5a7eSEwan Crawford     }
3394018f5a7eSEwan Crawford 
3395018f5a7eSEwan Crawford     // No match on coordinate
3396018f5a7eSEwan Crawford     return false;
3397018f5a7eSEwan Crawford }
3398018f5a7eSEwan Crawford 
3399018f5a7eSEwan Crawford // Tries to set a breakpoint on the start of a kernel, resolved using the kernel name.
3400018f5a7eSEwan Crawford // Argument 'coords', represents a three dimensional coordinate which can be used to specify
3401018f5a7eSEwan Crawford // a single kernel instance to break on. If this is set then we add a callback to the breakpoint.
34024640cde1SColin Riley void
3403018f5a7eSEwan Crawford RenderScriptRuntime::PlaceBreakpointOnKernel(Stream &strm, const char *name, const std::array<int, 3> coords,
3404018f5a7eSEwan Crawford                                              Error &error, TargetSP target)
34054640cde1SColin Riley {
34064640cde1SColin Riley     if (!name)
34074640cde1SColin Riley     {
34084640cde1SColin Riley         error.SetErrorString("invalid kernel name");
34094640cde1SColin Riley         return;
34104640cde1SColin Riley     }
34114640cde1SColin Riley 
34127dc7771cSEwan Crawford     InitSearchFilter(target);
341398156583SEwan Crawford 
34144640cde1SColin Riley     ConstString kernel_name(name);
34157dc7771cSEwan Crawford     BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
3416018f5a7eSEwan Crawford 
3417018f5a7eSEwan Crawford     // We have a conditional breakpoint on a specific coordinate
3418018f5a7eSEwan Crawford     if (coords[0] != -1)
3419018f5a7eSEwan Crawford     {
3420b3f7f69dSAidan Dodds         strm.Printf("Conditional kernel breakpoint on coordinate %" PRId32 ", %" PRId32 ", %" PRId32,
3421b3f7f69dSAidan Dodds                     coords[0], coords[1], coords[2]);
3422018f5a7eSEwan Crawford         strm.EOL();
3423018f5a7eSEwan Crawford 
3424018f5a7eSEwan Crawford         // Allocate memory for the baton, and copy over coordinate
34254f8817c2SEwan Crawford         uint32_t *baton = new uint32_t[coords.size()];
3426018f5a7eSEwan Crawford         baton[0] = coords[0]; baton[1] = coords[1]; baton[2] = coords[2];
3427018f5a7eSEwan Crawford 
3428018f5a7eSEwan Crawford         // Create a callback that will be invoked every time the breakpoint is hit.
3429018f5a7eSEwan Crawford         // The baton object passed to the handler is the target coordinate we want to break on.
3430018f5a7eSEwan Crawford         bp->SetCallback(KernelBreakpointHit, baton, true);
3431018f5a7eSEwan Crawford 
3432018f5a7eSEwan Crawford         // Store a shared pointer to the baton, so the memory will eventually be cleaned up after destruction
34334f8817c2SEwan Crawford         m_conditional_breaks[bp->GetID()] = std::shared_ptr<uint32_t>(baton);
3434018f5a7eSEwan Crawford     }
3435018f5a7eSEwan Crawford 
343698156583SEwan Crawford     if (bp)
343798156583SEwan Crawford         bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
34384640cde1SColin Riley }
34394640cde1SColin Riley 
34404640cde1SColin Riley void
34415ec532a9SColin Riley RenderScriptRuntime::DumpModules(Stream &strm) const
34425ec532a9SColin Riley {
34435ec532a9SColin Riley     strm.Printf("RenderScript Modules:");
34445ec532a9SColin Riley     strm.EOL();
34455ec532a9SColin Riley     strm.IndentMore();
34465ec532a9SColin Riley     for (const auto &module : m_rsmodules)
34475ec532a9SColin Riley     {
34484640cde1SColin Riley         module->Dump(strm);
34495ec532a9SColin Riley     }
34505ec532a9SColin Riley     strm.IndentLess();
34515ec532a9SColin Riley }
34525ec532a9SColin Riley 
345378f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails *
345478f339d1SEwan Crawford RenderScriptRuntime::LookUpScript(addr_t address, bool create)
345578f339d1SEwan Crawford {
345678f339d1SEwan Crawford     for (const auto &s : m_scripts)
345778f339d1SEwan Crawford     {
345878f339d1SEwan Crawford         if (s->script.isValid())
345978f339d1SEwan Crawford             if (*s->script == address)
346078f339d1SEwan Crawford                 return s.get();
346178f339d1SEwan Crawford     }
346278f339d1SEwan Crawford     if (create)
346378f339d1SEwan Crawford     {
346478f339d1SEwan Crawford         std::unique_ptr<ScriptDetails> s(new ScriptDetails);
346578f339d1SEwan Crawford         s->script = address;
346678f339d1SEwan Crawford         m_scripts.push_back(std::move(s));
3467d10ca9deSEwan Crawford         return m_scripts.back().get();
346878f339d1SEwan Crawford     }
346978f339d1SEwan Crawford     return nullptr;
347078f339d1SEwan Crawford }
347178f339d1SEwan Crawford 
347278f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails *
34735d057637SLuke Drummond RenderScriptRuntime::LookUpAllocation(addr_t address)
347478f339d1SEwan Crawford {
347578f339d1SEwan Crawford     for (const auto &a : m_allocations)
347678f339d1SEwan Crawford     {
347778f339d1SEwan Crawford         if (a->address.isValid())
347878f339d1SEwan Crawford             if (*a->address == address)
347978f339d1SEwan Crawford                 return a.get();
348078f339d1SEwan Crawford     }
34815d057637SLuke Drummond     return nullptr;
34825d057637SLuke Drummond }
34835d057637SLuke Drummond 
34845d057637SLuke Drummond RenderScriptRuntime::AllocationDetails *
34855d057637SLuke Drummond RenderScriptRuntime::CreateAllocation(addr_t address)
348678f339d1SEwan Crawford {
34875d057637SLuke Drummond     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
34885d057637SLuke Drummond 
34895d057637SLuke Drummond     // Remove any previous allocation which contains the same address
34905d057637SLuke Drummond     auto it = m_allocations.begin();
34915d057637SLuke Drummond     while (it != m_allocations.end())
34925d057637SLuke Drummond     {
34935d057637SLuke Drummond         if (*((*it)->address) == address)
34945d057637SLuke Drummond         {
34955d057637SLuke Drummond             if (log)
34965d057637SLuke Drummond                 log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64, __FUNCTION__, (*it)->id, address);
34975d057637SLuke Drummond 
34985d057637SLuke Drummond             it = m_allocations.erase(it);
34995d057637SLuke Drummond         }
35005d057637SLuke Drummond         else
35015d057637SLuke Drummond         {
35025d057637SLuke Drummond             it++;
35035d057637SLuke Drummond         }
35045d057637SLuke Drummond     }
35055d057637SLuke Drummond 
350678f339d1SEwan Crawford     std::unique_ptr<AllocationDetails> a(new AllocationDetails);
350778f339d1SEwan Crawford     a->address = address;
350878f339d1SEwan Crawford     m_allocations.push_back(std::move(a));
3509d10ca9deSEwan Crawford     return m_allocations.back().get();
351078f339d1SEwan Crawford }
351178f339d1SEwan Crawford 
35125ec532a9SColin Riley void
35135ec532a9SColin Riley RSModuleDescriptor::Dump(Stream &strm) const
35145ec532a9SColin Riley {
35155ec532a9SColin Riley     strm.Indent();
35165ec532a9SColin Riley     m_module->GetFileSpec().Dump(&strm);
35174640cde1SColin Riley     if (m_module->GetNumCompileUnits())
35184640cde1SColin Riley     {
35194640cde1SColin Riley         strm.Indent("Debug info loaded.");
35204640cde1SColin Riley     }
35214640cde1SColin Riley     else
35224640cde1SColin Riley     {
35234640cde1SColin Riley         strm.Indent("Debug info does not exist.");
35244640cde1SColin Riley     }
35255ec532a9SColin Riley     strm.EOL();
35265ec532a9SColin Riley     strm.IndentMore();
35275ec532a9SColin Riley     strm.Indent();
3528189598edSColin Riley     strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
35295ec532a9SColin Riley     strm.EOL();
35305ec532a9SColin Riley     strm.IndentMore();
35315ec532a9SColin Riley     for (const auto &global : m_globals)
35325ec532a9SColin Riley     {
35335ec532a9SColin Riley         global.Dump(strm);
35345ec532a9SColin Riley     }
35355ec532a9SColin Riley     strm.IndentLess();
35365ec532a9SColin Riley     strm.Indent();
3537189598edSColin Riley     strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
35385ec532a9SColin Riley     strm.EOL();
35395ec532a9SColin Riley     strm.IndentMore();
35405ec532a9SColin Riley     for (const auto &kernel : m_kernels)
35415ec532a9SColin Riley     {
35425ec532a9SColin Riley         kernel.Dump(strm);
35435ec532a9SColin Riley     }
35444640cde1SColin Riley     strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
35454640cde1SColin Riley     strm.EOL();
35464640cde1SColin Riley     strm.IndentMore();
35474640cde1SColin Riley     for (const auto &key_val : m_pragmas)
35484640cde1SColin Riley     {
35494640cde1SColin Riley         strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
35504640cde1SColin Riley         strm.EOL();
35514640cde1SColin Riley     }
35525ec532a9SColin Riley     strm.IndentLess(4);
35535ec532a9SColin Riley }
35545ec532a9SColin Riley 
35555ec532a9SColin Riley void
35565ec532a9SColin Riley RSGlobalDescriptor::Dump(Stream &strm) const
35575ec532a9SColin Riley {
35585ec532a9SColin Riley     strm.Indent(m_name.AsCString());
35594640cde1SColin Riley     VariableList var_list;
35604640cde1SColin Riley     m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
35614640cde1SColin Riley     if (var_list.GetSize() == 1)
35624640cde1SColin Riley     {
35634640cde1SColin Riley         auto var = var_list.GetVariableAtIndex(0);
35644640cde1SColin Riley         auto type = var->GetType();
35654640cde1SColin Riley         if (type)
35664640cde1SColin Riley         {
35674640cde1SColin Riley             strm.Printf(" - ");
35684640cde1SColin Riley             type->DumpTypeName(&strm);
35694640cde1SColin Riley         }
35704640cde1SColin Riley         else
35714640cde1SColin Riley         {
35724640cde1SColin Riley             strm.Printf(" - Unknown Type");
35734640cde1SColin Riley         }
35744640cde1SColin Riley     }
35754640cde1SColin Riley     else
35764640cde1SColin Riley     {
35774640cde1SColin Riley         strm.Printf(" - variable identified, but not found in binary");
35784640cde1SColin Riley         const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(m_name, eSymbolTypeData);
35794640cde1SColin Riley         if (s)
35804640cde1SColin Riley         {
35814640cde1SColin Riley             strm.Printf(" (symbol exists) ");
35824640cde1SColin Riley         }
35834640cde1SColin Riley     }
35844640cde1SColin Riley 
35855ec532a9SColin Riley     strm.EOL();
35865ec532a9SColin Riley }
35875ec532a9SColin Riley 
35885ec532a9SColin Riley void
35895ec532a9SColin Riley RSKernelDescriptor::Dump(Stream &strm) const
35905ec532a9SColin Riley {
35915ec532a9SColin Riley     strm.Indent(m_name.AsCString());
35925ec532a9SColin Riley     strm.EOL();
35935ec532a9SColin Riley }
35945ec532a9SColin Riley 
35955ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed
35965ec532a9SColin Riley {
35975ec532a9SColin Riley public:
35985ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
35995ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module dump",
36005ec532a9SColin Riley                               "Dumps renderscript specific information for all modules.", "renderscript module dump",
3601e87764f2SEnrico Granata                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
36025ec532a9SColin Riley     {
36035ec532a9SColin Riley     }
36045ec532a9SColin Riley 
3605222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
36065ec532a9SColin Riley 
36075ec532a9SColin Riley     bool
3608222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
36095ec532a9SColin Riley     {
36105ec532a9SColin Riley         RenderScriptRuntime *runtime =
36115ec532a9SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
36125ec532a9SColin Riley         runtime->DumpModules(result.GetOutputStream());
36135ec532a9SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
36145ec532a9SColin Riley         return true;
36155ec532a9SColin Riley     }
36165ec532a9SColin Riley };
36175ec532a9SColin Riley 
36185ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword
36195ec532a9SColin Riley {
36205ec532a9SColin Riley public:
36215ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
36227428a18cSKate Stone         : CommandObjectMultiword(interpreter, "renderscript module", "Commands that deal with RenderScript modules.",
3623b3f7f69dSAidan Dodds                                  nullptr)
36245ec532a9SColin Riley     {
36255ec532a9SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(interpreter)));
36265ec532a9SColin Riley     }
36275ec532a9SColin Riley 
3628222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModule() override = default;
36295ec532a9SColin Riley };
36305ec532a9SColin Riley 
36314640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed
36324640cde1SColin Riley {
36334640cde1SColin Riley public:
36344640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
36354640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript kernel list",
3636b3f7f69dSAidan Dodds                               "Lists renderscript kernel names and associated script resources.",
3637b3f7f69dSAidan Dodds                               "renderscript kernel list", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
36384640cde1SColin Riley     {
36394640cde1SColin Riley     }
36404640cde1SColin Riley 
3641222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelList() override = default;
36424640cde1SColin Riley 
36434640cde1SColin Riley     bool
3644222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
36454640cde1SColin Riley     {
36464640cde1SColin Riley         RenderScriptRuntime *runtime =
36474640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
36484640cde1SColin Riley         runtime->DumpKernels(result.GetOutputStream());
36494640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
36504640cde1SColin Riley         return true;
36514640cde1SColin Riley     }
36524640cde1SColin Riley };
36534640cde1SColin Riley 
36547dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointSet : public CommandObjectParsed
36554640cde1SColin Riley {
36564640cde1SColin Riley public:
36577dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointSet(CommandInterpreter &interpreter)
36587dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint set",
3659b3f7f69dSAidan Dodds                               "Sets a breakpoint on a renderscript kernel.",
3660b3f7f69dSAidan Dodds                               "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
3661b3f7f69dSAidan Dodds                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
3662*e1cfbc79STodd Fiala           m_options()
36634640cde1SColin Riley     {
36644640cde1SColin Riley     }
36654640cde1SColin Riley 
3666222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
3667222b937cSEugene Zelenko 
3668222b937cSEugene Zelenko     Options *
3669222b937cSEugene Zelenko     GetOptions() override
3670018f5a7eSEwan Crawford     {
3671018f5a7eSEwan Crawford         return &m_options;
3672018f5a7eSEwan Crawford     }
3673018f5a7eSEwan Crawford 
3674018f5a7eSEwan Crawford     class CommandOptions : public Options
3675018f5a7eSEwan Crawford     {
3676018f5a7eSEwan Crawford     public:
3677*e1cfbc79STodd Fiala         CommandOptions() : Options() {}
3678018f5a7eSEwan Crawford 
3679222b937cSEugene Zelenko         ~CommandOptions() override = default;
3680018f5a7eSEwan Crawford 
3681222b937cSEugene Zelenko         Error
3682*e1cfbc79STodd Fiala         SetOptionValue(uint32_t option_idx, const char *option_arg,
3683*e1cfbc79STodd Fiala                        ExecutionContext *execution_context) override
3684018f5a7eSEwan Crawford         {
3685018f5a7eSEwan Crawford             Error error;
3686018f5a7eSEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
3687018f5a7eSEwan Crawford 
3688018f5a7eSEwan Crawford             switch (short_option)
3689018f5a7eSEwan Crawford             {
3690018f5a7eSEwan Crawford                 case 'c':
3691018f5a7eSEwan Crawford                     if (!ParseCoordinate(option_arg))
3692b3f7f69dSAidan Dodds                         error.SetErrorStringWithFormat("Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
3693b3f7f69dSAidan Dodds                                                        option_arg);
3694018f5a7eSEwan Crawford                     break;
3695018f5a7eSEwan Crawford                 default:
3696018f5a7eSEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3697018f5a7eSEwan Crawford                     break;
3698018f5a7eSEwan Crawford             }
3699018f5a7eSEwan Crawford             return error;
3700018f5a7eSEwan Crawford         }
3701018f5a7eSEwan Crawford 
3702018f5a7eSEwan Crawford         // -c takes an argument of the form 'num[,num][,num]'.
3703018f5a7eSEwan Crawford         // Where 'id_cstr' is this argument with the whitespace trimmed.
3704018f5a7eSEwan Crawford         // Missing coordinates are defaulted to zero.
3705018f5a7eSEwan Crawford         bool
3706018f5a7eSEwan Crawford         ParseCoordinate(const char *id_cstr)
3707018f5a7eSEwan Crawford         {
3708018f5a7eSEwan Crawford             RegularExpression regex;
3709018f5a7eSEwan Crawford             RegularExpression::Match regex_match(3);
3710018f5a7eSEwan Crawford 
3711018f5a7eSEwan Crawford             bool matched = false;
3712018f5a7eSEwan Crawford             if (regex.Compile("^([0-9]+),([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3713018f5a7eSEwan Crawford                 matched = true;
3714018f5a7eSEwan Crawford             else if (regex.Compile("^([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3715018f5a7eSEwan Crawford                 matched = true;
3716018f5a7eSEwan Crawford             else if (regex.Compile("^([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3717018f5a7eSEwan Crawford                 matched = true;
3718018f5a7eSEwan Crawford             for (uint32_t i = 0; i < 3; i++)
3719018f5a7eSEwan Crawford             {
3720018f5a7eSEwan Crawford                 std::string group;
3721018f5a7eSEwan Crawford                 if (regex_match.GetMatchAtIndex(id_cstr, i + 1, group))
3722b3f7f69dSAidan Dodds                     m_coord[i] = (uint32_t)strtoul(group.c_str(), nullptr, 0);
3723018f5a7eSEwan Crawford                 else
3724018f5a7eSEwan Crawford                     m_coord[i] = 0;
3725018f5a7eSEwan Crawford             }
3726018f5a7eSEwan Crawford             return matched;
3727018f5a7eSEwan Crawford         }
3728018f5a7eSEwan Crawford 
3729018f5a7eSEwan Crawford         void
3730*e1cfbc79STodd Fiala         OptionParsingStarting(ExecutionContext *execution_context) override
3731018f5a7eSEwan Crawford         {
3732018f5a7eSEwan Crawford             // -1 means the -c option hasn't been set
3733018f5a7eSEwan Crawford             m_coord[0] = -1;
3734018f5a7eSEwan Crawford             m_coord[1] = -1;
3735018f5a7eSEwan Crawford             m_coord[2] = -1;
3736018f5a7eSEwan Crawford         }
3737018f5a7eSEwan Crawford 
3738018f5a7eSEwan Crawford         const OptionDefinition *
3739222b937cSEugene Zelenko         GetDefinitions() override
3740018f5a7eSEwan Crawford         {
3741018f5a7eSEwan Crawford             return g_option_table;
3742018f5a7eSEwan Crawford         }
3743018f5a7eSEwan Crawford 
3744018f5a7eSEwan Crawford         static OptionDefinition g_option_table[];
3745018f5a7eSEwan Crawford         std::array<int, 3> m_coord;
3746018f5a7eSEwan Crawford     };
3747018f5a7eSEwan Crawford 
37484640cde1SColin Riley     bool
3749222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
37504640cde1SColin Riley     {
37514640cde1SColin Riley         const size_t argc = command.GetArgumentCount();
3752018f5a7eSEwan Crawford         if (argc < 1)
37534640cde1SColin Riley         {
3754b3f7f69dSAidan Dodds             result.AppendErrorWithFormat("'%s' takes 1 argument of kernel name, and an optional coordinate.",
3755b3f7f69dSAidan Dodds                                          m_cmd_name.c_str());
3756018f5a7eSEwan Crawford             result.SetStatus(eReturnStatusFailed);
3757018f5a7eSEwan Crawford             return false;
3758018f5a7eSEwan Crawford         }
3759018f5a7eSEwan Crawford 
37604640cde1SColin Riley         RenderScriptRuntime *runtime =
37614640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
37624640cde1SColin Riley 
37634640cde1SColin Riley         Error error;
3764018f5a7eSEwan Crawford         runtime->PlaceBreakpointOnKernel(result.GetOutputStream(), command.GetArgumentAtIndex(0), m_options.m_coord,
376598156583SEwan Crawford                                          error, m_exe_ctx.GetTargetSP());
37664640cde1SColin Riley 
37674640cde1SColin Riley         if (error.Success())
37684640cde1SColin Riley         {
37694640cde1SColin Riley             result.AppendMessage("Breakpoint(s) created");
37704640cde1SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
37714640cde1SColin Riley             return true;
37724640cde1SColin Riley         }
37734640cde1SColin Riley         result.SetStatus(eReturnStatusFailed);
37744640cde1SColin Riley         result.AppendErrorWithFormat("Error: %s", error.AsCString());
37754640cde1SColin Riley         return false;
37764640cde1SColin Riley     }
37774640cde1SColin Riley 
3778018f5a7eSEwan Crawford private:
3779018f5a7eSEwan Crawford     CommandOptions m_options;
37804640cde1SColin Riley };
37814640cde1SColin Riley 
3782b3f7f69dSAidan Dodds OptionDefinition CommandObjectRenderScriptRuntimeKernelBreakpointSet::CommandOptions::g_option_table[] = {
3783b3f7f69dSAidan Dodds     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeValue,
3784018f5a7eSEwan Crawford      "Set a breakpoint on a single invocation of the kernel with specified coordinate.\n"
3785018f5a7eSEwan Crawford      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive integers representing kernel dimensions. "
3786018f5a7eSEwan Crawford      "Any unset dimensions will be defaulted to zero."},
3787b3f7f69dSAidan Dodds     {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}};
3788018f5a7eSEwan Crawford 
37897dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointAll : public CommandObjectParsed
37907dc7771cSEwan Crawford {
37917dc7771cSEwan Crawford public:
37927dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointAll(CommandInterpreter &interpreter)
3793b3f7f69dSAidan Dodds         : CommandObjectParsed(
3794b3f7f69dSAidan Dodds               interpreter, "renderscript kernel breakpoint all",
37957dc7771cSEwan Crawford               "Automatically sets a breakpoint on all renderscript kernels that are or will be loaded.\n"
37967dc7771cSEwan Crawford               "Disabling option means breakpoints will no longer be set on any kernels loaded in the future, "
37977dc7771cSEwan Crawford               "but does not remove currently set breakpoints.",
37987dc7771cSEwan Crawford               "renderscript kernel breakpoint all <enable/disable>",
37997dc7771cSEwan Crawford               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
38007dc7771cSEwan Crawford     {
38017dc7771cSEwan Crawford     }
38027dc7771cSEwan Crawford 
3803222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
38047dc7771cSEwan Crawford 
38057dc7771cSEwan Crawford     bool
3806222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
38077dc7771cSEwan Crawford     {
38087dc7771cSEwan Crawford         const size_t argc = command.GetArgumentCount();
38097dc7771cSEwan Crawford         if (argc != 1)
38107dc7771cSEwan Crawford         {
38117dc7771cSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
38127dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
38137dc7771cSEwan Crawford             return false;
38147dc7771cSEwan Crawford         }
38157dc7771cSEwan Crawford 
3816b3f7f69dSAidan Dodds         RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
3817b3f7f69dSAidan Dodds             m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
38187dc7771cSEwan Crawford 
38197dc7771cSEwan Crawford         bool do_break = false;
38207dc7771cSEwan Crawford         const char *argument = command.GetArgumentAtIndex(0);
38217dc7771cSEwan Crawford         if (strcmp(argument, "enable") == 0)
38227dc7771cSEwan Crawford         {
38237dc7771cSEwan Crawford             do_break = true;
38247dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will be set on all kernels.");
38257dc7771cSEwan Crawford         }
38267dc7771cSEwan Crawford         else if (strcmp(argument, "disable") == 0)
38277dc7771cSEwan Crawford         {
38287dc7771cSEwan Crawford             do_break = false;
38297dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will not be set on any new kernels.");
38307dc7771cSEwan Crawford         }
38317dc7771cSEwan Crawford         else
38327dc7771cSEwan Crawford         {
38337dc7771cSEwan Crawford             result.AppendErrorWithFormat("Argument must be either 'enable' or 'disable'");
38347dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
38357dc7771cSEwan Crawford             return false;
38367dc7771cSEwan Crawford         }
38377dc7771cSEwan Crawford 
38387dc7771cSEwan Crawford         runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
38397dc7771cSEwan Crawford 
38407dc7771cSEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
38417dc7771cSEwan Crawford         return true;
38427dc7771cSEwan Crawford     }
38437dc7771cSEwan Crawford };
38447dc7771cSEwan Crawford 
38454f8817c2SEwan Crawford class CommandObjectRenderScriptRuntimeKernelCoordinate : public CommandObjectParsed
38464f8817c2SEwan Crawford {
38474f8817c2SEwan Crawford public:
38484f8817c2SEwan Crawford     CommandObjectRenderScriptRuntimeKernelCoordinate(CommandInterpreter &interpreter)
38494f8817c2SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel coordinate",
38504f8817c2SEwan Crawford                               "Shows the (x,y,z) coordinate of the current kernel invocation.",
38514f8817c2SEwan Crawford                               "renderscript kernel coordinate",
38524f8817c2SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
38534f8817c2SEwan Crawford     {
38544f8817c2SEwan Crawford     }
38554f8817c2SEwan Crawford 
38564f8817c2SEwan Crawford     ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
38574f8817c2SEwan Crawford 
38584f8817c2SEwan Crawford     bool
38594f8817c2SEwan Crawford     DoExecute(Args &command, CommandReturnObject &result) override
38604f8817c2SEwan Crawford     {
38614f8817c2SEwan Crawford         RSCoordinate coord{}; // Zero initialize array
38624f8817c2SEwan Crawford         bool success = RenderScriptRuntime::GetKernelCoordinate(coord, m_exe_ctx.GetThreadPtr());
38634f8817c2SEwan Crawford         Stream &stream = result.GetOutputStream();
38644f8817c2SEwan Crawford 
38654f8817c2SEwan Crawford         if (success)
38664f8817c2SEwan Crawford         {
38674f8817c2SEwan Crawford             stream.Printf("Coordinate: (%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")", coord[0], coord[1], coord[2]);
38684f8817c2SEwan Crawford             stream.EOL();
38694f8817c2SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
38704f8817c2SEwan Crawford         }
38714f8817c2SEwan Crawford         else
38724f8817c2SEwan Crawford         {
38734f8817c2SEwan Crawford             stream.Printf("Error: Coordinate could not be found.");
38744f8817c2SEwan Crawford             stream.EOL();
38754f8817c2SEwan Crawford             result.SetStatus(eReturnStatusFailed);
38764f8817c2SEwan Crawford         }
38774f8817c2SEwan Crawford         return true;
38784f8817c2SEwan Crawford     }
38794f8817c2SEwan Crawford };
38804f8817c2SEwan Crawford 
38817dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpoint : public CommandObjectMultiword
38827dc7771cSEwan Crawford {
38837dc7771cSEwan Crawford public:
38847dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpoint(CommandInterpreter &interpreter)
3885b3f7f69dSAidan Dodds         : CommandObjectMultiword(interpreter, "renderscript kernel",
3886b3f7f69dSAidan Dodds                                  "Commands that generate breakpoints on renderscript kernels.", nullptr)
38877dc7771cSEwan Crawford     {
38887dc7771cSEwan Crawford         LoadSubCommand("set", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(interpreter)));
38897dc7771cSEwan Crawford         LoadSubCommand("all", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(interpreter)));
38907dc7771cSEwan Crawford     }
38917dc7771cSEwan Crawford 
3892222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
38937dc7771cSEwan Crawford };
38947dc7771cSEwan Crawford 
38954640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword
38964640cde1SColin Riley {
38974640cde1SColin Riley public:
38984640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
38997428a18cSKate Stone         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that deal with RenderScript kernels.",
3900b3f7f69dSAidan Dodds                                  nullptr)
39014640cde1SColin Riley     {
39024640cde1SColin Riley         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(interpreter)));
390336175cc0SEwan Crawford         LoadSubCommand("coordinate",
390436175cc0SEwan Crawford                        CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
3905b3f7f69dSAidan Dodds         LoadSubCommand("breakpoint",
3906b3f7f69dSAidan Dodds                        CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
39074640cde1SColin Riley     }
39084640cde1SColin Riley 
3909222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernel() override = default;
39104640cde1SColin Riley };
39114640cde1SColin Riley 
39124640cde1SColin Riley class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed
39134640cde1SColin Riley {
39144640cde1SColin Riley public:
39154640cde1SColin Riley     CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
3916b3f7f69dSAidan Dodds         : CommandObjectParsed(interpreter, "renderscript context dump", "Dumps renderscript context information.",
3917b3f7f69dSAidan Dodds                               "renderscript context dump", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
39184640cde1SColin Riley     {
39194640cde1SColin Riley     }
39204640cde1SColin Riley 
3921222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeContextDump() override = default;
39224640cde1SColin Riley 
39234640cde1SColin Riley     bool
3924222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
39254640cde1SColin Riley     {
39264640cde1SColin Riley         RenderScriptRuntime *runtime =
39274640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
39284640cde1SColin Riley         runtime->DumpContexts(result.GetOutputStream());
39294640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
39304640cde1SColin Riley         return true;
39314640cde1SColin Riley     }
39324640cde1SColin Riley };
39334640cde1SColin Riley 
39344640cde1SColin Riley class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword
39354640cde1SColin Riley {
39364640cde1SColin Riley public:
39374640cde1SColin Riley     CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
39387428a18cSKate Stone         : CommandObjectMultiword(interpreter, "renderscript context", "Commands that deal with RenderScript contexts.",
3939b3f7f69dSAidan Dodds                                  nullptr)
39404640cde1SColin Riley     {
39414640cde1SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(interpreter)));
39424640cde1SColin Riley     }
39434640cde1SColin Riley 
3944222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeContext() override = default;
39454640cde1SColin Riley };
39464640cde1SColin Riley 
3947a0f08674SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationDump : public CommandObjectParsed
3948a0f08674SEwan Crawford {
3949a0f08674SEwan Crawford public:
3950a0f08674SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationDump(CommandInterpreter &interpreter)
3951a0f08674SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation dump",
3952a0f08674SEwan Crawford                               "Displays the contents of a particular allocation", "renderscript allocation dump <ID>",
3953b3f7f69dSAidan Dodds                               eCommandRequiresProcess | eCommandProcessMustBeLaunched),
3954*e1cfbc79STodd Fiala           m_options()
3955a0f08674SEwan Crawford     {
3956a0f08674SEwan Crawford     }
3957a0f08674SEwan Crawford 
3958222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
3959222b937cSEugene Zelenko 
3960222b937cSEugene Zelenko     Options *
3961222b937cSEugene Zelenko     GetOptions() override
3962a0f08674SEwan Crawford     {
3963a0f08674SEwan Crawford         return &m_options;
3964a0f08674SEwan Crawford     }
3965a0f08674SEwan Crawford 
3966a0f08674SEwan Crawford     class CommandOptions : public Options
3967a0f08674SEwan Crawford     {
3968a0f08674SEwan Crawford     public:
3969*e1cfbc79STodd Fiala         CommandOptions() : Options() {}
3970a0f08674SEwan Crawford 
3971222b937cSEugene Zelenko         ~CommandOptions() override = default;
3972a0f08674SEwan Crawford 
3973222b937cSEugene Zelenko         Error
3974*e1cfbc79STodd Fiala         SetOptionValue(uint32_t option_idx, const char *option_arg,
3975*e1cfbc79STodd Fiala                        ExecutionContext *execution_context) override
3976a0f08674SEwan Crawford         {
3977a0f08674SEwan Crawford             Error error;
3978a0f08674SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
3979a0f08674SEwan Crawford 
3980a0f08674SEwan Crawford             switch (short_option)
3981a0f08674SEwan Crawford             {
3982a0f08674SEwan Crawford                 case 'f':
3983a0f08674SEwan Crawford                     m_outfile.SetFile(option_arg, true);
3984a0f08674SEwan Crawford                     if (m_outfile.Exists())
3985a0f08674SEwan Crawford                     {
3986a0f08674SEwan Crawford                         m_outfile.Clear();
3987a0f08674SEwan Crawford                         error.SetErrorStringWithFormat("file already exists: '%s'", option_arg);
3988a0f08674SEwan Crawford                     }
3989a0f08674SEwan Crawford                     break;
3990a0f08674SEwan Crawford                 default:
3991a0f08674SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3992a0f08674SEwan Crawford                     break;
3993a0f08674SEwan Crawford             }
3994a0f08674SEwan Crawford             return error;
3995a0f08674SEwan Crawford         }
3996a0f08674SEwan Crawford 
3997a0f08674SEwan Crawford         void
3998*e1cfbc79STodd Fiala         OptionParsingStarting(ExecutionContext *execution_context) override
3999a0f08674SEwan Crawford         {
4000a0f08674SEwan Crawford             m_outfile.Clear();
4001a0f08674SEwan Crawford         }
4002a0f08674SEwan Crawford 
4003a0f08674SEwan Crawford         const OptionDefinition *
4004222b937cSEugene Zelenko         GetDefinitions() override
4005a0f08674SEwan Crawford         {
4006a0f08674SEwan Crawford             return g_option_table;
4007a0f08674SEwan Crawford         }
4008a0f08674SEwan Crawford 
4009a0f08674SEwan Crawford         static OptionDefinition g_option_table[];
4010a0f08674SEwan Crawford         FileSpec m_outfile;
4011a0f08674SEwan Crawford     };
4012a0f08674SEwan Crawford 
4013a0f08674SEwan Crawford     bool
4014222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
4015a0f08674SEwan Crawford     {
4016a0f08674SEwan Crawford         const size_t argc = command.GetArgumentCount();
4017a0f08674SEwan Crawford         if (argc < 1)
4018a0f08674SEwan Crawford         {
4019a0f08674SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. As well as an optional -f argument",
4020a0f08674SEwan Crawford                                          m_cmd_name.c_str());
4021a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
4022a0f08674SEwan Crawford             return false;
4023a0f08674SEwan Crawford         }
4024a0f08674SEwan Crawford 
4025b3f7f69dSAidan Dodds         RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4026b3f7f69dSAidan Dodds             m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
4027a0f08674SEwan Crawford 
4028a0f08674SEwan Crawford         const char *id_cstr = command.GetArgumentAtIndex(0);
4029a0f08674SEwan Crawford         bool convert_complete = false;
4030a0f08674SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
4031a0f08674SEwan Crawford         if (!convert_complete)
4032a0f08674SEwan Crawford         {
4033a0f08674SEwan Crawford             result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
4034a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
4035a0f08674SEwan Crawford             return false;
4036a0f08674SEwan Crawford         }
4037a0f08674SEwan Crawford 
4038a0f08674SEwan Crawford         Stream *output_strm = nullptr;
4039a0f08674SEwan Crawford         StreamFile outfile_stream;
4040a0f08674SEwan Crawford         const FileSpec &outfile_spec = m_options.m_outfile; // Dump allocation to file instead
4041a0f08674SEwan Crawford         if (outfile_spec)
4042a0f08674SEwan Crawford         {
4043a0f08674SEwan Crawford             // Open output file
4044a0f08674SEwan Crawford             char path[256];
4045a0f08674SEwan Crawford             outfile_spec.GetPath(path, sizeof(path));
4046a0f08674SEwan Crawford             if (outfile_stream.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate).Success())
4047a0f08674SEwan Crawford             {
4048a0f08674SEwan Crawford                 output_strm = &outfile_stream;
4049a0f08674SEwan Crawford                 result.GetOutputStream().Printf("Results written to '%s'", path);
4050a0f08674SEwan Crawford                 result.GetOutputStream().EOL();
4051a0f08674SEwan Crawford             }
4052a0f08674SEwan Crawford             else
4053a0f08674SEwan Crawford             {
4054a0f08674SEwan Crawford                 result.AppendErrorWithFormat("Couldn't open file '%s'", path);
4055a0f08674SEwan Crawford                 result.SetStatus(eReturnStatusFailed);
4056a0f08674SEwan Crawford                 return false;
4057a0f08674SEwan Crawford             }
4058a0f08674SEwan Crawford         }
4059a0f08674SEwan Crawford         else
4060a0f08674SEwan Crawford             output_strm = &result.GetOutputStream();
4061a0f08674SEwan Crawford 
4062a0f08674SEwan Crawford         assert(output_strm != nullptr);
4063a0f08674SEwan Crawford         bool success = runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4064a0f08674SEwan Crawford 
4065a0f08674SEwan Crawford         if (success)
4066a0f08674SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
4067a0f08674SEwan Crawford         else
4068a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
4069a0f08674SEwan Crawford 
4070a0f08674SEwan Crawford         return true;
4071a0f08674SEwan Crawford     }
4072a0f08674SEwan Crawford 
4073a0f08674SEwan Crawford private:
4074a0f08674SEwan Crawford     CommandOptions m_options;
4075a0f08674SEwan Crawford };
4076a0f08674SEwan Crawford 
4077b3f7f69dSAidan Dodds OptionDefinition CommandObjectRenderScriptRuntimeAllocationDump::CommandOptions::g_option_table[] = {
4078b3f7f69dSAidan Dodds     {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename,
4079a0f08674SEwan Crawford      "Print results to specified file instead of command line."},
4080b3f7f69dSAidan Dodds     {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}};
4081a0f08674SEwan Crawford 
408215f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationList : public CommandObjectParsed
408315f2bd95SEwan Crawford {
408415f2bd95SEwan Crawford public:
408515f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationList(CommandInterpreter &interpreter)
408615f2bd95SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation list",
408715f2bd95SEwan Crawford                               "List renderscript allocations and their information.", "renderscript allocation list",
4088b3f7f69dSAidan Dodds                               eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4089*e1cfbc79STodd Fiala           m_options()
409015f2bd95SEwan Crawford     {
409115f2bd95SEwan Crawford     }
409215f2bd95SEwan Crawford 
4093222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4094222b937cSEugene Zelenko 
4095222b937cSEugene Zelenko     Options *
4096222b937cSEugene Zelenko     GetOptions() override
409715f2bd95SEwan Crawford     {
409815f2bd95SEwan Crawford         return &m_options;
409915f2bd95SEwan Crawford     }
410015f2bd95SEwan Crawford 
410115f2bd95SEwan Crawford     class CommandOptions : public Options
410215f2bd95SEwan Crawford     {
410315f2bd95SEwan Crawford     public:
4104*e1cfbc79STodd Fiala         CommandOptions() : Options(), m_id(0) {}
410515f2bd95SEwan Crawford 
4106222b937cSEugene Zelenko         ~CommandOptions() override = default;
410715f2bd95SEwan Crawford 
4108222b937cSEugene Zelenko         Error
4109*e1cfbc79STodd Fiala         SetOptionValue(uint32_t option_idx, const char *option_arg,
4110*e1cfbc79STodd Fiala                        ExecutionContext *execution_context) override
411115f2bd95SEwan Crawford         {
411215f2bd95SEwan Crawford             Error error;
411315f2bd95SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
411415f2bd95SEwan Crawford 
411515f2bd95SEwan Crawford             switch (short_option)
411615f2bd95SEwan Crawford             {
4117b649b005SEwan Crawford                 case 'i':
4118b649b005SEwan Crawford                     bool success;
4119b649b005SEwan Crawford                     m_id = StringConvert::ToUInt32(option_arg, 0, 0, &success);
4120b649b005SEwan Crawford                     if (!success)
4121b649b005SEwan Crawford                         error.SetErrorStringWithFormat("invalid integer value for option '%c'", short_option);
412215f2bd95SEwan Crawford                     break;
412315f2bd95SEwan Crawford                 default:
412415f2bd95SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
412515f2bd95SEwan Crawford                     break;
412615f2bd95SEwan Crawford             }
412715f2bd95SEwan Crawford             return error;
412815f2bd95SEwan Crawford         }
412915f2bd95SEwan Crawford 
413015f2bd95SEwan Crawford         void
4131*e1cfbc79STodd Fiala         OptionParsingStarting(ExecutionContext *execution_context) override
413215f2bd95SEwan Crawford         {
4133b649b005SEwan Crawford             m_id = 0;
413415f2bd95SEwan Crawford         }
413515f2bd95SEwan Crawford 
413615f2bd95SEwan Crawford         const OptionDefinition *
4137222b937cSEugene Zelenko         GetDefinitions() override
413815f2bd95SEwan Crawford         {
413915f2bd95SEwan Crawford             return g_option_table;
414015f2bd95SEwan Crawford         }
414115f2bd95SEwan Crawford 
414215f2bd95SEwan Crawford         static OptionDefinition g_option_table[];
4143b649b005SEwan Crawford         uint32_t m_id;
414415f2bd95SEwan Crawford     };
414515f2bd95SEwan Crawford 
414615f2bd95SEwan Crawford     bool
4147222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
414815f2bd95SEwan Crawford     {
4149b3f7f69dSAidan Dodds         RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4150b3f7f69dSAidan Dodds             m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
4151b649b005SEwan Crawford         runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(), m_options.m_id);
415215f2bd95SEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
415315f2bd95SEwan Crawford         return true;
415415f2bd95SEwan Crawford     }
415515f2bd95SEwan Crawford 
415615f2bd95SEwan Crawford private:
415715f2bd95SEwan Crawford     CommandOptions m_options;
415815f2bd95SEwan Crawford };
415915f2bd95SEwan Crawford 
4160b649b005SEwan Crawford OptionDefinition CommandObjectRenderScriptRuntimeAllocationList::CommandOptions::g_option_table[] = {
4161b3f7f69dSAidan Dodds     {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeIndex,
4162b649b005SEwan Crawford      "Only show details of a single allocation with specified id."},
4163b3f7f69dSAidan Dodds     {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}};
416415f2bd95SEwan Crawford 
416555232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationLoad : public CommandObjectParsed
416655232f09SEwan Crawford {
416755232f09SEwan Crawford public:
416855232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationLoad(CommandInterpreter &interpreter)
4169b3f7f69dSAidan Dodds         : CommandObjectParsed(
4170b3f7f69dSAidan Dodds               interpreter, "renderscript allocation load", "Loads renderscript allocation contents from a file.",
4171b3f7f69dSAidan Dodds               "renderscript allocation load <ID> <filename>", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
417255232f09SEwan Crawford     {
417355232f09SEwan Crawford     }
417455232f09SEwan Crawford 
4175222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
417655232f09SEwan Crawford 
417755232f09SEwan Crawford     bool
4178222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
417955232f09SEwan Crawford     {
418055232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
418155232f09SEwan Crawford         if (argc != 2)
418255232f09SEwan Crawford         {
4183b3f7f69dSAidan Dodds             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.",
4184b3f7f69dSAidan Dodds                                          m_cmd_name.c_str());
418555232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
418655232f09SEwan Crawford             return false;
418755232f09SEwan Crawford         }
418855232f09SEwan Crawford 
4189b3f7f69dSAidan Dodds         RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4190b3f7f69dSAidan Dodds             m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
419155232f09SEwan Crawford 
419255232f09SEwan Crawford         const char *id_cstr = command.GetArgumentAtIndex(0);
419355232f09SEwan Crawford         bool convert_complete = false;
419455232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
419555232f09SEwan Crawford         if (!convert_complete)
419655232f09SEwan Crawford         {
419755232f09SEwan Crawford             result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
419855232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
419955232f09SEwan Crawford             return false;
420055232f09SEwan Crawford         }
420155232f09SEwan Crawford 
420255232f09SEwan Crawford         const char *filename = command.GetArgumentAtIndex(1);
420355232f09SEwan Crawford         bool success = runtime->LoadAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
420455232f09SEwan Crawford 
420555232f09SEwan Crawford         if (success)
420655232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
420755232f09SEwan Crawford         else
420855232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
420955232f09SEwan Crawford 
421055232f09SEwan Crawford         return true;
421155232f09SEwan Crawford     }
421255232f09SEwan Crawford };
421355232f09SEwan Crawford 
421455232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationSave : public CommandObjectParsed
421555232f09SEwan Crawford {
421655232f09SEwan Crawford public:
421755232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationSave(CommandInterpreter &interpreter)
4218b3f7f69dSAidan Dodds         : CommandObjectParsed(
4219b3f7f69dSAidan Dodds               interpreter, "renderscript allocation save", "Write renderscript allocation contents to a file.",
4220b3f7f69dSAidan Dodds               "renderscript allocation save <ID> <filename>", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
422155232f09SEwan Crawford     {
422255232f09SEwan Crawford     }
422355232f09SEwan Crawford 
4224222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
422555232f09SEwan Crawford 
422655232f09SEwan Crawford     bool
4227222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
422855232f09SEwan Crawford     {
422955232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
423055232f09SEwan Crawford         if (argc != 2)
423155232f09SEwan Crawford         {
4232b3f7f69dSAidan Dodds             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.",
4233b3f7f69dSAidan Dodds                                          m_cmd_name.c_str());
423455232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
423555232f09SEwan Crawford             return false;
423655232f09SEwan Crawford         }
423755232f09SEwan Crawford 
4238b3f7f69dSAidan Dodds         RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4239b3f7f69dSAidan Dodds             m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
424055232f09SEwan Crawford 
424155232f09SEwan Crawford         const char *id_cstr = command.GetArgumentAtIndex(0);
424255232f09SEwan Crawford         bool convert_complete = false;
424355232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
424455232f09SEwan Crawford         if (!convert_complete)
424555232f09SEwan Crawford         {
424655232f09SEwan Crawford             result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
424755232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
424855232f09SEwan Crawford             return false;
424955232f09SEwan Crawford         }
425055232f09SEwan Crawford 
425155232f09SEwan Crawford         const char *filename = command.GetArgumentAtIndex(1);
425255232f09SEwan Crawford         bool success = runtime->SaveAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
425355232f09SEwan Crawford 
425455232f09SEwan Crawford         if (success)
425555232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
425655232f09SEwan Crawford         else
425755232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
425855232f09SEwan Crawford 
425955232f09SEwan Crawford         return true;
426055232f09SEwan Crawford     }
426155232f09SEwan Crawford };
426255232f09SEwan Crawford 
42630d2bfcfbSEwan Crawford class CommandObjectRenderScriptRuntimeAllocationRefresh : public CommandObjectParsed
42640d2bfcfbSEwan Crawford {
42650d2bfcfbSEwan Crawford public:
42660d2bfcfbSEwan Crawford     CommandObjectRenderScriptRuntimeAllocationRefresh(CommandInterpreter &interpreter)
42670d2bfcfbSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation refresh",
42680d2bfcfbSEwan Crawford                               "Recomputes the details of all allocations.", "renderscript allocation refresh",
42690d2bfcfbSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
42700d2bfcfbSEwan Crawford     {
42710d2bfcfbSEwan Crawford     }
42720d2bfcfbSEwan Crawford 
42730d2bfcfbSEwan Crawford     ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
42740d2bfcfbSEwan Crawford 
42750d2bfcfbSEwan Crawford     bool
42760d2bfcfbSEwan Crawford     DoExecute(Args &command, CommandReturnObject &result) override
42770d2bfcfbSEwan Crawford     {
42780d2bfcfbSEwan Crawford         RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
42790d2bfcfbSEwan Crawford             m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
42800d2bfcfbSEwan Crawford 
42810d2bfcfbSEwan Crawford         bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr());
42820d2bfcfbSEwan Crawford 
42830d2bfcfbSEwan Crawford         if (success)
42840d2bfcfbSEwan Crawford         {
42850d2bfcfbSEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
42860d2bfcfbSEwan Crawford             return true;
42870d2bfcfbSEwan Crawford         }
42880d2bfcfbSEwan Crawford         else
42890d2bfcfbSEwan Crawford         {
42900d2bfcfbSEwan Crawford             result.SetStatus(eReturnStatusFailed);
42910d2bfcfbSEwan Crawford             return false;
42920d2bfcfbSEwan Crawford         }
42930d2bfcfbSEwan Crawford     }
42940d2bfcfbSEwan Crawford };
42950d2bfcfbSEwan Crawford 
429615f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocation : public CommandObjectMultiword
429715f2bd95SEwan Crawford {
429815f2bd95SEwan Crawford public:
429915f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4300b3f7f69dSAidan Dodds         : CommandObjectMultiword(interpreter, "renderscript allocation",
43017428a18cSKate Stone                                  "Commands that deal with RenderScript allocations.", nullptr)
430215f2bd95SEwan Crawford     {
430315f2bd95SEwan Crawford         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4304a0f08674SEwan Crawford         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
430555232f09SEwan Crawford         LoadSubCommand("save", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
430655232f09SEwan Crawford         LoadSubCommand("load", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
43070d2bfcfbSEwan Crawford         LoadSubCommand("refresh", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(interpreter)));
430815f2bd95SEwan Crawford     }
430915f2bd95SEwan Crawford 
4310222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocation() override = default;
431115f2bd95SEwan Crawford };
431215f2bd95SEwan Crawford 
43134640cde1SColin Riley class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed
43144640cde1SColin Riley {
43154640cde1SColin Riley public:
43164640cde1SColin Riley     CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
43177428a18cSKate Stone         : CommandObjectParsed(interpreter, "renderscript status", "Displays current RenderScript runtime status.",
4318b3f7f69dSAidan Dodds                               "renderscript status", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
43194640cde1SColin Riley     {
43204640cde1SColin Riley     }
43214640cde1SColin Riley 
4322222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeStatus() override = default;
43234640cde1SColin Riley 
43244640cde1SColin Riley     bool
4325222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
43264640cde1SColin Riley     {
43274640cde1SColin Riley         RenderScriptRuntime *runtime =
43284640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
43294640cde1SColin Riley         runtime->Status(result.GetOutputStream());
43304640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
43314640cde1SColin Riley         return true;
43324640cde1SColin Riley     }
43334640cde1SColin Riley };
43344640cde1SColin Riley 
43355ec532a9SColin Riley class CommandObjectRenderScriptRuntime : public CommandObjectMultiword
43365ec532a9SColin Riley {
43375ec532a9SColin Riley public:
43385ec532a9SColin Riley     CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
43397428a18cSKate Stone         : CommandObjectMultiword(interpreter, "renderscript", "Commands for operating on the RenderScript runtime.",
43405ec532a9SColin Riley                                  "renderscript <subcommand> [<subcommand-options>]")
43415ec532a9SColin Riley     {
43425ec532a9SColin Riley         LoadSubCommand("module", CommandObjectSP(new CommandObjectRenderScriptRuntimeModule(interpreter)));
43434640cde1SColin Riley         LoadSubCommand("status", CommandObjectSP(new CommandObjectRenderScriptRuntimeStatus(interpreter)));
43444640cde1SColin Riley         LoadSubCommand("kernel", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernel(interpreter)));
43454640cde1SColin Riley         LoadSubCommand("context", CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(interpreter)));
434615f2bd95SEwan Crawford         LoadSubCommand("allocation", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
43475ec532a9SColin Riley     }
43485ec532a9SColin Riley 
4349222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntime() override = default;
43505ec532a9SColin Riley };
4351ef20b08fSColin Riley 
4352ef20b08fSColin Riley void
4353ef20b08fSColin Riley RenderScriptRuntime::Initiate()
43545ec532a9SColin Riley {
4355ef20b08fSColin Riley     assert(!m_initiated);
43565ec532a9SColin Riley }
4357ef20b08fSColin Riley 
4358ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
4359b3f7f69dSAidan Dodds     : lldb_private::CPPLanguageRuntime(process),
4360b3f7f69dSAidan Dodds       m_initiated(false),
4361b3f7f69dSAidan Dodds       m_debuggerPresentFlagged(false),
436219459580SLuke Drummond       m_breakAllKernels(false),
436319459580SLuke Drummond       m_ir_passes(nullptr)
4364ef20b08fSColin Riley {
43654640cde1SColin Riley     ModulesDidLoad(process->GetTarget().GetImages());
4366ef20b08fSColin Riley }
43674640cde1SColin Riley 
43684640cde1SColin Riley lldb::CommandObjectSP
43694640cde1SColin Riley RenderScriptRuntime::GetCommandObject(lldb_private::CommandInterpreter &interpreter)
43704640cde1SColin Riley {
43710a66e2f1SEnrico Granata     return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
43724640cde1SColin Riley }
43734640cde1SColin Riley 
437478f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
4375