1dda28197Spatrick //===-- RenderScriptRuntime.cpp -------------------------------------------===//
2061da546Spatrick //
3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6061da546Spatrick //
7061da546Spatrick //===----------------------------------------------------------------------===//
8061da546Spatrick
9061da546Spatrick #include "RenderScriptRuntime.h"
10061da546Spatrick #include "RenderScriptScriptGroup.h"
11061da546Spatrick
12061da546Spatrick #include "lldb/Breakpoint/StoppointCallbackContext.h"
13061da546Spatrick #include "lldb/Core/Debugger.h"
14061da546Spatrick #include "lldb/Core/DumpDataExtractor.h"
15061da546Spatrick #include "lldb/Core/PluginManager.h"
16061da546Spatrick #include "lldb/Core/ValueObjectVariable.h"
17061da546Spatrick #include "lldb/DataFormatters/DumpValueObjectOptions.h"
18061da546Spatrick #include "lldb/Expression/UserExpression.h"
19061da546Spatrick #include "lldb/Host/OptionParser.h"
20061da546Spatrick #include "lldb/Interpreter/CommandInterpreter.h"
21061da546Spatrick #include "lldb/Interpreter/CommandObjectMultiword.h"
22061da546Spatrick #include "lldb/Interpreter/CommandReturnObject.h"
23061da546Spatrick #include "lldb/Interpreter/Options.h"
24061da546Spatrick #include "lldb/Symbol/Function.h"
25061da546Spatrick #include "lldb/Symbol/Symbol.h"
26061da546Spatrick #include "lldb/Symbol/Type.h"
27061da546Spatrick #include "lldb/Symbol/VariableList.h"
28061da546Spatrick #include "lldb/Target/Process.h"
29061da546Spatrick #include "lldb/Target/RegisterContext.h"
30061da546Spatrick #include "lldb/Target/SectionLoadList.h"
31061da546Spatrick #include "lldb/Target/Target.h"
32061da546Spatrick #include "lldb/Target/Thread.h"
33061da546Spatrick #include "lldb/Utility/Args.h"
34061da546Spatrick #include "lldb/Utility/ConstString.h"
35*f6aab3d8Srobert #include "lldb/Utility/LLDBLog.h"
36061da546Spatrick #include "lldb/Utility/Log.h"
37061da546Spatrick #include "lldb/Utility/RegisterValue.h"
38061da546Spatrick #include "lldb/Utility/RegularExpression.h"
39061da546Spatrick #include "lldb/Utility/Status.h"
40061da546Spatrick
41061da546Spatrick #include "llvm/ADT/StringSwitch.h"
42061da546Spatrick
43061da546Spatrick #include <memory>
44061da546Spatrick
45061da546Spatrick using namespace lldb;
46061da546Spatrick using namespace lldb_private;
47061da546Spatrick using namespace lldb_renderscript;
48061da546Spatrick
49dda28197Spatrick LLDB_PLUGIN_DEFINE(RenderScriptRuntime)
50dda28197Spatrick
51061da546Spatrick #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")"
52061da546Spatrick
53061da546Spatrick char RenderScriptRuntime::ID = 0;
54061da546Spatrick
55061da546Spatrick namespace {
56061da546Spatrick
57061da546Spatrick // The empirical_type adds a basic level of validation to arbitrary data
58061da546Spatrick // allowing us to track if data has been discovered and stored or not. An
59061da546Spatrick // empirical_type will be marked as valid only if it has been explicitly
60061da546Spatrick // assigned to.
61061da546Spatrick template <typename type_t> class empirical_type {
62061da546Spatrick public:
63061da546Spatrick // Ctor. Contents is invalid when constructed.
64be691f3bSpatrick empirical_type() = default;
65061da546Spatrick
66061da546Spatrick // Return true and copy contents to out if valid, else return false.
get(type_t & out) const67061da546Spatrick bool get(type_t &out) const {
68061da546Spatrick if (valid)
69061da546Spatrick out = data;
70061da546Spatrick return valid;
71061da546Spatrick }
72061da546Spatrick
73061da546Spatrick // Return a pointer to the contents or nullptr if it was not valid.
get() const74061da546Spatrick const type_t *get() const { return valid ? &data : nullptr; }
75061da546Spatrick
76061da546Spatrick // Assign data explicitly.
set(const type_t in)77061da546Spatrick void set(const type_t in) {
78061da546Spatrick data = in;
79061da546Spatrick valid = true;
80061da546Spatrick }
81061da546Spatrick
82061da546Spatrick // Mark contents as invalid.
invalidate()83061da546Spatrick void invalidate() { valid = false; }
84061da546Spatrick
85061da546Spatrick // Returns true if this type contains valid data.
isValid() const86061da546Spatrick bool isValid() const { return valid; }
87061da546Spatrick
88061da546Spatrick // Assignment operator.
operator =(const type_t in)89061da546Spatrick empirical_type<type_t> &operator=(const type_t in) {
90061da546Spatrick set(in);
91061da546Spatrick return *this;
92061da546Spatrick }
93061da546Spatrick
94061da546Spatrick // Dereference operator returns contents.
95061da546Spatrick // Warning: Will assert if not valid so use only when you know data is valid.
operator *() const96061da546Spatrick const type_t &operator*() const {
97061da546Spatrick assert(valid);
98061da546Spatrick return data;
99061da546Spatrick }
100061da546Spatrick
101061da546Spatrick protected:
102be691f3bSpatrick bool valid = false;
103061da546Spatrick type_t data;
104061da546Spatrick };
105061da546Spatrick
106061da546Spatrick // ArgItem is used by the GetArgs() function when reading function arguments
107061da546Spatrick // from the target.
108061da546Spatrick struct ArgItem {
109061da546Spatrick enum { ePointer, eInt32, eInt64, eLong, eBool } type;
110061da546Spatrick
111061da546Spatrick uint64_t value;
112061da546Spatrick
operator uint64_t__anon56233e910111::ArgItem113061da546Spatrick explicit operator uint64_t() const { return value; }
114061da546Spatrick };
115061da546Spatrick
116061da546Spatrick // Context structure to be passed into GetArgsXXX(), argument reading functions
117061da546Spatrick // below.
118061da546Spatrick struct GetArgsCtx {
119061da546Spatrick RegisterContext *reg_ctx;
120061da546Spatrick Process *process;
121061da546Spatrick };
122061da546Spatrick
GetArgsX86(const GetArgsCtx & ctx,ArgItem * arg_list,size_t num_args)123061da546Spatrick bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
124*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
125061da546Spatrick
126061da546Spatrick Status err;
127061da546Spatrick
128061da546Spatrick // get the current stack pointer
129061da546Spatrick uint64_t sp = ctx.reg_ctx->GetSP();
130061da546Spatrick
131061da546Spatrick for (size_t i = 0; i < num_args; ++i) {
132061da546Spatrick ArgItem &arg = arg_list[i];
133061da546Spatrick // advance up the stack by one argument
134061da546Spatrick sp += sizeof(uint32_t);
135061da546Spatrick // get the argument type size
136061da546Spatrick size_t arg_size = sizeof(uint32_t);
137061da546Spatrick // read the argument from memory
138061da546Spatrick arg.value = 0;
139061da546Spatrick Status err;
140061da546Spatrick size_t read =
141061da546Spatrick ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
142061da546Spatrick if (read != arg_size || !err.Success()) {
143061da546Spatrick LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 " '%s'",
144061da546Spatrick __FUNCTION__, uint64_t(i), err.AsCString());
145061da546Spatrick return false;
146061da546Spatrick }
147061da546Spatrick }
148061da546Spatrick return true;
149061da546Spatrick }
150061da546Spatrick
GetArgsX86_64(GetArgsCtx & ctx,ArgItem * arg_list,size_t num_args)151061da546Spatrick bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
152*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
153061da546Spatrick
154061da546Spatrick // number of arguments passed in registers
155061da546Spatrick static const uint32_t args_in_reg = 6;
156061da546Spatrick // register passing order
157061da546Spatrick static const std::array<const char *, args_in_reg> reg_names{
158061da546Spatrick {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
159061da546Spatrick // argument type to size mapping
160061da546Spatrick static const std::array<size_t, 5> arg_size{{
161061da546Spatrick 8, // ePointer,
162061da546Spatrick 4, // eInt32,
163061da546Spatrick 8, // eInt64,
164061da546Spatrick 8, // eLong,
165061da546Spatrick 4, // eBool,
166061da546Spatrick }};
167061da546Spatrick
168061da546Spatrick Status err;
169061da546Spatrick
170061da546Spatrick // get the current stack pointer
171061da546Spatrick uint64_t sp = ctx.reg_ctx->GetSP();
172061da546Spatrick // step over the return address
173061da546Spatrick sp += sizeof(uint64_t);
174061da546Spatrick
175061da546Spatrick // check the stack alignment was correct (16 byte aligned)
176061da546Spatrick if ((sp & 0xf) != 0x0) {
177061da546Spatrick LLDB_LOGF(log, "%s - stack misaligned", __FUNCTION__);
178061da546Spatrick return false;
179061da546Spatrick }
180061da546Spatrick
181061da546Spatrick // find the start of arguments on the stack
182061da546Spatrick uint64_t sp_offset = 0;
183061da546Spatrick for (uint32_t i = args_in_reg; i < num_args; ++i) {
184061da546Spatrick sp_offset += arg_size[arg_list[i].type];
185061da546Spatrick }
186061da546Spatrick // round up to multiple of 16
187061da546Spatrick sp_offset = (sp_offset + 0xf) & 0xf;
188061da546Spatrick sp += sp_offset;
189061da546Spatrick
190061da546Spatrick for (size_t i = 0; i < num_args; ++i) {
191061da546Spatrick bool success = false;
192061da546Spatrick ArgItem &arg = arg_list[i];
193061da546Spatrick // arguments passed in registers
194061da546Spatrick if (i < args_in_reg) {
195061da546Spatrick const RegisterInfo *reg =
196061da546Spatrick ctx.reg_ctx->GetRegisterInfoByName(reg_names[i]);
197061da546Spatrick RegisterValue reg_val;
198061da546Spatrick if (ctx.reg_ctx->ReadRegister(reg, reg_val))
199061da546Spatrick arg.value = reg_val.GetAsUInt64(0, &success);
200061da546Spatrick }
201061da546Spatrick // arguments passed on the stack
202061da546Spatrick else {
203061da546Spatrick // get the argument type size
204061da546Spatrick const size_t size = arg_size[arg_list[i].type];
205061da546Spatrick // read the argument from memory
206061da546Spatrick arg.value = 0;
207061da546Spatrick // note: due to little endian layout reading 4 or 8 bytes will give the
208061da546Spatrick // correct value.
209061da546Spatrick size_t read = ctx.process->ReadMemory(sp, &arg.value, size, err);
210061da546Spatrick success = (err.Success() && read == size);
211061da546Spatrick // advance past this argument
212061da546Spatrick sp -= size;
213061da546Spatrick }
214061da546Spatrick // fail if we couldn't read this argument
215061da546Spatrick if (!success) {
216061da546Spatrick LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
217061da546Spatrick __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
218061da546Spatrick return false;
219061da546Spatrick }
220061da546Spatrick }
221061da546Spatrick return true;
222061da546Spatrick }
223061da546Spatrick
GetArgsArm(GetArgsCtx & ctx,ArgItem * arg_list,size_t num_args)224061da546Spatrick bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
225061da546Spatrick // number of arguments passed in registers
226061da546Spatrick static const uint32_t args_in_reg = 4;
227061da546Spatrick
228*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
229061da546Spatrick
230061da546Spatrick Status err;
231061da546Spatrick
232061da546Spatrick // get the current stack pointer
233061da546Spatrick uint64_t sp = ctx.reg_ctx->GetSP();
234061da546Spatrick
235061da546Spatrick for (size_t i = 0; i < num_args; ++i) {
236061da546Spatrick bool success = false;
237061da546Spatrick ArgItem &arg = arg_list[i];
238061da546Spatrick // arguments passed in registers
239061da546Spatrick if (i < args_in_reg) {
240061da546Spatrick const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
241061da546Spatrick RegisterValue reg_val;
242061da546Spatrick if (ctx.reg_ctx->ReadRegister(reg, reg_val))
243061da546Spatrick arg.value = reg_val.GetAsUInt32(0, &success);
244061da546Spatrick }
245061da546Spatrick // arguments passed on the stack
246061da546Spatrick else {
247061da546Spatrick // get the argument type size
248061da546Spatrick const size_t arg_size = sizeof(uint32_t);
249061da546Spatrick // clear all 64bits
250061da546Spatrick arg.value = 0;
251061da546Spatrick // read this argument from memory
252061da546Spatrick size_t bytes_read =
253061da546Spatrick ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
254061da546Spatrick success = (err.Success() && bytes_read == arg_size);
255061da546Spatrick // advance the stack pointer
256061da546Spatrick sp += sizeof(uint32_t);
257061da546Spatrick }
258061da546Spatrick // fail if we couldn't read this argument
259061da546Spatrick if (!success) {
260061da546Spatrick LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
261061da546Spatrick __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
262061da546Spatrick return false;
263061da546Spatrick }
264061da546Spatrick }
265061da546Spatrick return true;
266061da546Spatrick }
267061da546Spatrick
GetArgsAarch64(GetArgsCtx & ctx,ArgItem * arg_list,size_t num_args)268061da546Spatrick bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
269061da546Spatrick // number of arguments passed in registers
270061da546Spatrick static const uint32_t args_in_reg = 8;
271061da546Spatrick
272*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
273061da546Spatrick
274061da546Spatrick for (size_t i = 0; i < num_args; ++i) {
275061da546Spatrick bool success = false;
276061da546Spatrick ArgItem &arg = arg_list[i];
277061da546Spatrick // arguments passed in registers
278061da546Spatrick if (i < args_in_reg) {
279061da546Spatrick const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
280061da546Spatrick RegisterValue reg_val;
281061da546Spatrick if (ctx.reg_ctx->ReadRegister(reg, reg_val))
282061da546Spatrick arg.value = reg_val.GetAsUInt64(0, &success);
283061da546Spatrick }
284061da546Spatrick // arguments passed on the stack
285061da546Spatrick else {
286061da546Spatrick LLDB_LOGF(log, "%s - reading arguments spilled to stack not implemented",
287061da546Spatrick __FUNCTION__);
288061da546Spatrick }
289061da546Spatrick // fail if we couldn't read this argument
290061da546Spatrick if (!success) {
291061da546Spatrick LLDB_LOGF(log, "%s - error reading argument: %" PRIu64, __FUNCTION__,
292061da546Spatrick uint64_t(i));
293061da546Spatrick return false;
294061da546Spatrick }
295061da546Spatrick }
296061da546Spatrick return true;
297061da546Spatrick }
298061da546Spatrick
GetArgsMipsel(GetArgsCtx & ctx,ArgItem * arg_list,size_t num_args)299061da546Spatrick bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
300061da546Spatrick // number of arguments passed in registers
301061da546Spatrick static const uint32_t args_in_reg = 4;
302061da546Spatrick // register file offset to first argument
303061da546Spatrick static const uint32_t reg_offset = 4;
304061da546Spatrick
305*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
306061da546Spatrick
307061da546Spatrick Status err;
308061da546Spatrick
309061da546Spatrick // find offset to arguments on the stack (+16 to skip over a0-a3 shadow
310061da546Spatrick // space)
311061da546Spatrick uint64_t sp = ctx.reg_ctx->GetSP() + 16;
312061da546Spatrick
313061da546Spatrick for (size_t i = 0; i < num_args; ++i) {
314061da546Spatrick bool success = false;
315061da546Spatrick ArgItem &arg = arg_list[i];
316061da546Spatrick // arguments passed in registers
317061da546Spatrick if (i < args_in_reg) {
318061da546Spatrick const RegisterInfo *reg =
319061da546Spatrick ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
320061da546Spatrick RegisterValue reg_val;
321061da546Spatrick if (ctx.reg_ctx->ReadRegister(reg, reg_val))
322061da546Spatrick arg.value = reg_val.GetAsUInt64(0, &success);
323061da546Spatrick }
324061da546Spatrick // arguments passed on the stack
325061da546Spatrick else {
326061da546Spatrick const size_t arg_size = sizeof(uint32_t);
327061da546Spatrick arg.value = 0;
328061da546Spatrick size_t bytes_read =
329061da546Spatrick ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
330061da546Spatrick success = (err.Success() && bytes_read == arg_size);
331061da546Spatrick // advance the stack pointer
332061da546Spatrick sp += arg_size;
333061da546Spatrick }
334061da546Spatrick // fail if we couldn't read this argument
335061da546Spatrick if (!success) {
336061da546Spatrick LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
337061da546Spatrick __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
338061da546Spatrick return false;
339061da546Spatrick }
340061da546Spatrick }
341061da546Spatrick return true;
342061da546Spatrick }
343061da546Spatrick
GetArgsMips64el(GetArgsCtx & ctx,ArgItem * arg_list,size_t num_args)344061da546Spatrick bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
345061da546Spatrick // number of arguments passed in registers
346061da546Spatrick static const uint32_t args_in_reg = 8;
347061da546Spatrick // register file offset to first argument
348061da546Spatrick static const uint32_t reg_offset = 4;
349061da546Spatrick
350*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
351061da546Spatrick
352061da546Spatrick Status err;
353061da546Spatrick
354061da546Spatrick // get the current stack pointer
355061da546Spatrick uint64_t sp = ctx.reg_ctx->GetSP();
356061da546Spatrick
357061da546Spatrick for (size_t i = 0; i < num_args; ++i) {
358061da546Spatrick bool success = false;
359061da546Spatrick ArgItem &arg = arg_list[i];
360061da546Spatrick // arguments passed in registers
361061da546Spatrick if (i < args_in_reg) {
362061da546Spatrick const RegisterInfo *reg =
363061da546Spatrick ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
364061da546Spatrick RegisterValue reg_val;
365061da546Spatrick if (ctx.reg_ctx->ReadRegister(reg, reg_val))
366061da546Spatrick arg.value = reg_val.GetAsUInt64(0, &success);
367061da546Spatrick }
368061da546Spatrick // arguments passed on the stack
369061da546Spatrick else {
370061da546Spatrick // get the argument type size
371061da546Spatrick const size_t arg_size = sizeof(uint64_t);
372061da546Spatrick // clear all 64bits
373061da546Spatrick arg.value = 0;
374061da546Spatrick // read this argument from memory
375061da546Spatrick size_t bytes_read =
376061da546Spatrick ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
377061da546Spatrick success = (err.Success() && bytes_read == arg_size);
378061da546Spatrick // advance the stack pointer
379061da546Spatrick sp += arg_size;
380061da546Spatrick }
381061da546Spatrick // fail if we couldn't read this argument
382061da546Spatrick if (!success) {
383061da546Spatrick LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
384061da546Spatrick __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
385061da546Spatrick return false;
386061da546Spatrick }
387061da546Spatrick }
388061da546Spatrick return true;
389061da546Spatrick }
390061da546Spatrick
GetArgs(ExecutionContext & exe_ctx,ArgItem * arg_list,size_t num_args)391061da546Spatrick bool GetArgs(ExecutionContext &exe_ctx, ArgItem *arg_list, size_t num_args) {
392*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
393061da546Spatrick
394061da546Spatrick // verify that we have a target
395061da546Spatrick if (!exe_ctx.GetTargetPtr()) {
396061da546Spatrick LLDB_LOGF(log, "%s - invalid target", __FUNCTION__);
397061da546Spatrick return false;
398061da546Spatrick }
399061da546Spatrick
400061da546Spatrick GetArgsCtx ctx = {exe_ctx.GetRegisterContext(), exe_ctx.GetProcessPtr()};
401061da546Spatrick assert(ctx.reg_ctx && ctx.process);
402061da546Spatrick
403061da546Spatrick // dispatch based on architecture
404061da546Spatrick switch (exe_ctx.GetTargetPtr()->GetArchitecture().GetMachine()) {
405061da546Spatrick case llvm::Triple::ArchType::x86:
406061da546Spatrick return GetArgsX86(ctx, arg_list, num_args);
407061da546Spatrick
408061da546Spatrick case llvm::Triple::ArchType::x86_64:
409061da546Spatrick return GetArgsX86_64(ctx, arg_list, num_args);
410061da546Spatrick
411061da546Spatrick case llvm::Triple::ArchType::arm:
412061da546Spatrick return GetArgsArm(ctx, arg_list, num_args);
413061da546Spatrick
414061da546Spatrick case llvm::Triple::ArchType::aarch64:
415061da546Spatrick return GetArgsAarch64(ctx, arg_list, num_args);
416061da546Spatrick
417061da546Spatrick case llvm::Triple::ArchType::mipsel:
418061da546Spatrick return GetArgsMipsel(ctx, arg_list, num_args);
419061da546Spatrick
420061da546Spatrick case llvm::Triple::ArchType::mips64el:
421061da546Spatrick return GetArgsMips64el(ctx, arg_list, num_args);
422061da546Spatrick
423061da546Spatrick default:
424061da546Spatrick // unsupported architecture
425061da546Spatrick if (log) {
426061da546Spatrick LLDB_LOGF(log, "%s - architecture not supported: '%s'", __FUNCTION__,
427061da546Spatrick exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
428061da546Spatrick }
429061da546Spatrick return false;
430061da546Spatrick }
431061da546Spatrick }
432061da546Spatrick
IsRenderScriptScriptModule(ModuleSP module)433061da546Spatrick bool IsRenderScriptScriptModule(ModuleSP module) {
434061da546Spatrick if (!module)
435061da546Spatrick return false;
436061da546Spatrick return module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
437061da546Spatrick eSymbolTypeData) != nullptr;
438061da546Spatrick }
439061da546Spatrick
ParseCoordinate(llvm::StringRef coord_s,RSCoordinate & coord)440061da546Spatrick bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
441061da546Spatrick // takes an argument of the form 'num[,num][,num]'. Where 'coord_s' is a
442061da546Spatrick // comma separated 1,2 or 3-dimensional coordinate with the whitespace
443061da546Spatrick // trimmed. Missing coordinates are defaulted to zero. If parsing of any
444061da546Spatrick // elements fails the contents of &coord are undefined and `false` is
445061da546Spatrick // returned, `true` otherwise
446061da546Spatrick
447061da546Spatrick llvm::SmallVector<llvm::StringRef, 4> matches;
448061da546Spatrick
449061da546Spatrick if (!RegularExpression("^([0-9]+),([0-9]+),([0-9]+)$")
450061da546Spatrick .Execute(coord_s, &matches) &&
451061da546Spatrick !RegularExpression("^([0-9]+),([0-9]+)$").Execute(coord_s, &matches) &&
452061da546Spatrick !RegularExpression("^([0-9]+)$").Execute(coord_s, &matches))
453061da546Spatrick return false;
454061da546Spatrick
455061da546Spatrick auto get_index = [&](size_t idx, uint32_t &i) -> bool {
456061da546Spatrick std::string group;
457061da546Spatrick errno = 0;
458061da546Spatrick if (idx + 1 < matches.size()) {
459061da546Spatrick return !llvm::StringRef(matches[idx + 1]).getAsInteger<uint32_t>(10, i);
460061da546Spatrick }
461061da546Spatrick return true;
462061da546Spatrick };
463061da546Spatrick
464061da546Spatrick return get_index(0, coord.x) && get_index(1, coord.y) &&
465061da546Spatrick get_index(2, coord.z);
466061da546Spatrick }
467061da546Spatrick
SkipPrologue(lldb::ModuleSP & module,Address & addr)468061da546Spatrick bool SkipPrologue(lldb::ModuleSP &module, Address &addr) {
469*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
470061da546Spatrick SymbolContext sc;
471061da546Spatrick uint32_t resolved_flags =
472061da546Spatrick module->ResolveSymbolContextForAddress(addr, eSymbolContextFunction, sc);
473061da546Spatrick if (resolved_flags & eSymbolContextFunction) {
474061da546Spatrick if (sc.function) {
475061da546Spatrick const uint32_t offset = sc.function->GetPrologueByteSize();
476061da546Spatrick ConstString name = sc.GetFunctionName();
477061da546Spatrick if (offset)
478061da546Spatrick addr.Slide(offset);
479061da546Spatrick LLDB_LOGF(log, "%s: Prologue offset for %s is %" PRIu32, __FUNCTION__,
480061da546Spatrick name.AsCString(), offset);
481061da546Spatrick }
482061da546Spatrick return true;
483061da546Spatrick } else
484061da546Spatrick return false;
485061da546Spatrick }
486061da546Spatrick } // anonymous namespace
487061da546Spatrick
488061da546Spatrick // The ScriptDetails class collects data associated with a single script
489061da546Spatrick // instance.
490061da546Spatrick struct RenderScriptRuntime::ScriptDetails {
491061da546Spatrick ~ScriptDetails() = default;
492061da546Spatrick
493061da546Spatrick enum ScriptType { eScript, eScriptC };
494061da546Spatrick
495061da546Spatrick // The derived type of the script.
496061da546Spatrick empirical_type<ScriptType> type;
497061da546Spatrick // The name of the original source file.
498061da546Spatrick empirical_type<std::string> res_name;
499061da546Spatrick // Path to script .so file on the device.
500061da546Spatrick empirical_type<std::string> shared_lib;
501061da546Spatrick // Directory where kernel objects are cached on device.
502061da546Spatrick empirical_type<std::string> cache_dir;
503061da546Spatrick // Pointer to the context which owns this script.
504061da546Spatrick empirical_type<lldb::addr_t> context;
505061da546Spatrick // Pointer to the script object itself.
506061da546Spatrick empirical_type<lldb::addr_t> script;
507061da546Spatrick };
508061da546Spatrick
509061da546Spatrick // This Element class represents the Element object in RS, defining the type
510061da546Spatrick // associated with an Allocation.
511061da546Spatrick struct RenderScriptRuntime::Element {
512061da546Spatrick // Taken from rsDefines.h
513061da546Spatrick enum DataKind {
514061da546Spatrick RS_KIND_USER,
515061da546Spatrick RS_KIND_PIXEL_L = 7,
516061da546Spatrick RS_KIND_PIXEL_A,
517061da546Spatrick RS_KIND_PIXEL_LA,
518061da546Spatrick RS_KIND_PIXEL_RGB,
519061da546Spatrick RS_KIND_PIXEL_RGBA,
520061da546Spatrick RS_KIND_PIXEL_DEPTH,
521061da546Spatrick RS_KIND_PIXEL_YUV,
522061da546Spatrick RS_KIND_INVALID = 100
523061da546Spatrick };
524061da546Spatrick
525061da546Spatrick // Taken from rsDefines.h
526061da546Spatrick enum DataType {
527061da546Spatrick RS_TYPE_NONE = 0,
528061da546Spatrick RS_TYPE_FLOAT_16,
529061da546Spatrick RS_TYPE_FLOAT_32,
530061da546Spatrick RS_TYPE_FLOAT_64,
531061da546Spatrick RS_TYPE_SIGNED_8,
532061da546Spatrick RS_TYPE_SIGNED_16,
533061da546Spatrick RS_TYPE_SIGNED_32,
534061da546Spatrick RS_TYPE_SIGNED_64,
535061da546Spatrick RS_TYPE_UNSIGNED_8,
536061da546Spatrick RS_TYPE_UNSIGNED_16,
537061da546Spatrick RS_TYPE_UNSIGNED_32,
538061da546Spatrick RS_TYPE_UNSIGNED_64,
539061da546Spatrick RS_TYPE_BOOLEAN,
540061da546Spatrick
541061da546Spatrick RS_TYPE_UNSIGNED_5_6_5,
542061da546Spatrick RS_TYPE_UNSIGNED_5_5_5_1,
543061da546Spatrick RS_TYPE_UNSIGNED_4_4_4_4,
544061da546Spatrick
545061da546Spatrick RS_TYPE_MATRIX_4X4,
546061da546Spatrick RS_TYPE_MATRIX_3X3,
547061da546Spatrick RS_TYPE_MATRIX_2X2,
548061da546Spatrick
549061da546Spatrick RS_TYPE_ELEMENT = 1000,
550061da546Spatrick RS_TYPE_TYPE,
551061da546Spatrick RS_TYPE_ALLOCATION,
552061da546Spatrick RS_TYPE_SAMPLER,
553061da546Spatrick RS_TYPE_SCRIPT,
554061da546Spatrick RS_TYPE_MESH,
555061da546Spatrick RS_TYPE_PROGRAM_FRAGMENT,
556061da546Spatrick RS_TYPE_PROGRAM_VERTEX,
557061da546Spatrick RS_TYPE_PROGRAM_RASTER,
558061da546Spatrick RS_TYPE_PROGRAM_STORE,
559061da546Spatrick RS_TYPE_FONT,
560061da546Spatrick
561061da546Spatrick RS_TYPE_INVALID = 10000
562061da546Spatrick };
563061da546Spatrick
564061da546Spatrick std::vector<Element> children; // Child Element fields for structs
565061da546Spatrick empirical_type<lldb::addr_t>
566061da546Spatrick element_ptr; // Pointer to the RS Element of the Type
567061da546Spatrick empirical_type<DataType>
568061da546Spatrick type; // Type of each data pointer stored by the allocation
569061da546Spatrick empirical_type<DataKind>
570061da546Spatrick type_kind; // Defines pixel type if Allocation is created from an image
571061da546Spatrick empirical_type<uint32_t>
572061da546Spatrick type_vec_size; // Vector size of each data point, e.g '4' for uchar4
573061da546Spatrick empirical_type<uint32_t> field_count; // Number of Subelements
574061da546Spatrick empirical_type<uint32_t> datum_size; // Size of a single Element with padding
575061da546Spatrick empirical_type<uint32_t> padding; // Number of padding bytes
576061da546Spatrick empirical_type<uint32_t>
577061da546Spatrick array_size; // Number of items in array, only needed for structs
578061da546Spatrick ConstString type_name; // Name of type, only needed for structs
579061da546Spatrick
580061da546Spatrick static ConstString
581061da546Spatrick GetFallbackStructName(); // Print this as the type name of a struct Element
582061da546Spatrick // If we can't resolve the actual struct name
583061da546Spatrick
ShouldRefreshRenderScriptRuntime::Element584061da546Spatrick bool ShouldRefresh() const {
585061da546Spatrick const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
586061da546Spatrick const bool valid_type =
587061da546Spatrick type.isValid() && type_vec_size.isValid() && type_kind.isValid();
588061da546Spatrick return !valid_ptr || !valid_type || !datum_size.isValid();
589061da546Spatrick }
590061da546Spatrick };
591061da546Spatrick
592061da546Spatrick // This AllocationDetails class collects data associated with a single
593061da546Spatrick // allocation instance.
594061da546Spatrick struct RenderScriptRuntime::AllocationDetails {
595061da546Spatrick struct Dimension {
596061da546Spatrick uint32_t dim_1;
597061da546Spatrick uint32_t dim_2;
598061da546Spatrick uint32_t dim_3;
599061da546Spatrick uint32_t cube_map;
600061da546Spatrick
DimensionRenderScriptRuntime::AllocationDetails::Dimension601061da546Spatrick Dimension() {
602061da546Spatrick dim_1 = 0;
603061da546Spatrick dim_2 = 0;
604061da546Spatrick dim_3 = 0;
605061da546Spatrick cube_map = 0;
606061da546Spatrick }
607061da546Spatrick };
608061da546Spatrick
609061da546Spatrick // The FileHeader struct specifies the header we use for writing allocations
610061da546Spatrick // to a binary file. Our format begins with the ASCII characters "RSAD",
611061da546Spatrick // identifying the file as an allocation dump. Member variables dims and
612061da546Spatrick // hdr_size are then written consecutively, immediately followed by an
613061da546Spatrick // instance of the ElementHeader struct. Because Elements can contain
614061da546Spatrick // subelements, there may be more than one instance of the ElementHeader
615061da546Spatrick // struct. With this first instance being the root element, and the other
616061da546Spatrick // instances being the root's descendants. To identify which instances are an
617061da546Spatrick // ElementHeader's children, each struct is immediately followed by a
618061da546Spatrick // sequence of consecutive offsets to the start of its child structs. These
619061da546Spatrick // offsets are
620061da546Spatrick // 4 bytes in size, and the 0 offset signifies no more children.
621061da546Spatrick struct FileHeader {
622061da546Spatrick uint8_t ident[4]; // ASCII 'RSAD' identifying the file
623061da546Spatrick uint32_t dims[3]; // Dimensions
624061da546Spatrick uint16_t hdr_size; // Header size in bytes, including all element headers
625061da546Spatrick };
626061da546Spatrick
627061da546Spatrick struct ElementHeader {
628061da546Spatrick uint16_t type; // DataType enum
629061da546Spatrick uint32_t kind; // DataKind enum
630061da546Spatrick uint32_t element_size; // Size of a single element, including padding
631061da546Spatrick uint16_t vector_size; // Vector width
632061da546Spatrick uint32_t array_size; // Number of elements in array
633061da546Spatrick };
634061da546Spatrick
635061da546Spatrick // Monotonically increasing from 1
636061da546Spatrick static uint32_t ID;
637061da546Spatrick
638061da546Spatrick // Maps Allocation DataType enum and vector size to printable strings using
639061da546Spatrick // mapping from RenderScript numerical types summary documentation
640061da546Spatrick static const char *RsDataTypeToString[][4];
641061da546Spatrick
642061da546Spatrick // Maps Allocation DataKind enum to printable strings
643061da546Spatrick static const char *RsDataKindToString[];
644061da546Spatrick
645061da546Spatrick // Maps allocation types to format sizes for printing.
646061da546Spatrick static const uint32_t RSTypeToFormat[][3];
647061da546Spatrick
648061da546Spatrick // Give each allocation an ID as a way
649061da546Spatrick // for commands to reference it.
650061da546Spatrick const uint32_t id;
651061da546Spatrick
652061da546Spatrick // Allocation Element type
653061da546Spatrick RenderScriptRuntime::Element element;
654061da546Spatrick // Dimensions of the Allocation
655061da546Spatrick empirical_type<Dimension> dimension;
656061da546Spatrick // Pointer to address of the RS Allocation
657061da546Spatrick empirical_type<lldb::addr_t> address;
658061da546Spatrick // Pointer to the data held by the Allocation
659061da546Spatrick empirical_type<lldb::addr_t> data_ptr;
660061da546Spatrick // Pointer to the RS Type of the Allocation
661061da546Spatrick empirical_type<lldb::addr_t> type_ptr;
662061da546Spatrick // Pointer to the RS Context of the Allocation
663061da546Spatrick empirical_type<lldb::addr_t> context;
664061da546Spatrick // Size of the allocation
665061da546Spatrick empirical_type<uint32_t> size;
666061da546Spatrick // Stride between rows of the allocation
667061da546Spatrick empirical_type<uint32_t> stride;
668061da546Spatrick
669061da546Spatrick // Give each allocation an id, so we can reference it in user commands.
AllocationDetailsRenderScriptRuntime::AllocationDetails670061da546Spatrick AllocationDetails() : id(ID++) {}
671061da546Spatrick
ShouldRefreshRenderScriptRuntime::AllocationDetails672061da546Spatrick bool ShouldRefresh() const {
673061da546Spatrick bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
674061da546Spatrick valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
675061da546Spatrick return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
676061da546Spatrick element.ShouldRefresh();
677061da546Spatrick }
678061da546Spatrick };
679061da546Spatrick
GetFallbackStructName()680061da546Spatrick ConstString RenderScriptRuntime::Element::GetFallbackStructName() {
681061da546Spatrick static const ConstString FallbackStructName("struct");
682061da546Spatrick return FallbackStructName;
683061da546Spatrick }
684061da546Spatrick
685061da546Spatrick uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
686061da546Spatrick
687061da546Spatrick const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
688061da546Spatrick "User", "Undefined", "Undefined", "Undefined",
689061da546Spatrick "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7
690061da546Spatrick "L Pixel", "A Pixel", "LA Pixel", "RGB Pixel",
691061da546Spatrick "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
692061da546Spatrick
693061da546Spatrick const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
694061da546Spatrick {"None", "None", "None", "None"},
695061da546Spatrick {"half", "half2", "half3", "half4"},
696061da546Spatrick {"float", "float2", "float3", "float4"},
697061da546Spatrick {"double", "double2", "double3", "double4"},
698061da546Spatrick {"char", "char2", "char3", "char4"},
699061da546Spatrick {"short", "short2", "short3", "short4"},
700061da546Spatrick {"int", "int2", "int3", "int4"},
701061da546Spatrick {"long", "long2", "long3", "long4"},
702061da546Spatrick {"uchar", "uchar2", "uchar3", "uchar4"},
703061da546Spatrick {"ushort", "ushort2", "ushort3", "ushort4"},
704061da546Spatrick {"uint", "uint2", "uint3", "uint4"},
705061da546Spatrick {"ulong", "ulong2", "ulong3", "ulong4"},
706061da546Spatrick {"bool", "bool2", "bool3", "bool4"},
707061da546Spatrick {"packed_565", "packed_565", "packed_565", "packed_565"},
708061da546Spatrick {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
709061da546Spatrick {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
710061da546Spatrick {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
711061da546Spatrick {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
712061da546Spatrick {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
713061da546Spatrick
714061da546Spatrick // Handlers
715061da546Spatrick {"RS Element", "RS Element", "RS Element", "RS Element"},
716061da546Spatrick {"RS Type", "RS Type", "RS Type", "RS Type"},
717061da546Spatrick {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
718061da546Spatrick {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
719061da546Spatrick {"RS Script", "RS Script", "RS Script", "RS Script"},
720061da546Spatrick
721061da546Spatrick // Deprecated
722061da546Spatrick {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
723061da546Spatrick {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
724061da546Spatrick "RS Program Fragment"},
725061da546Spatrick {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
726061da546Spatrick "RS Program Vertex"},
727061da546Spatrick {"RS Program Raster", "RS Program Raster", "RS Program Raster",
728061da546Spatrick "RS Program Raster"},
729061da546Spatrick {"RS Program Store", "RS Program Store", "RS Program Store",
730061da546Spatrick "RS Program Store"},
731061da546Spatrick {"RS Font", "RS Font", "RS Font", "RS Font"}};
732061da546Spatrick
733061da546Spatrick // Used as an index into the RSTypeToFormat array elements
734061da546Spatrick enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
735061da546Spatrick
736061da546Spatrick // { format enum of single element, format enum of element vector, size of
737061da546Spatrick // element}
738061da546Spatrick const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
739061da546Spatrick // RS_TYPE_NONE
740061da546Spatrick {eFormatHex, eFormatHex, 1},
741061da546Spatrick // RS_TYPE_FLOAT_16
742061da546Spatrick {eFormatFloat, eFormatVectorOfFloat16, 2},
743061da546Spatrick // RS_TYPE_FLOAT_32
744061da546Spatrick {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
745061da546Spatrick // RS_TYPE_FLOAT_64
746061da546Spatrick {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
747061da546Spatrick // RS_TYPE_SIGNED_8
748061da546Spatrick {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
749061da546Spatrick // RS_TYPE_SIGNED_16
750061da546Spatrick {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
751061da546Spatrick // RS_TYPE_SIGNED_32
752061da546Spatrick {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
753061da546Spatrick // RS_TYPE_SIGNED_64
754061da546Spatrick {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
755061da546Spatrick // RS_TYPE_UNSIGNED_8
756061da546Spatrick {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
757061da546Spatrick // RS_TYPE_UNSIGNED_16
758061da546Spatrick {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
759061da546Spatrick // RS_TYPE_UNSIGNED_32
760061da546Spatrick {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
761061da546Spatrick // RS_TYPE_UNSIGNED_64
762061da546Spatrick {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
763061da546Spatrick // RS_TYPE_BOOL
764061da546Spatrick {eFormatBoolean, eFormatBoolean, 1},
765061da546Spatrick // RS_TYPE_UNSIGNED_5_6_5
766061da546Spatrick {eFormatHex, eFormatHex, sizeof(uint16_t)},
767061da546Spatrick // RS_TYPE_UNSIGNED_5_5_5_1
768061da546Spatrick {eFormatHex, eFormatHex, sizeof(uint16_t)},
769061da546Spatrick // RS_TYPE_UNSIGNED_4_4_4_4
770061da546Spatrick {eFormatHex, eFormatHex, sizeof(uint16_t)},
771061da546Spatrick // RS_TYPE_MATRIX_4X4
772061da546Spatrick {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
773061da546Spatrick // RS_TYPE_MATRIX_3X3
774061da546Spatrick {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
775061da546Spatrick // RS_TYPE_MATRIX_2X2
776061da546Spatrick {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
777061da546Spatrick
778061da546Spatrick // Static Functions
779061da546Spatrick LanguageRuntime *
CreateInstance(Process * process,lldb::LanguageType language)780061da546Spatrick RenderScriptRuntime::CreateInstance(Process *process,
781061da546Spatrick lldb::LanguageType language) {
782061da546Spatrick
783061da546Spatrick if (language == eLanguageTypeExtRenderScript)
784061da546Spatrick return new RenderScriptRuntime(process);
785061da546Spatrick else
786061da546Spatrick return nullptr;
787061da546Spatrick }
788061da546Spatrick
789061da546Spatrick // Callback with a module to search for matching symbols. We first check that
790061da546Spatrick // the module contains RS kernels. Then look for a symbol which matches our
791061da546Spatrick // kernel name. The breakpoint address is finally set using the address of this
792061da546Spatrick // symbol.
793061da546Spatrick Searcher::CallbackReturn
SearchCallback(SearchFilter & filter,SymbolContext & context,Address *)794061da546Spatrick RSBreakpointResolver::SearchCallback(SearchFilter &filter,
795061da546Spatrick SymbolContext &context, Address *) {
796dda28197Spatrick BreakpointSP breakpoint_sp = GetBreakpoint();
797dda28197Spatrick assert(breakpoint_sp);
798dda28197Spatrick
799061da546Spatrick ModuleSP module = context.module_sp;
800061da546Spatrick
801061da546Spatrick if (!module || !IsRenderScriptScriptModule(module))
802061da546Spatrick return Searcher::eCallbackReturnContinue;
803061da546Spatrick
804061da546Spatrick // Attempt to set a breakpoint on the kernel name symbol within the module
805061da546Spatrick // library. If it's not found, it's likely debug info is unavailable - try to
806061da546Spatrick // set a breakpoint on <name>.expand.
807061da546Spatrick const Symbol *kernel_sym =
808061da546Spatrick module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
809061da546Spatrick if (!kernel_sym) {
810061da546Spatrick std::string kernel_name_expanded(m_kernel_name.AsCString());
811061da546Spatrick kernel_name_expanded.append(".expand");
812061da546Spatrick kernel_sym = module->FindFirstSymbolWithNameAndType(
813061da546Spatrick ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
814061da546Spatrick }
815061da546Spatrick
816061da546Spatrick if (kernel_sym) {
817061da546Spatrick Address bp_addr = kernel_sym->GetAddress();
818061da546Spatrick if (filter.AddressPasses(bp_addr))
819dda28197Spatrick breakpoint_sp->AddLocation(bp_addr);
820061da546Spatrick }
821061da546Spatrick
822061da546Spatrick return Searcher::eCallbackReturnContinue;
823061da546Spatrick }
824061da546Spatrick
825061da546Spatrick Searcher::CallbackReturn
SearchCallback(lldb_private::SearchFilter & filter,lldb_private::SymbolContext & context,Address *)826061da546Spatrick RSReduceBreakpointResolver::SearchCallback(lldb_private::SearchFilter &filter,
827061da546Spatrick lldb_private::SymbolContext &context,
828061da546Spatrick Address *) {
829dda28197Spatrick BreakpointSP breakpoint_sp = GetBreakpoint();
830dda28197Spatrick assert(breakpoint_sp);
831dda28197Spatrick
832061da546Spatrick // We need to have access to the list of reductions currently parsed, as
833061da546Spatrick // reduce names don't actually exist as symbols in a module. They are only
834061da546Spatrick // identifiable by parsing the .rs.info packet, or finding the expand symbol.
835061da546Spatrick // We therefore need access to the list of parsed rs modules to properly
836061da546Spatrick // resolve reduction names.
837*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Breakpoints);
838061da546Spatrick ModuleSP module = context.module_sp;
839061da546Spatrick
840061da546Spatrick if (!module || !IsRenderScriptScriptModule(module))
841061da546Spatrick return Searcher::eCallbackReturnContinue;
842061da546Spatrick
843061da546Spatrick if (!m_rsmodules)
844061da546Spatrick return Searcher::eCallbackReturnContinue;
845061da546Spatrick
846061da546Spatrick for (const auto &module_desc : *m_rsmodules) {
847061da546Spatrick if (module_desc->m_module != module)
848061da546Spatrick continue;
849061da546Spatrick
850061da546Spatrick for (const auto &reduction : module_desc->m_reductions) {
851061da546Spatrick if (reduction.m_reduce_name != m_reduce_name)
852061da546Spatrick continue;
853061da546Spatrick
854061da546Spatrick std::array<std::pair<ConstString, int>, 5> funcs{
855061da546Spatrick {{reduction.m_init_name, eKernelTypeInit},
856061da546Spatrick {reduction.m_accum_name, eKernelTypeAccum},
857061da546Spatrick {reduction.m_comb_name, eKernelTypeComb},
858061da546Spatrick {reduction.m_outc_name, eKernelTypeOutC},
859061da546Spatrick {reduction.m_halter_name, eKernelTypeHalter}}};
860061da546Spatrick
861061da546Spatrick for (const auto &kernel : funcs) {
862061da546Spatrick // Skip constituent functions that don't match our spec
863061da546Spatrick if (!(m_kernel_types & kernel.second))
864061da546Spatrick continue;
865061da546Spatrick
866061da546Spatrick const auto kernel_name = kernel.first;
867061da546Spatrick const auto symbol = module->FindFirstSymbolWithNameAndType(
868061da546Spatrick kernel_name, eSymbolTypeCode);
869061da546Spatrick if (!symbol)
870061da546Spatrick continue;
871061da546Spatrick
872061da546Spatrick auto address = symbol->GetAddress();
873061da546Spatrick if (filter.AddressPasses(address)) {
874061da546Spatrick bool new_bp;
875061da546Spatrick if (!SkipPrologue(module, address)) {
876061da546Spatrick LLDB_LOGF(log, "%s: Error trying to skip prologue", __FUNCTION__);
877061da546Spatrick }
878dda28197Spatrick breakpoint_sp->AddLocation(address, &new_bp);
879061da546Spatrick LLDB_LOGF(log, "%s: %s reduction breakpoint on %s in %s",
880061da546Spatrick __FUNCTION__, new_bp ? "new" : "existing",
881061da546Spatrick kernel_name.GetCString(),
882*f6aab3d8Srobert address.GetModule()->GetFileSpec().GetPath().c_str());
883061da546Spatrick }
884061da546Spatrick }
885061da546Spatrick }
886061da546Spatrick }
887061da546Spatrick return eCallbackReturnContinue;
888061da546Spatrick }
889061da546Spatrick
SearchCallback(SearchFilter & filter,SymbolContext & context,Address * addr)890061da546Spatrick Searcher::CallbackReturn RSScriptGroupBreakpointResolver::SearchCallback(
891061da546Spatrick SearchFilter &filter, SymbolContext &context, Address *addr) {
892061da546Spatrick
893dda28197Spatrick BreakpointSP breakpoint_sp = GetBreakpoint();
894dda28197Spatrick if (!breakpoint_sp)
895061da546Spatrick return eCallbackReturnContinue;
896061da546Spatrick
897*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Breakpoints);
898061da546Spatrick ModuleSP &module = context.module_sp;
899061da546Spatrick
900061da546Spatrick if (!module || !IsRenderScriptScriptModule(module))
901061da546Spatrick return Searcher::eCallbackReturnContinue;
902061da546Spatrick
903061da546Spatrick std::vector<std::string> names;
904dda28197Spatrick Breakpoint& breakpoint = *breakpoint_sp;
905dda28197Spatrick breakpoint.GetNames(names);
906061da546Spatrick if (names.empty())
907061da546Spatrick return eCallbackReturnContinue;
908061da546Spatrick
909061da546Spatrick for (auto &name : names) {
910061da546Spatrick const RSScriptGroupDescriptorSP sg = FindScriptGroup(ConstString(name));
911061da546Spatrick if (!sg) {
912061da546Spatrick LLDB_LOGF(log, "%s: could not find script group for %s", __FUNCTION__,
913061da546Spatrick name.c_str());
914061da546Spatrick continue;
915061da546Spatrick }
916061da546Spatrick
917061da546Spatrick LLDB_LOGF(log, "%s: Found ScriptGroup for %s", __FUNCTION__, name.c_str());
918061da546Spatrick
919061da546Spatrick for (const RSScriptGroupDescriptor::Kernel &k : sg->m_kernels) {
920061da546Spatrick if (log) {
921061da546Spatrick LLDB_LOGF(log, "%s: Adding breakpoint for %s", __FUNCTION__,
922061da546Spatrick k.m_name.AsCString());
923061da546Spatrick LLDB_LOGF(log, "%s: Kernel address 0x%" PRIx64, __FUNCTION__, k.m_addr);
924061da546Spatrick }
925061da546Spatrick
926061da546Spatrick const lldb_private::Symbol *sym =
927061da546Spatrick module->FindFirstSymbolWithNameAndType(k.m_name, eSymbolTypeCode);
928061da546Spatrick if (!sym) {
929061da546Spatrick LLDB_LOGF(log, "%s: Unable to find symbol for %s", __FUNCTION__,
930061da546Spatrick k.m_name.AsCString());
931061da546Spatrick continue;
932061da546Spatrick }
933061da546Spatrick
934061da546Spatrick if (log) {
935061da546Spatrick LLDB_LOGF(log, "%s: Found symbol name is %s", __FUNCTION__,
936061da546Spatrick sym->GetName().AsCString());
937061da546Spatrick }
938061da546Spatrick
939061da546Spatrick auto address = sym->GetAddress();
940061da546Spatrick if (!SkipPrologue(module, address)) {
941061da546Spatrick LLDB_LOGF(log, "%s: Error trying to skip prologue", __FUNCTION__);
942061da546Spatrick }
943061da546Spatrick
944061da546Spatrick bool new_bp;
945dda28197Spatrick breakpoint.AddLocation(address, &new_bp);
946061da546Spatrick
947061da546Spatrick LLDB_LOGF(log, "%s: Placed %sbreakpoint on %s", __FUNCTION__,
948061da546Spatrick new_bp ? "new " : "", k.m_name.AsCString());
949061da546Spatrick
950061da546Spatrick // exit after placing the first breakpoint if we do not intend to stop on
951061da546Spatrick // all kernels making up this script group
952061da546Spatrick if (!m_stop_on_all)
953061da546Spatrick break;
954061da546Spatrick }
955061da546Spatrick }
956061da546Spatrick
957061da546Spatrick return eCallbackReturnContinue;
958061da546Spatrick }
959061da546Spatrick
Initialize()960061da546Spatrick void RenderScriptRuntime::Initialize() {
961061da546Spatrick PluginManager::RegisterPlugin(GetPluginNameStatic(),
962061da546Spatrick "RenderScript language support", CreateInstance,
963061da546Spatrick GetCommandObject);
964061da546Spatrick }
965061da546Spatrick
Terminate()966061da546Spatrick void RenderScriptRuntime::Terminate() {
967061da546Spatrick PluginManager::UnregisterPlugin(CreateInstance);
968061da546Spatrick }
969061da546Spatrick
970061da546Spatrick RenderScriptRuntime::ModuleKind
GetModuleKind(const lldb::ModuleSP & module_sp)971061da546Spatrick RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
972061da546Spatrick if (module_sp) {
973061da546Spatrick if (IsRenderScriptScriptModule(module_sp))
974061da546Spatrick return eModuleKindKernelObj;
975061da546Spatrick
976061da546Spatrick // Is this the main RS runtime library
977061da546Spatrick const ConstString rs_lib("libRS.so");
978061da546Spatrick if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
979061da546Spatrick return eModuleKindLibRS;
980061da546Spatrick }
981061da546Spatrick
982061da546Spatrick const ConstString rs_driverlib("libRSDriver.so");
983061da546Spatrick if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
984061da546Spatrick return eModuleKindDriver;
985061da546Spatrick }
986061da546Spatrick
987061da546Spatrick const ConstString rs_cpureflib("libRSCpuRef.so");
988061da546Spatrick if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
989061da546Spatrick return eModuleKindImpl;
990061da546Spatrick }
991061da546Spatrick }
992061da546Spatrick return eModuleKindIgnored;
993061da546Spatrick }
994061da546Spatrick
IsRenderScriptModule(const lldb::ModuleSP & module_sp)995061da546Spatrick bool RenderScriptRuntime::IsRenderScriptModule(
996061da546Spatrick const lldb::ModuleSP &module_sp) {
997061da546Spatrick return GetModuleKind(module_sp) != eModuleKindIgnored;
998061da546Spatrick }
999061da546Spatrick
ModulesDidLoad(const ModuleList & module_list)1000061da546Spatrick void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
1001061da546Spatrick std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1002061da546Spatrick
1003061da546Spatrick size_t num_modules = module_list.GetSize();
1004061da546Spatrick for (size_t i = 0; i < num_modules; i++) {
1005061da546Spatrick auto mod = module_list.GetModuleAtIndex(i);
1006061da546Spatrick if (IsRenderScriptModule(mod)) {
1007061da546Spatrick LoadModule(mod);
1008061da546Spatrick }
1009061da546Spatrick }
1010061da546Spatrick }
1011061da546Spatrick
GetDynamicTypeAndAddress(ValueObject & in_value,lldb::DynamicValueType use_dynamic,TypeAndOrName & class_type_or_name,Address & address,Value::ValueType & value_type)1012061da546Spatrick bool RenderScriptRuntime::GetDynamicTypeAndAddress(
1013061da546Spatrick ValueObject &in_value, lldb::DynamicValueType use_dynamic,
1014061da546Spatrick TypeAndOrName &class_type_or_name, Address &address,
1015061da546Spatrick Value::ValueType &value_type) {
1016061da546Spatrick return false;
1017061da546Spatrick }
1018061da546Spatrick
1019061da546Spatrick TypeAndOrName
FixUpDynamicType(const TypeAndOrName & type_and_or_name,ValueObject & static_value)1020061da546Spatrick RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
1021061da546Spatrick ValueObject &static_value) {
1022061da546Spatrick return type_and_or_name;
1023061da546Spatrick }
1024061da546Spatrick
CouldHaveDynamicValue(ValueObject & in_value)1025061da546Spatrick bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
1026061da546Spatrick return false;
1027061da546Spatrick }
1028061da546Spatrick
1029061da546Spatrick lldb::BreakpointResolverSP
CreateExceptionResolver(const lldb::BreakpointSP & bp,bool catch_bp,bool throw_bp)1030dda28197Spatrick RenderScriptRuntime::CreateExceptionResolver(const lldb::BreakpointSP &bp,
1031dda28197Spatrick bool catch_bp, bool throw_bp) {
1032061da546Spatrick BreakpointResolverSP resolver_sp;
1033061da546Spatrick return resolver_sp;
1034061da546Spatrick }
1035061da546Spatrick
1036061da546Spatrick const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
1037061da546Spatrick {
1038061da546Spatrick // rsdScript
1039061da546Spatrick {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
1040061da546Spatrick "NS0_7ScriptCEPKcS7_PKhjj",
1041061da546Spatrick "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
1042061da546Spatrick "7ScriptCEPKcS7_PKhmj",
1043061da546Spatrick 0, RenderScriptRuntime::eModuleKindDriver,
1044061da546Spatrick &lldb_private::RenderScriptRuntime::CaptureScriptInit},
1045061da546Spatrick {"rsdScriptInvokeForEachMulti",
1046061da546Spatrick "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1047061da546Spatrick "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
1048061da546Spatrick "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1049061da546Spatrick "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
1050061da546Spatrick 0, RenderScriptRuntime::eModuleKindDriver,
1051061da546Spatrick &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
1052061da546Spatrick {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
1053061da546Spatrick "script7ContextEPKNS0_6ScriptEjPvj",
1054061da546Spatrick "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
1055061da546Spatrick "6ScriptEjPvm",
1056061da546Spatrick 0, RenderScriptRuntime::eModuleKindDriver,
1057061da546Spatrick &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
1058061da546Spatrick
1059061da546Spatrick // rsdAllocation
1060061da546Spatrick {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
1061061da546Spatrick "ontextEPNS0_10AllocationEb",
1062061da546Spatrick "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
1063061da546Spatrick "10AllocationEb",
1064061da546Spatrick 0, RenderScriptRuntime::eModuleKindDriver,
1065061da546Spatrick &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
1066061da546Spatrick {"rsdAllocationRead2D",
1067061da546Spatrick "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1068061da546Spatrick "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1069061da546Spatrick "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1070061da546Spatrick "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1071061da546Spatrick 0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1072061da546Spatrick {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1073061da546Spatrick "ript7ContextEPNS0_10AllocationE",
1074061da546Spatrick "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1075061da546Spatrick "10AllocationE",
1076061da546Spatrick 0, RenderScriptRuntime::eModuleKindDriver,
1077061da546Spatrick &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
1078061da546Spatrick
1079061da546Spatrick // renderscript script groups
1080061da546Spatrick {"rsdDebugHintScriptGroup2", "_ZN7android12renderscript21debugHintScrip"
1081061da546Spatrick "tGroup2EPKcjPKPFvPK24RsExpandKernelDriver"
1082061da546Spatrick "InfojjjEj",
1083061da546Spatrick "_ZN7android12renderscript21debugHintScriptGroup2EPKcjPKPFvPK24RsExpan"
1084061da546Spatrick "dKernelDriverInfojjjEj",
1085061da546Spatrick 0, RenderScriptRuntime::eModuleKindImpl,
1086061da546Spatrick &lldb_private::RenderScriptRuntime::CaptureDebugHintScriptGroup2}};
1087061da546Spatrick
1088061da546Spatrick const size_t RenderScriptRuntime::s_runtimeHookCount =
1089061da546Spatrick sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
1090061da546Spatrick
HookCallback(void * baton,StoppointCallbackContext * ctx,lldb::user_id_t break_id,lldb::user_id_t break_loc_id)1091061da546Spatrick bool RenderScriptRuntime::HookCallback(void *baton,
1092061da546Spatrick StoppointCallbackContext *ctx,
1093061da546Spatrick lldb::user_id_t break_id,
1094061da546Spatrick lldb::user_id_t break_loc_id) {
1095061da546Spatrick RuntimeHook *hook = (RuntimeHook *)baton;
1096061da546Spatrick ExecutionContext exe_ctx(ctx->exe_ctx_ref);
1097061da546Spatrick
1098061da546Spatrick RenderScriptRuntime *lang_rt = llvm::cast<RenderScriptRuntime>(
1099061da546Spatrick exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1100061da546Spatrick eLanguageTypeExtRenderScript));
1101061da546Spatrick
1102061da546Spatrick lang_rt->HookCallback(hook, exe_ctx);
1103061da546Spatrick
1104061da546Spatrick return false;
1105061da546Spatrick }
1106061da546Spatrick
HookCallback(RuntimeHook * hook,ExecutionContext & exe_ctx)1107061da546Spatrick void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
1108061da546Spatrick ExecutionContext &exe_ctx) {
1109*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
1110061da546Spatrick
1111061da546Spatrick LLDB_LOGF(log, "%s - '%s'", __FUNCTION__, hook->defn->name);
1112061da546Spatrick
1113061da546Spatrick if (hook->defn->grabber) {
1114061da546Spatrick (this->*(hook->defn->grabber))(hook, exe_ctx);
1115061da546Spatrick }
1116061da546Spatrick }
1117061da546Spatrick
CaptureDebugHintScriptGroup2(RuntimeHook * hook_info,ExecutionContext & context)1118061da546Spatrick void RenderScriptRuntime::CaptureDebugHintScriptGroup2(
1119061da546Spatrick RuntimeHook *hook_info, ExecutionContext &context) {
1120*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
1121061da546Spatrick
1122061da546Spatrick enum {
1123061da546Spatrick eGroupName = 0,
1124061da546Spatrick eGroupNameSize,
1125061da546Spatrick eKernel,
1126061da546Spatrick eKernelCount,
1127061da546Spatrick };
1128061da546Spatrick
1129061da546Spatrick std::array<ArgItem, 4> args{{
1130061da546Spatrick {ArgItem::ePointer, 0}, // const char *groupName
1131061da546Spatrick {ArgItem::eInt32, 0}, // const uint32_t groupNameSize
1132061da546Spatrick {ArgItem::ePointer, 0}, // const ExpandFuncTy *kernel
1133061da546Spatrick {ArgItem::eInt32, 0}, // const uint32_t kernelCount
1134061da546Spatrick }};
1135061da546Spatrick
1136061da546Spatrick if (!GetArgs(context, args.data(), args.size())) {
1137061da546Spatrick LLDB_LOGF(log, "%s - Error while reading the function parameters",
1138061da546Spatrick __FUNCTION__);
1139061da546Spatrick return;
1140061da546Spatrick } else if (log) {
1141061da546Spatrick LLDB_LOGF(log, "%s - groupName : 0x%" PRIx64, __FUNCTION__,
1142061da546Spatrick addr_t(args[eGroupName]));
1143061da546Spatrick LLDB_LOGF(log, "%s - groupNameSize: %" PRIu64, __FUNCTION__,
1144061da546Spatrick uint64_t(args[eGroupNameSize]));
1145061da546Spatrick LLDB_LOGF(log, "%s - kernel : 0x%" PRIx64, __FUNCTION__,
1146061da546Spatrick addr_t(args[eKernel]));
1147061da546Spatrick LLDB_LOGF(log, "%s - kernelCount : %" PRIu64, __FUNCTION__,
1148061da546Spatrick uint64_t(args[eKernelCount]));
1149061da546Spatrick }
1150061da546Spatrick
1151061da546Spatrick // parse script group name
1152061da546Spatrick ConstString group_name;
1153061da546Spatrick {
1154061da546Spatrick Status err;
1155061da546Spatrick const uint64_t len = uint64_t(args[eGroupNameSize]);
1156061da546Spatrick std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]);
1157061da546Spatrick m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err);
1158061da546Spatrick buffer.get()[len] = '\0';
1159061da546Spatrick if (!err.Success()) {
1160061da546Spatrick LLDB_LOGF(log, "Error reading scriptgroup name from target");
1161061da546Spatrick return;
1162061da546Spatrick } else {
1163061da546Spatrick LLDB_LOGF(log, "Extracted scriptgroup name %s", buffer.get());
1164061da546Spatrick }
1165061da546Spatrick // write back the script group name
1166061da546Spatrick group_name.SetCString(buffer.get());
1167061da546Spatrick }
1168061da546Spatrick
1169061da546Spatrick // create or access existing script group
1170061da546Spatrick RSScriptGroupDescriptorSP group;
1171061da546Spatrick {
1172061da546Spatrick // search for existing script group
1173061da546Spatrick for (auto sg : m_scriptGroups) {
1174061da546Spatrick if (sg->m_name == group_name) {
1175061da546Spatrick group = sg;
1176061da546Spatrick break;
1177061da546Spatrick }
1178061da546Spatrick }
1179061da546Spatrick if (!group) {
1180061da546Spatrick group = std::make_shared<RSScriptGroupDescriptor>();
1181061da546Spatrick group->m_name = group_name;
1182061da546Spatrick m_scriptGroups.push_back(group);
1183061da546Spatrick } else {
1184061da546Spatrick // already have this script group
1185061da546Spatrick LLDB_LOGF(log, "Attempt to add duplicate script group %s",
1186061da546Spatrick group_name.AsCString());
1187061da546Spatrick return;
1188061da546Spatrick }
1189061da546Spatrick }
1190061da546Spatrick assert(group);
1191061da546Spatrick
1192061da546Spatrick const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1193061da546Spatrick std::vector<addr_t> kernels;
1194061da546Spatrick // parse kernel addresses in script group
1195061da546Spatrick for (uint64_t i = 0; i < uint64_t(args[eKernelCount]); ++i) {
1196061da546Spatrick RSScriptGroupDescriptor::Kernel kernel;
1197061da546Spatrick // extract script group kernel addresses from the target
1198061da546Spatrick const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size;
1199061da546Spatrick uint64_t kernel_addr = 0;
1200061da546Spatrick Status err;
1201061da546Spatrick size_t read =
1202061da546Spatrick m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err);
1203061da546Spatrick if (!err.Success() || read != target_ptr_size) {
1204061da546Spatrick LLDB_LOGF(log, "Error parsing kernel address %" PRIu64 " in script group",
1205061da546Spatrick i);
1206061da546Spatrick return;
1207061da546Spatrick }
1208061da546Spatrick LLDB_LOGF(log, "Extracted scriptgroup kernel address - 0x%" PRIx64,
1209061da546Spatrick kernel_addr);
1210061da546Spatrick kernel.m_addr = kernel_addr;
1211061da546Spatrick
1212061da546Spatrick // try to resolve the associated kernel name
1213061da546Spatrick if (!ResolveKernelName(kernel.m_addr, kernel.m_name)) {
1214061da546Spatrick LLDB_LOGF(log, "Parsed scriptgroup kernel %" PRIu64 " - 0x%" PRIx64, i,
1215061da546Spatrick kernel_addr);
1216061da546Spatrick return;
1217061da546Spatrick }
1218061da546Spatrick
1219061da546Spatrick // try to find the non '.expand' function
1220061da546Spatrick {
1221061da546Spatrick const llvm::StringRef expand(".expand");
1222061da546Spatrick const llvm::StringRef name_ref = kernel.m_name.GetStringRef();
1223061da546Spatrick if (name_ref.endswith(expand)) {
1224061da546Spatrick const ConstString base_kernel(name_ref.drop_back(expand.size()));
1225061da546Spatrick // verify this function is a valid kernel
1226061da546Spatrick if (IsKnownKernel(base_kernel)) {
1227061da546Spatrick kernel.m_name = base_kernel;
1228061da546Spatrick LLDB_LOGF(log, "%s - found non expand version '%s'", __FUNCTION__,
1229061da546Spatrick base_kernel.GetCString());
1230061da546Spatrick }
1231061da546Spatrick }
1232061da546Spatrick }
1233061da546Spatrick // add to a list of script group kernels we know about
1234061da546Spatrick group->m_kernels.push_back(kernel);
1235061da546Spatrick }
1236061da546Spatrick
1237061da546Spatrick // Resolve any pending scriptgroup breakpoints
1238061da546Spatrick {
1239061da546Spatrick Target &target = m_process->GetTarget();
1240061da546Spatrick const BreakpointList &list = target.GetBreakpointList();
1241061da546Spatrick const size_t num_breakpoints = list.GetSize();
1242061da546Spatrick LLDB_LOGF(log, "Resolving %zu breakpoints", num_breakpoints);
1243061da546Spatrick for (size_t i = 0; i < num_breakpoints; ++i) {
1244061da546Spatrick const BreakpointSP bp = list.GetBreakpointAtIndex(i);
1245061da546Spatrick if (bp) {
1246061da546Spatrick if (bp->MatchesName(group_name.AsCString())) {
1247061da546Spatrick LLDB_LOGF(log, "Found breakpoint with name %s",
1248061da546Spatrick group_name.AsCString());
1249061da546Spatrick bp->ResolveBreakpoint();
1250061da546Spatrick }
1251061da546Spatrick }
1252061da546Spatrick }
1253061da546Spatrick }
1254061da546Spatrick }
1255061da546Spatrick
CaptureScriptInvokeForEachMulti(RuntimeHook * hook,ExecutionContext & exe_ctx)1256061da546Spatrick void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
1257061da546Spatrick RuntimeHook *hook, ExecutionContext &exe_ctx) {
1258*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
1259061da546Spatrick
1260061da546Spatrick enum {
1261061da546Spatrick eRsContext = 0,
1262061da546Spatrick eRsScript,
1263061da546Spatrick eRsSlot,
1264061da546Spatrick eRsAIns,
1265061da546Spatrick eRsInLen,
1266061da546Spatrick eRsAOut,
1267061da546Spatrick eRsUsr,
1268061da546Spatrick eRsUsrLen,
1269061da546Spatrick eRsSc,
1270061da546Spatrick };
1271061da546Spatrick
1272061da546Spatrick std::array<ArgItem, 9> args{{
1273061da546Spatrick ArgItem{ArgItem::ePointer, 0}, // const Context *rsc
1274061da546Spatrick ArgItem{ArgItem::ePointer, 0}, // Script *s
1275061da546Spatrick ArgItem{ArgItem::eInt32, 0}, // uint32_t slot
1276061da546Spatrick ArgItem{ArgItem::ePointer, 0}, // const Allocation **aIns
1277061da546Spatrick ArgItem{ArgItem::eInt32, 0}, // size_t inLen
1278061da546Spatrick ArgItem{ArgItem::ePointer, 0}, // Allocation *aout
1279061da546Spatrick ArgItem{ArgItem::ePointer, 0}, // const void *usr
1280061da546Spatrick ArgItem{ArgItem::eInt32, 0}, // size_t usrLen
1281061da546Spatrick ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall *sc
1282061da546Spatrick }};
1283061da546Spatrick
1284061da546Spatrick bool success = GetArgs(exe_ctx, &args[0], args.size());
1285061da546Spatrick if (!success) {
1286061da546Spatrick LLDB_LOGF(log, "%s - Error while reading the function parameters",
1287061da546Spatrick __FUNCTION__);
1288061da546Spatrick return;
1289061da546Spatrick }
1290061da546Spatrick
1291061da546Spatrick const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1292061da546Spatrick Status err;
1293061da546Spatrick std::vector<uint64_t> allocs;
1294061da546Spatrick
1295061da546Spatrick // traverse allocation list
1296061da546Spatrick for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1297061da546Spatrick // calculate offest to allocation pointer
1298061da546Spatrick const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1299061da546Spatrick
1300061da546Spatrick // Note: due to little endian layout, reading 32bits or 64bits into res
1301061da546Spatrick // will give the correct results.
1302061da546Spatrick uint64_t result = 0;
1303061da546Spatrick size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
1304061da546Spatrick if (read != target_ptr_size || !err.Success()) {
1305061da546Spatrick LLDB_LOGF(log,
1306061da546Spatrick "%s - Error while reading allocation list argument %" PRIu64,
1307061da546Spatrick __FUNCTION__, i);
1308061da546Spatrick } else {
1309061da546Spatrick allocs.push_back(result);
1310061da546Spatrick }
1311061da546Spatrick }
1312061da546Spatrick
1313061da546Spatrick // if there is an output allocation track it
1314061da546Spatrick if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
1315061da546Spatrick allocs.push_back(alloc_out);
1316061da546Spatrick }
1317061da546Spatrick
1318061da546Spatrick // for all allocations we have found
1319061da546Spatrick for (const uint64_t alloc_addr : allocs) {
1320061da546Spatrick AllocationDetails *alloc = LookUpAllocation(alloc_addr);
1321061da546Spatrick if (!alloc)
1322061da546Spatrick alloc = CreateAllocation(alloc_addr);
1323061da546Spatrick
1324061da546Spatrick if (alloc) {
1325061da546Spatrick // save the allocation address
1326061da546Spatrick if (alloc->address.isValid()) {
1327061da546Spatrick // check the allocation address we already have matches
1328061da546Spatrick assert(*alloc->address.get() == alloc_addr);
1329061da546Spatrick } else {
1330061da546Spatrick alloc->address = alloc_addr;
1331061da546Spatrick }
1332061da546Spatrick
1333061da546Spatrick // save the context
1334061da546Spatrick if (log) {
1335061da546Spatrick if (alloc->context.isValid() &&
1336061da546Spatrick *alloc->context.get() != addr_t(args[eRsContext]))
1337061da546Spatrick LLDB_LOGF(log, "%s - Allocation used by multiple contexts",
1338061da546Spatrick __FUNCTION__);
1339061da546Spatrick }
1340061da546Spatrick alloc->context = addr_t(args[eRsContext]);
1341061da546Spatrick }
1342061da546Spatrick }
1343061da546Spatrick
1344061da546Spatrick // make sure we track this script object
1345061da546Spatrick if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1346061da546Spatrick LookUpScript(addr_t(args[eRsScript]), true)) {
1347061da546Spatrick if (log) {
1348061da546Spatrick if (script->context.isValid() &&
1349061da546Spatrick *script->context.get() != addr_t(args[eRsContext]))
1350061da546Spatrick LLDB_LOGF(log, "%s - Script used by multiple contexts", __FUNCTION__);
1351061da546Spatrick }
1352061da546Spatrick script->context = addr_t(args[eRsContext]);
1353061da546Spatrick }
1354061da546Spatrick }
1355061da546Spatrick
CaptureSetGlobalVar(RuntimeHook * hook,ExecutionContext & context)1356061da546Spatrick void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1357061da546Spatrick ExecutionContext &context) {
1358*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
1359061da546Spatrick
1360061da546Spatrick enum {
1361061da546Spatrick eRsContext,
1362061da546Spatrick eRsScript,
1363061da546Spatrick eRsId,
1364061da546Spatrick eRsData,
1365061da546Spatrick eRsLength,
1366061da546Spatrick };
1367061da546Spatrick
1368061da546Spatrick std::array<ArgItem, 5> args{{
1369061da546Spatrick ArgItem{ArgItem::ePointer, 0}, // eRsContext
1370061da546Spatrick ArgItem{ArgItem::ePointer, 0}, // eRsScript
1371061da546Spatrick ArgItem{ArgItem::eInt32, 0}, // eRsId
1372061da546Spatrick ArgItem{ArgItem::ePointer, 0}, // eRsData
1373061da546Spatrick ArgItem{ArgItem::eInt32, 0}, // eRsLength
1374061da546Spatrick }};
1375061da546Spatrick
1376061da546Spatrick bool success = GetArgs(context, &args[0], args.size());
1377061da546Spatrick if (!success) {
1378061da546Spatrick LLDB_LOGF(log, "%s - error reading the function parameters.", __FUNCTION__);
1379061da546Spatrick return;
1380061da546Spatrick }
1381061da546Spatrick
1382061da546Spatrick if (log) {
1383061da546Spatrick LLDB_LOGF(log,
1384061da546Spatrick "%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1385061da546Spatrick ":%" PRIu64 "bytes.",
1386061da546Spatrick __FUNCTION__, uint64_t(args[eRsContext]),
1387061da546Spatrick uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1388061da546Spatrick uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
1389061da546Spatrick
1390061da546Spatrick addr_t script_addr = addr_t(args[eRsScript]);
1391061da546Spatrick if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
1392061da546Spatrick auto rsm = m_scriptMappings[script_addr];
1393061da546Spatrick if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1394061da546Spatrick auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1395061da546Spatrick LLDB_LOGF(log, "%s - Setting of '%s' within '%s' inferred",
1396061da546Spatrick __FUNCTION__, rsg.m_name.AsCString(),
1397061da546Spatrick rsm->m_module->GetFileSpec().GetFilename().AsCString());
1398061da546Spatrick }
1399061da546Spatrick }
1400061da546Spatrick }
1401061da546Spatrick }
1402061da546Spatrick
CaptureAllocationInit(RuntimeHook * hook,ExecutionContext & exe_ctx)1403061da546Spatrick void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
1404061da546Spatrick ExecutionContext &exe_ctx) {
1405*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
1406061da546Spatrick
1407061da546Spatrick enum { eRsContext, eRsAlloc, eRsForceZero };
1408061da546Spatrick
1409061da546Spatrick std::array<ArgItem, 3> args{{
1410061da546Spatrick ArgItem{ArgItem::ePointer, 0}, // eRsContext
1411061da546Spatrick ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1412061da546Spatrick ArgItem{ArgItem::eBool, 0}, // eRsForceZero
1413061da546Spatrick }};
1414061da546Spatrick
1415061da546Spatrick bool success = GetArgs(exe_ctx, &args[0], args.size());
1416061da546Spatrick if (!success) {
1417061da546Spatrick LLDB_LOGF(log, "%s - error while reading the function parameters",
1418061da546Spatrick __FUNCTION__);
1419061da546Spatrick return;
1420061da546Spatrick }
1421061da546Spatrick
1422061da546Spatrick LLDB_LOGF(log, "%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1423061da546Spatrick __FUNCTION__, uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]),
1424061da546Spatrick uint64_t(args[eRsForceZero]));
1425061da546Spatrick
1426061da546Spatrick AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
1427061da546Spatrick if (alloc)
1428061da546Spatrick alloc->context = uint64_t(args[eRsContext]);
1429061da546Spatrick }
1430061da546Spatrick
CaptureAllocationDestroy(RuntimeHook * hook,ExecutionContext & exe_ctx)1431061da546Spatrick void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
1432061da546Spatrick ExecutionContext &exe_ctx) {
1433*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
1434061da546Spatrick
1435061da546Spatrick enum {
1436061da546Spatrick eRsContext,
1437061da546Spatrick eRsAlloc,
1438061da546Spatrick };
1439061da546Spatrick
1440061da546Spatrick std::array<ArgItem, 2> args{{
1441061da546Spatrick ArgItem{ArgItem::ePointer, 0}, // eRsContext
1442061da546Spatrick ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1443061da546Spatrick }};
1444061da546Spatrick
1445061da546Spatrick bool success = GetArgs(exe_ctx, &args[0], args.size());
1446061da546Spatrick if (!success) {
1447061da546Spatrick LLDB_LOGF(log, "%s - error while reading the function parameters.",
1448061da546Spatrick __FUNCTION__);
1449061da546Spatrick return;
1450061da546Spatrick }
1451061da546Spatrick
1452061da546Spatrick LLDB_LOGF(log, "%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1453061da546Spatrick uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1454061da546Spatrick
1455061da546Spatrick for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1456061da546Spatrick auto &allocation_up = *iter; // get the unique pointer
1457061da546Spatrick if (allocation_up->address.isValid() &&
1458061da546Spatrick *allocation_up->address.get() == addr_t(args[eRsAlloc])) {
1459061da546Spatrick m_allocations.erase(iter);
1460061da546Spatrick LLDB_LOGF(log, "%s - deleted allocation entry.", __FUNCTION__);
1461061da546Spatrick return;
1462061da546Spatrick }
1463061da546Spatrick }
1464061da546Spatrick
1465061da546Spatrick LLDB_LOGF(log, "%s - couldn't find destroyed allocation.", __FUNCTION__);
1466061da546Spatrick }
1467061da546Spatrick
CaptureScriptInit(RuntimeHook * hook,ExecutionContext & exe_ctx)1468061da546Spatrick void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
1469061da546Spatrick ExecutionContext &exe_ctx) {
1470*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
1471061da546Spatrick
1472061da546Spatrick Status err;
1473061da546Spatrick Process *process = exe_ctx.GetProcessPtr();
1474061da546Spatrick
1475061da546Spatrick enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
1476061da546Spatrick
1477061da546Spatrick std::array<ArgItem, 4> args{
1478061da546Spatrick {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
1479061da546Spatrick ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
1480061da546Spatrick bool success = GetArgs(exe_ctx, &args[0], args.size());
1481061da546Spatrick if (!success) {
1482061da546Spatrick LLDB_LOGF(log, "%s - error while reading the function parameters.",
1483061da546Spatrick __FUNCTION__);
1484061da546Spatrick return;
1485061da546Spatrick }
1486061da546Spatrick
1487061da546Spatrick std::string res_name;
1488061da546Spatrick process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
1489061da546Spatrick if (err.Fail()) {
1490061da546Spatrick LLDB_LOGF(log, "%s - error reading res_name: %s.", __FUNCTION__,
1491061da546Spatrick err.AsCString());
1492061da546Spatrick }
1493061da546Spatrick
1494061da546Spatrick std::string cache_dir;
1495061da546Spatrick process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
1496061da546Spatrick if (err.Fail()) {
1497061da546Spatrick LLDB_LOGF(log, "%s - error reading cache_dir: %s.", __FUNCTION__,
1498061da546Spatrick err.AsCString());
1499061da546Spatrick }
1500061da546Spatrick
1501061da546Spatrick LLDB_LOGF(log, "%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1502061da546Spatrick __FUNCTION__, uint64_t(args[eRsContext]), uint64_t(args[eRsScript]),
1503061da546Spatrick res_name.c_str(), cache_dir.c_str());
1504061da546Spatrick
1505061da546Spatrick if (res_name.size() > 0) {
1506061da546Spatrick StreamString strm;
1507061da546Spatrick strm.Printf("librs.%s.so", res_name.c_str());
1508061da546Spatrick
1509061da546Spatrick ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1510061da546Spatrick if (script) {
1511061da546Spatrick script->type = ScriptDetails::eScriptC;
1512061da546Spatrick script->cache_dir = cache_dir;
1513061da546Spatrick script->res_name = res_name;
1514dda28197Spatrick script->shared_lib = std::string(strm.GetString());
1515061da546Spatrick script->context = addr_t(args[eRsContext]);
1516061da546Spatrick }
1517061da546Spatrick
1518061da546Spatrick LLDB_LOGF(log,
1519061da546Spatrick "%s - '%s' tagged with context 0x%" PRIx64
1520061da546Spatrick " and script 0x%" PRIx64 ".",
1521061da546Spatrick __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1522061da546Spatrick uint64_t(args[eRsScript]));
1523061da546Spatrick } else if (log) {
1524061da546Spatrick LLDB_LOGF(log, "%s - resource name invalid, Script not tagged.",
1525061da546Spatrick __FUNCTION__);
1526061da546Spatrick }
1527061da546Spatrick }
1528061da546Spatrick
LoadRuntimeHooks(lldb::ModuleSP module,ModuleKind kind)1529061da546Spatrick void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1530061da546Spatrick ModuleKind kind) {
1531*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
1532061da546Spatrick
1533061da546Spatrick if (!module) {
1534061da546Spatrick return;
1535061da546Spatrick }
1536061da546Spatrick
1537061da546Spatrick Target &target = GetProcess()->GetTarget();
1538061da546Spatrick const llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
1539061da546Spatrick
1540061da546Spatrick if (machine != llvm::Triple::ArchType::x86 &&
1541061da546Spatrick machine != llvm::Triple::ArchType::arm &&
1542061da546Spatrick machine != llvm::Triple::ArchType::aarch64 &&
1543061da546Spatrick machine != llvm::Triple::ArchType::mipsel &&
1544061da546Spatrick machine != llvm::Triple::ArchType::mips64el &&
1545061da546Spatrick machine != llvm::Triple::ArchType::x86_64) {
1546061da546Spatrick LLDB_LOGF(log, "%s - unable to hook runtime functions.", __FUNCTION__);
1547061da546Spatrick return;
1548061da546Spatrick }
1549061da546Spatrick
1550061da546Spatrick const uint32_t target_ptr_size =
1551061da546Spatrick target.GetArchitecture().GetAddressByteSize();
1552061da546Spatrick
1553061da546Spatrick std::array<bool, s_runtimeHookCount> hook_placed;
1554061da546Spatrick hook_placed.fill(false);
1555061da546Spatrick
1556061da546Spatrick for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
1557061da546Spatrick const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1558061da546Spatrick if (hook_defn->kind != kind) {
1559061da546Spatrick continue;
1560061da546Spatrick }
1561061da546Spatrick
1562061da546Spatrick const char *symbol_name = (target_ptr_size == 4)
1563061da546Spatrick ? hook_defn->symbol_name_m32
1564061da546Spatrick : hook_defn->symbol_name_m64;
1565061da546Spatrick
1566061da546Spatrick const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1567061da546Spatrick ConstString(symbol_name), eSymbolTypeCode);
1568061da546Spatrick if (!sym) {
1569061da546Spatrick if (log) {
1570061da546Spatrick LLDB_LOGF(log, "%s - symbol '%s' related to the function %s not found",
1571061da546Spatrick __FUNCTION__, symbol_name, hook_defn->name);
1572061da546Spatrick }
1573061da546Spatrick continue;
1574061da546Spatrick }
1575061da546Spatrick
1576061da546Spatrick addr_t addr = sym->GetLoadAddress(&target);
1577061da546Spatrick if (addr == LLDB_INVALID_ADDRESS) {
1578061da546Spatrick LLDB_LOGF(log,
1579061da546Spatrick "%s - unable to resolve the address of hook function '%s' "
1580061da546Spatrick "with symbol '%s'.",
1581061da546Spatrick __FUNCTION__, hook_defn->name, symbol_name);
1582061da546Spatrick continue;
1583061da546Spatrick } else {
1584061da546Spatrick LLDB_LOGF(log, "%s - function %s, address resolved at 0x%" PRIx64,
1585061da546Spatrick __FUNCTION__, hook_defn->name, addr);
1586061da546Spatrick }
1587061da546Spatrick
1588061da546Spatrick RuntimeHookSP hook(new RuntimeHook());
1589061da546Spatrick hook->address = addr;
1590061da546Spatrick hook->defn = hook_defn;
1591061da546Spatrick hook->bp_sp = target.CreateBreakpoint(addr, true, false);
1592061da546Spatrick hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
1593061da546Spatrick m_runtimeHooks[addr] = hook;
1594061da546Spatrick if (log) {
1595061da546Spatrick LLDB_LOGF(log,
1596061da546Spatrick "%s - successfully hooked '%s' in '%s' version %" PRIu64
1597061da546Spatrick " at 0x%" PRIx64 ".",
1598061da546Spatrick __FUNCTION__, hook_defn->name,
1599061da546Spatrick module->GetFileSpec().GetFilename().AsCString(),
1600061da546Spatrick (uint64_t)hook_defn->version, (uint64_t)addr);
1601061da546Spatrick }
1602061da546Spatrick hook_placed[idx] = true;
1603061da546Spatrick }
1604061da546Spatrick
1605061da546Spatrick // log any unhooked function
1606061da546Spatrick if (log) {
1607061da546Spatrick for (size_t i = 0; i < hook_placed.size(); ++i) {
1608061da546Spatrick if (hook_placed[i])
1609061da546Spatrick continue;
1610061da546Spatrick const HookDefn &hook_defn = s_runtimeHookDefns[i];
1611061da546Spatrick if (hook_defn.kind != kind)
1612061da546Spatrick continue;
1613061da546Spatrick LLDB_LOGF(log, "%s - function %s was not hooked", __FUNCTION__,
1614061da546Spatrick hook_defn.name);
1615061da546Spatrick }
1616061da546Spatrick }
1617061da546Spatrick }
1618061da546Spatrick
FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp)1619061da546Spatrick void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
1620061da546Spatrick if (!rsmodule_sp)
1621061da546Spatrick return;
1622061da546Spatrick
1623*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
1624061da546Spatrick
1625061da546Spatrick const ModuleSP module = rsmodule_sp->m_module;
1626061da546Spatrick const FileSpec &file = module->GetPlatformFileSpec();
1627061da546Spatrick
1628061da546Spatrick // Iterate over all of the scripts that we currently know of. Note: We cant
1629061da546Spatrick // push or pop to m_scripts here or it may invalidate rs_script.
1630061da546Spatrick for (const auto &rs_script : m_scripts) {
1631061da546Spatrick // Extract the expected .so file path for this script.
1632061da546Spatrick std::string shared_lib;
1633061da546Spatrick if (!rs_script->shared_lib.get(shared_lib))
1634061da546Spatrick continue;
1635061da546Spatrick
1636061da546Spatrick // Only proceed if the module that has loaded corresponds to this script.
1637061da546Spatrick if (file.GetFilename() != ConstString(shared_lib.c_str()))
1638061da546Spatrick continue;
1639061da546Spatrick
1640061da546Spatrick // Obtain the script address which we use as a key.
1641061da546Spatrick lldb::addr_t script;
1642061da546Spatrick if (!rs_script->script.get(script))
1643061da546Spatrick continue;
1644061da546Spatrick
1645061da546Spatrick // If we have a script mapping for the current script.
1646061da546Spatrick if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
1647061da546Spatrick // if the module we have stored is different to the one we just received.
1648061da546Spatrick if (m_scriptMappings[script] != rsmodule_sp) {
1649061da546Spatrick LLDB_LOGF(
1650061da546Spatrick log,
1651061da546Spatrick "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1652061da546Spatrick __FUNCTION__, (uint64_t)script,
1653061da546Spatrick rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1654061da546Spatrick }
1655061da546Spatrick }
1656061da546Spatrick // We don't have a script mapping for the current script.
1657061da546Spatrick else {
1658061da546Spatrick // Obtain the script resource name.
1659061da546Spatrick std::string res_name;
1660061da546Spatrick if (rs_script->res_name.get(res_name))
1661061da546Spatrick // Set the modules resource name.
1662061da546Spatrick rsmodule_sp->m_resname = res_name;
1663061da546Spatrick // Add Script/Module pair to map.
1664061da546Spatrick m_scriptMappings[script] = rsmodule_sp;
1665061da546Spatrick LLDB_LOGF(log, "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1666061da546Spatrick __FUNCTION__, (uint64_t)script,
1667061da546Spatrick rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1668061da546Spatrick }
1669061da546Spatrick }
1670061da546Spatrick }
1671061da546Spatrick
1672061da546Spatrick // Uses the Target API to evaluate the expression passed as a parameter to the
1673061da546Spatrick // function The result of that expression is returned an unsigned 64 bit int,
1674061da546Spatrick // via the result* parameter. Function returns true on success, and false on
1675061da546Spatrick // failure
EvalRSExpression(const char * expr,StackFrame * frame_ptr,uint64_t * result)1676061da546Spatrick bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1677061da546Spatrick StackFrame *frame_ptr,
1678061da546Spatrick uint64_t *result) {
1679*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
1680061da546Spatrick LLDB_LOGF(log, "%s(%s)", __FUNCTION__, expr);
1681061da546Spatrick
1682061da546Spatrick ValueObjectSP expr_result;
1683061da546Spatrick EvaluateExpressionOptions options;
1684061da546Spatrick options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
1685061da546Spatrick // Perform the actual expression evaluation
1686061da546Spatrick auto &target = GetProcess()->GetTarget();
1687061da546Spatrick target.EvaluateExpression(expr, frame_ptr, expr_result, options);
1688061da546Spatrick
1689061da546Spatrick if (!expr_result) {
1690061da546Spatrick LLDB_LOGF(log, "%s: couldn't evaluate expression.", __FUNCTION__);
1691061da546Spatrick return false;
1692061da546Spatrick }
1693061da546Spatrick
1694061da546Spatrick // The result of the expression is invalid
1695061da546Spatrick if (!expr_result->GetError().Success()) {
1696061da546Spatrick Status err = expr_result->GetError();
1697061da546Spatrick // Expression returned is void, so this is actually a success
1698061da546Spatrick if (err.GetError() == UserExpression::kNoResult) {
1699061da546Spatrick LLDB_LOGF(log, "%s - expression returned void.", __FUNCTION__);
1700061da546Spatrick
1701061da546Spatrick result = nullptr;
1702061da546Spatrick return true;
1703061da546Spatrick }
1704061da546Spatrick
1705061da546Spatrick LLDB_LOGF(log, "%s - error evaluating expression result: %s", __FUNCTION__,
1706061da546Spatrick err.AsCString());
1707061da546Spatrick return false;
1708061da546Spatrick }
1709061da546Spatrick
1710061da546Spatrick bool success = false;
1711061da546Spatrick // We only read the result as an uint32_t.
1712061da546Spatrick *result = expr_result->GetValueAsUnsigned(0, &success);
1713061da546Spatrick
1714061da546Spatrick if (!success) {
1715061da546Spatrick LLDB_LOGF(log, "%s - couldn't convert expression result to uint32_t",
1716061da546Spatrick __FUNCTION__);
1717061da546Spatrick return false;
1718061da546Spatrick }
1719061da546Spatrick
1720061da546Spatrick return true;
1721061da546Spatrick }
1722061da546Spatrick
1723061da546Spatrick namespace {
1724061da546Spatrick // Used to index expression format strings
1725061da546Spatrick enum ExpressionStrings {
1726061da546Spatrick eExprGetOffsetPtr = 0,
1727061da546Spatrick eExprAllocGetType,
1728061da546Spatrick eExprTypeDimX,
1729061da546Spatrick eExprTypeDimY,
1730061da546Spatrick eExprTypeDimZ,
1731061da546Spatrick eExprTypeElemPtr,
1732061da546Spatrick eExprElementType,
1733061da546Spatrick eExprElementKind,
1734061da546Spatrick eExprElementVec,
1735061da546Spatrick eExprElementFieldCount,
1736061da546Spatrick eExprSubelementsId,
1737061da546Spatrick eExprSubelementsName,
1738061da546Spatrick eExprSubelementsArrSize,
1739061da546Spatrick
1740061da546Spatrick _eExprLast // keep at the end, implicit size of the array runtime_expressions
1741061da546Spatrick };
1742061da546Spatrick
1743061da546Spatrick // max length of an expanded expression
1744061da546Spatrick const int jit_max_expr_size = 512;
1745061da546Spatrick
1746061da546Spatrick // Retrieve the string to JIT for the given expression
1747061da546Spatrick #define JIT_TEMPLATE_CONTEXT "void* ctxt = (void*)rsDebugGetContextWrapper(0x%" PRIx64 "); "
JITTemplate(ExpressionStrings e)1748061da546Spatrick const char *JITTemplate(ExpressionStrings e) {
1749061da546Spatrick // Format strings containing the expressions we may need to evaluate.
1750061da546Spatrick static std::array<const char *, _eExprLast> runtime_expressions = {
1751061da546Spatrick {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1752061da546Spatrick "(int*)_"
1753061da546Spatrick "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1754061da546Spatrick "CubemapFace"
1755061da546Spatrick "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)", // eExprGetOffsetPtr
1756061da546Spatrick
1757061da546Spatrick // Type* rsaAllocationGetType(Context*, Allocation*)
1758061da546Spatrick JIT_TEMPLATE_CONTEXT "(void*)rsaAllocationGetType(ctxt, 0x%" PRIx64 ")", // eExprAllocGetType
1759061da546Spatrick
1760061da546Spatrick // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
1761061da546Spatrick // data in the following way mHal.state.dimX; mHal.state.dimY;
1762061da546Spatrick // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement;
1763061da546Spatrick // into typeData Need to specify 32 or 64 bit for uint_t since this
1764061da546Spatrick // differs between devices
1765061da546Spatrick JIT_TEMPLATE_CONTEXT
1766061da546Spatrick "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1767061da546Spatrick ", 0x%" PRIx64 ", data, 6); data[0]", // eExprTypeDimX
1768061da546Spatrick JIT_TEMPLATE_CONTEXT
1769061da546Spatrick "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1770061da546Spatrick ", 0x%" PRIx64 ", data, 6); data[1]", // eExprTypeDimY
1771061da546Spatrick JIT_TEMPLATE_CONTEXT
1772061da546Spatrick "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1773061da546Spatrick ", 0x%" PRIx64 ", data, 6); data[2]", // eExprTypeDimZ
1774061da546Spatrick JIT_TEMPLATE_CONTEXT
1775061da546Spatrick "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1776061da546Spatrick ", 0x%" PRIx64 ", data, 6); data[5]", // eExprTypeElemPtr
1777061da546Spatrick
1778061da546Spatrick // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1779061da546Spatrick // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1780061da546Spatrick // elemData
1781061da546Spatrick JIT_TEMPLATE_CONTEXT
1782061da546Spatrick "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1783061da546Spatrick ", 0x%" PRIx64 ", data, 5); data[0]", // eExprElementType
1784061da546Spatrick JIT_TEMPLATE_CONTEXT
1785061da546Spatrick "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1786061da546Spatrick ", 0x%" PRIx64 ", data, 5); data[1]", // eExprElementKind
1787061da546Spatrick JIT_TEMPLATE_CONTEXT
1788061da546Spatrick "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1789061da546Spatrick ", 0x%" PRIx64 ", data, 5); data[3]", // eExprElementVec
1790061da546Spatrick JIT_TEMPLATE_CONTEXT
1791061da546Spatrick "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1792061da546Spatrick ", 0x%" PRIx64 ", data, 5); data[4]", // eExprElementFieldCount
1793061da546Spatrick
1794061da546Spatrick // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
1795061da546Spatrick // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1796061da546Spatrick // Needed for Allocations of structs to gather details about
1797061da546Spatrick // fields/Subelements Element* of field
1798061da546Spatrick JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1799061da546Spatrick "]; size_t arr_size[%" PRIu32 "];"
1800061da546Spatrick "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1801061da546Spatrick ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]", // eExprSubelementsId
1802061da546Spatrick
1803061da546Spatrick // Name of field
1804061da546Spatrick JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1805061da546Spatrick "]; size_t arr_size[%" PRIu32 "];"
1806061da546Spatrick "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1807061da546Spatrick ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]", // eExprSubelementsName
1808061da546Spatrick
1809061da546Spatrick // Array size of field
1810061da546Spatrick JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1811061da546Spatrick "]; size_t arr_size[%" PRIu32 "];"
1812061da546Spatrick "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1813061da546Spatrick ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}}; // eExprSubelementsArrSize
1814061da546Spatrick
1815061da546Spatrick return runtime_expressions[e];
1816061da546Spatrick }
1817061da546Spatrick } // end of the anonymous namespace
1818061da546Spatrick
1819061da546Spatrick // JITs the RS runtime for the internal data pointer of an allocation. Is
1820061da546Spatrick // passed x,y,z coordinates for the pointer to a specific element. Then sets
1821061da546Spatrick // the data_ptr member in Allocation with the result. Returns true on success,
1822061da546Spatrick // false otherwise
JITDataPointer(AllocationDetails * alloc,StackFrame * frame_ptr,uint32_t x,uint32_t y,uint32_t z)1823061da546Spatrick bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1824061da546Spatrick StackFrame *frame_ptr, uint32_t x,
1825061da546Spatrick uint32_t y, uint32_t z) {
1826*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
1827061da546Spatrick
1828061da546Spatrick if (!alloc->address.isValid()) {
1829061da546Spatrick LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
1830061da546Spatrick return false;
1831061da546Spatrick }
1832061da546Spatrick
1833061da546Spatrick const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
1834061da546Spatrick char expr_buf[jit_max_expr_size];
1835061da546Spatrick
1836061da546Spatrick int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1837061da546Spatrick *alloc->address.get(), x, y, z);
1838061da546Spatrick if (written < 0) {
1839061da546Spatrick LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
1840061da546Spatrick return false;
1841061da546Spatrick } else if (written >= jit_max_expr_size) {
1842061da546Spatrick LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
1843061da546Spatrick return false;
1844061da546Spatrick }
1845061da546Spatrick
1846061da546Spatrick uint64_t result = 0;
1847061da546Spatrick if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1848061da546Spatrick return false;
1849061da546Spatrick
1850061da546Spatrick addr_t data_ptr = static_cast<lldb::addr_t>(result);
1851061da546Spatrick alloc->data_ptr = data_ptr;
1852061da546Spatrick
1853061da546Spatrick return true;
1854061da546Spatrick }
1855061da546Spatrick
1856061da546Spatrick // JITs the RS runtime for the internal pointer to the RS Type of an allocation
1857061da546Spatrick // Then sets the type_ptr member in Allocation with the result. Returns true on
1858061da546Spatrick // success, false otherwise
JITTypePointer(AllocationDetails * alloc,StackFrame * frame_ptr)1859061da546Spatrick bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1860061da546Spatrick StackFrame *frame_ptr) {
1861*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
1862061da546Spatrick
1863061da546Spatrick if (!alloc->address.isValid() || !alloc->context.isValid()) {
1864061da546Spatrick LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
1865061da546Spatrick return false;
1866061da546Spatrick }
1867061da546Spatrick
1868061da546Spatrick const char *fmt_str = JITTemplate(eExprAllocGetType);
1869061da546Spatrick char expr_buf[jit_max_expr_size];
1870061da546Spatrick
1871061da546Spatrick int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1872061da546Spatrick *alloc->context.get(), *alloc->address.get());
1873061da546Spatrick if (written < 0) {
1874061da546Spatrick LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
1875061da546Spatrick return false;
1876061da546Spatrick } else if (written >= jit_max_expr_size) {
1877061da546Spatrick LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
1878061da546Spatrick return false;
1879061da546Spatrick }
1880061da546Spatrick
1881061da546Spatrick uint64_t result = 0;
1882061da546Spatrick if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1883061da546Spatrick return false;
1884061da546Spatrick
1885061da546Spatrick addr_t type_ptr = static_cast<lldb::addr_t>(result);
1886061da546Spatrick alloc->type_ptr = type_ptr;
1887061da546Spatrick
1888061da546Spatrick return true;
1889061da546Spatrick }
1890061da546Spatrick
1891061da546Spatrick // JITs the RS runtime for information about the dimensions and type of an
1892061da546Spatrick // allocation Then sets dimension and element_ptr members in Allocation with
1893061da546Spatrick // the result. Returns true on success, false otherwise
JITTypePacked(AllocationDetails * alloc,StackFrame * frame_ptr)1894061da546Spatrick bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1895061da546Spatrick StackFrame *frame_ptr) {
1896*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
1897061da546Spatrick
1898061da546Spatrick if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
1899061da546Spatrick LLDB_LOGF(log, "%s - Failed to find allocation details.", __FUNCTION__);
1900061da546Spatrick return false;
1901061da546Spatrick }
1902061da546Spatrick
1903061da546Spatrick // Expression is different depending on if device is 32 or 64 bit
1904061da546Spatrick uint32_t target_ptr_size =
1905061da546Spatrick GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
1906061da546Spatrick const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
1907061da546Spatrick
1908061da546Spatrick // We want 4 elements from packed data
1909061da546Spatrick const uint32_t num_exprs = 4;
1910061da546Spatrick static_assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1),
1911061da546Spatrick "Invalid number of expressions");
1912061da546Spatrick
1913061da546Spatrick char expr_bufs[num_exprs][jit_max_expr_size];
1914061da546Spatrick uint64_t results[num_exprs];
1915061da546Spatrick
1916061da546Spatrick for (uint32_t i = 0; i < num_exprs; ++i) {
1917061da546Spatrick const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
1918061da546Spatrick int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str,
1919061da546Spatrick *alloc->context.get(), bits, *alloc->type_ptr.get());
1920061da546Spatrick if (written < 0) {
1921061da546Spatrick LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
1922061da546Spatrick return false;
1923061da546Spatrick } else if (written >= jit_max_expr_size) {
1924061da546Spatrick LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
1925061da546Spatrick return false;
1926061da546Spatrick }
1927061da546Spatrick
1928061da546Spatrick // Perform expression evaluation
1929061da546Spatrick if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
1930061da546Spatrick return false;
1931061da546Spatrick }
1932061da546Spatrick
1933061da546Spatrick // Assign results to allocation members
1934061da546Spatrick AllocationDetails::Dimension dims;
1935061da546Spatrick dims.dim_1 = static_cast<uint32_t>(results[0]);
1936061da546Spatrick dims.dim_2 = static_cast<uint32_t>(results[1]);
1937061da546Spatrick dims.dim_3 = static_cast<uint32_t>(results[2]);
1938061da546Spatrick alloc->dimension = dims;
1939061da546Spatrick
1940061da546Spatrick addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
1941061da546Spatrick alloc->element.element_ptr = element_ptr;
1942061da546Spatrick
1943061da546Spatrick LLDB_LOGF(log,
1944061da546Spatrick "%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
1945061da546Spatrick ") Element*: 0x%" PRIx64 ".",
1946061da546Spatrick __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
1947061da546Spatrick
1948061da546Spatrick return true;
1949061da546Spatrick }
1950061da546Spatrick
1951061da546Spatrick // JITs the RS runtime for information about the Element of an allocation Then
1952061da546Spatrick // sets type, type_vec_size, field_count and type_kind members in Element with
1953061da546Spatrick // the result. Returns true on success, false otherwise
JITElementPacked(Element & elem,const lldb::addr_t context,StackFrame * frame_ptr)1954061da546Spatrick bool RenderScriptRuntime::JITElementPacked(Element &elem,
1955061da546Spatrick const lldb::addr_t context,
1956061da546Spatrick StackFrame *frame_ptr) {
1957*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
1958061da546Spatrick
1959061da546Spatrick if (!elem.element_ptr.isValid()) {
1960061da546Spatrick LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
1961061da546Spatrick return false;
1962061da546Spatrick }
1963061da546Spatrick
1964061da546Spatrick // We want 4 elements from packed data
1965061da546Spatrick const uint32_t num_exprs = 4;
1966061da546Spatrick static_assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1),
1967061da546Spatrick "Invalid number of expressions");
1968061da546Spatrick
1969061da546Spatrick char expr_bufs[num_exprs][jit_max_expr_size];
1970061da546Spatrick uint64_t results[num_exprs];
1971061da546Spatrick
1972061da546Spatrick for (uint32_t i = 0; i < num_exprs; i++) {
1973061da546Spatrick const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
1974061da546Spatrick int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
1975061da546Spatrick *elem.element_ptr.get());
1976061da546Spatrick if (written < 0) {
1977061da546Spatrick LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
1978061da546Spatrick return false;
1979061da546Spatrick } else if (written >= jit_max_expr_size) {
1980061da546Spatrick LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
1981061da546Spatrick return false;
1982061da546Spatrick }
1983061da546Spatrick
1984061da546Spatrick // Perform expression evaluation
1985061da546Spatrick if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
1986061da546Spatrick return false;
1987061da546Spatrick }
1988061da546Spatrick
1989061da546Spatrick // Assign results to allocation members
1990061da546Spatrick elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
1991061da546Spatrick elem.type_kind =
1992061da546Spatrick static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
1993061da546Spatrick elem.type_vec_size = static_cast<uint32_t>(results[2]);
1994061da546Spatrick elem.field_count = static_cast<uint32_t>(results[3]);
1995061da546Spatrick
1996061da546Spatrick LLDB_LOGF(log,
1997061da546Spatrick "%s - data type %" PRIu32 ", pixel type %" PRIu32
1998061da546Spatrick ", vector size %" PRIu32 ", field count %" PRIu32,
1999061da546Spatrick __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
2000061da546Spatrick *elem.type_vec_size.get(), *elem.field_count.get());
2001061da546Spatrick
2002061da546Spatrick // If this Element has subelements then JIT rsaElementGetSubElements() for
2003061da546Spatrick // details about its fields
2004061da546Spatrick return !(*elem.field_count.get() > 0 &&
2005061da546Spatrick !JITSubelements(elem, context, frame_ptr));
2006061da546Spatrick }
2007061da546Spatrick
2008061da546Spatrick // JITs the RS runtime for information about the subelements/fields of a struct
2009061da546Spatrick // allocation This is necessary for infering the struct type so we can pretty
2010061da546Spatrick // print the allocation's contents. Returns true on success, false otherwise
JITSubelements(Element & elem,const lldb::addr_t context,StackFrame * frame_ptr)2011061da546Spatrick bool RenderScriptRuntime::JITSubelements(Element &elem,
2012061da546Spatrick const lldb::addr_t context,
2013061da546Spatrick StackFrame *frame_ptr) {
2014*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
2015061da546Spatrick
2016061da546Spatrick if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
2017061da546Spatrick LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
2018061da546Spatrick return false;
2019061da546Spatrick }
2020061da546Spatrick
2021061da546Spatrick const short num_exprs = 3;
2022061da546Spatrick static_assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1),
2023061da546Spatrick "Invalid number of expressions");
2024061da546Spatrick
2025061da546Spatrick char expr_buffer[jit_max_expr_size];
2026061da546Spatrick uint64_t results;
2027061da546Spatrick
2028061da546Spatrick // Iterate over struct fields.
2029061da546Spatrick const uint32_t field_count = *elem.field_count.get();
2030061da546Spatrick for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
2031061da546Spatrick Element child;
2032061da546Spatrick for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
2033061da546Spatrick const char *fmt_str =
2034061da546Spatrick JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
2035061da546Spatrick int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
2036061da546Spatrick context, field_count, field_count, field_count,
2037061da546Spatrick *elem.element_ptr.get(), field_count, field_index);
2038061da546Spatrick if (written < 0) {
2039061da546Spatrick LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
2040061da546Spatrick return false;
2041061da546Spatrick } else if (written >= jit_max_expr_size) {
2042061da546Spatrick LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
2043061da546Spatrick return false;
2044061da546Spatrick }
2045061da546Spatrick
2046061da546Spatrick // Perform expression evaluation
2047061da546Spatrick if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
2048061da546Spatrick return false;
2049061da546Spatrick
2050061da546Spatrick LLDB_LOGF(log, "%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
2051061da546Spatrick
2052061da546Spatrick switch (expr_index) {
2053061da546Spatrick case 0: // Element* of child
2054061da546Spatrick child.element_ptr = static_cast<addr_t>(results);
2055061da546Spatrick break;
2056061da546Spatrick case 1: // Name of child
2057061da546Spatrick {
2058061da546Spatrick lldb::addr_t address = static_cast<addr_t>(results);
2059061da546Spatrick Status err;
2060061da546Spatrick std::string name;
2061061da546Spatrick GetProcess()->ReadCStringFromMemory(address, name, err);
2062061da546Spatrick if (!err.Fail())
2063061da546Spatrick child.type_name = ConstString(name);
2064061da546Spatrick else {
2065061da546Spatrick LLDB_LOGF(log, "%s - warning: Couldn't read field name.",
2066061da546Spatrick __FUNCTION__);
2067061da546Spatrick }
2068061da546Spatrick break;
2069061da546Spatrick }
2070061da546Spatrick case 2: // Array size of child
2071061da546Spatrick child.array_size = static_cast<uint32_t>(results);
2072061da546Spatrick break;
2073061da546Spatrick }
2074061da546Spatrick }
2075061da546Spatrick
2076061da546Spatrick // We need to recursively JIT each Element field of the struct since
2077061da546Spatrick // structs can be nested inside structs.
2078061da546Spatrick if (!JITElementPacked(child, context, frame_ptr))
2079061da546Spatrick return false;
2080061da546Spatrick elem.children.push_back(child);
2081061da546Spatrick }
2082061da546Spatrick
2083061da546Spatrick // Try to infer the name of the struct type so we can pretty print the
2084061da546Spatrick // allocation contents.
2085061da546Spatrick FindStructTypeName(elem, frame_ptr);
2086061da546Spatrick
2087061da546Spatrick return true;
2088061da546Spatrick }
2089061da546Spatrick
2090061da546Spatrick // JITs the RS runtime for the address of the last element in the allocation.
2091061da546Spatrick // The `elem_size` parameter represents the size of a single element, including
2092061da546Spatrick // padding. Which is needed as an offset from the last element pointer. Using
2093061da546Spatrick // this offset minus the starting address we can calculate the size of the
2094061da546Spatrick // allocation. Returns true on success, false otherwise
JITAllocationSize(AllocationDetails * alloc,StackFrame * frame_ptr)2095061da546Spatrick bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
2096061da546Spatrick StackFrame *frame_ptr) {
2097*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
2098061da546Spatrick
2099061da546Spatrick if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
2100061da546Spatrick !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
2101061da546Spatrick LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
2102061da546Spatrick return false;
2103061da546Spatrick }
2104061da546Spatrick
2105061da546Spatrick // Find dimensions
2106061da546Spatrick uint32_t dim_x = alloc->dimension.get()->dim_1;
2107061da546Spatrick uint32_t dim_y = alloc->dimension.get()->dim_2;
2108061da546Spatrick uint32_t dim_z = alloc->dimension.get()->dim_3;
2109061da546Spatrick
2110061da546Spatrick // Our plan of jitting the last element address doesn't seem to work for
2111061da546Spatrick // struct Allocations` Instead try to infer the size ourselves without any
2112061da546Spatrick // inter element padding.
2113061da546Spatrick if (alloc->element.children.size() > 0) {
2114061da546Spatrick if (dim_x == 0)
2115061da546Spatrick dim_x = 1;
2116061da546Spatrick if (dim_y == 0)
2117061da546Spatrick dim_y = 1;
2118061da546Spatrick if (dim_z == 0)
2119061da546Spatrick dim_z = 1;
2120061da546Spatrick
2121061da546Spatrick alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
2122061da546Spatrick
2123061da546Spatrick LLDB_LOGF(log, "%s - inferred size of struct allocation %" PRIu32 ".",
2124061da546Spatrick __FUNCTION__, *alloc->size.get());
2125061da546Spatrick return true;
2126061da546Spatrick }
2127061da546Spatrick
2128061da546Spatrick const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2129061da546Spatrick char expr_buf[jit_max_expr_size];
2130061da546Spatrick
2131061da546Spatrick // Calculate last element
2132061da546Spatrick dim_x = dim_x == 0 ? 0 : dim_x - 1;
2133061da546Spatrick dim_y = dim_y == 0 ? 0 : dim_y - 1;
2134061da546Spatrick dim_z = dim_z == 0 ? 0 : dim_z - 1;
2135061da546Spatrick
2136061da546Spatrick int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2137061da546Spatrick *alloc->address.get(), dim_x, dim_y, dim_z);
2138061da546Spatrick if (written < 0) {
2139061da546Spatrick LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
2140061da546Spatrick return false;
2141061da546Spatrick } else if (written >= jit_max_expr_size) {
2142061da546Spatrick LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
2143061da546Spatrick return false;
2144061da546Spatrick }
2145061da546Spatrick
2146061da546Spatrick uint64_t result = 0;
2147061da546Spatrick if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2148061da546Spatrick return false;
2149061da546Spatrick
2150061da546Spatrick addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2151061da546Spatrick // Find pointer to last element and add on size of an element
2152061da546Spatrick alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
2153061da546Spatrick *alloc->element.datum_size.get();
2154061da546Spatrick
2155061da546Spatrick return true;
2156061da546Spatrick }
2157061da546Spatrick
2158061da546Spatrick // JITs the RS runtime for information about the stride between rows in the
2159061da546Spatrick // allocation. This is done to detect padding, since allocated memory is
2160061da546Spatrick // 16-byte aligned. Returns true on success, false otherwise
JITAllocationStride(AllocationDetails * alloc,StackFrame * frame_ptr)2161061da546Spatrick bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
2162061da546Spatrick StackFrame *frame_ptr) {
2163*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
2164061da546Spatrick
2165061da546Spatrick if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
2166061da546Spatrick LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
2167061da546Spatrick return false;
2168061da546Spatrick }
2169061da546Spatrick
2170061da546Spatrick const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2171061da546Spatrick char expr_buf[jit_max_expr_size];
2172061da546Spatrick
2173061da546Spatrick int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2174061da546Spatrick *alloc->address.get(), 0, 1, 0);
2175061da546Spatrick if (written < 0) {
2176061da546Spatrick LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
2177061da546Spatrick return false;
2178061da546Spatrick } else if (written >= jit_max_expr_size) {
2179061da546Spatrick LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
2180061da546Spatrick return false;
2181061da546Spatrick }
2182061da546Spatrick
2183061da546Spatrick uint64_t result = 0;
2184061da546Spatrick if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2185061da546Spatrick return false;
2186061da546Spatrick
2187061da546Spatrick addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2188061da546Spatrick alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
2189061da546Spatrick
2190061da546Spatrick return true;
2191061da546Spatrick }
2192061da546Spatrick
2193061da546Spatrick // JIT all the current runtime info regarding an allocation
RefreshAllocation(AllocationDetails * alloc,StackFrame * frame_ptr)2194061da546Spatrick bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2195061da546Spatrick StackFrame *frame_ptr) {
2196061da546Spatrick // GetOffsetPointer()
2197061da546Spatrick if (!JITDataPointer(alloc, frame_ptr))
2198061da546Spatrick return false;
2199061da546Spatrick
2200061da546Spatrick // rsaAllocationGetType()
2201061da546Spatrick if (!JITTypePointer(alloc, frame_ptr))
2202061da546Spatrick return false;
2203061da546Spatrick
2204061da546Spatrick // rsaTypeGetNativeData()
2205061da546Spatrick if (!JITTypePacked(alloc, frame_ptr))
2206061da546Spatrick return false;
2207061da546Spatrick
2208061da546Spatrick // rsaElementGetNativeData()
2209061da546Spatrick if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
2210061da546Spatrick return false;
2211061da546Spatrick
2212061da546Spatrick // Sets the datum_size member in Element
2213061da546Spatrick SetElementSize(alloc->element);
2214061da546Spatrick
2215061da546Spatrick // Use GetOffsetPointer() to infer size of the allocation
2216061da546Spatrick return JITAllocationSize(alloc, frame_ptr);
2217061da546Spatrick }
2218061da546Spatrick
2219be691f3bSpatrick // Function attempts to set the type_name member of the parameterised Element
2220061da546Spatrick // object. This string should be the name of the struct type the Element
2221061da546Spatrick // represents. We need this string for pretty printing the Element to users.
FindStructTypeName(Element & elem,StackFrame * frame_ptr)2222061da546Spatrick void RenderScriptRuntime::FindStructTypeName(Element &elem,
2223061da546Spatrick StackFrame *frame_ptr) {
2224*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
2225061da546Spatrick
2226061da546Spatrick if (!elem.type_name.IsEmpty()) // Name already set
2227061da546Spatrick return;
2228061da546Spatrick else
2229061da546Spatrick elem.type_name = Element::GetFallbackStructName(); // Default type name if
2230061da546Spatrick // we don't succeed
2231061da546Spatrick
2232061da546Spatrick // Find all the global variables from the script rs modules
2233061da546Spatrick VariableList var_list;
2234061da546Spatrick for (auto module_sp : m_rsmodules)
2235061da546Spatrick module_sp->m_module->FindGlobalVariables(
2236061da546Spatrick RegularExpression(llvm::StringRef(".")), UINT32_MAX, var_list);
2237061da546Spatrick
2238061da546Spatrick // Iterate over all the global variables looking for one with a matching type
2239061da546Spatrick // to the Element. We make the assumption a match exists since there needs to
2240061da546Spatrick // be a global variable to reflect the struct type back into java host code.
2241061da546Spatrick for (const VariableSP &var_sp : var_list) {
2242061da546Spatrick if (!var_sp)
2243061da546Spatrick continue;
2244061da546Spatrick
2245061da546Spatrick ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
2246061da546Spatrick if (!valobj_sp)
2247061da546Spatrick continue;
2248061da546Spatrick
2249061da546Spatrick // Find the number of variable fields.
2250061da546Spatrick // If it has no fields, or more fields than our Element, then it can't be
2251061da546Spatrick // the struct we're looking for. Don't check for equality since RS can add
2252061da546Spatrick // extra struct members for padding.
2253061da546Spatrick size_t num_children = valobj_sp->GetNumChildren();
2254061da546Spatrick if (num_children > elem.children.size() || num_children == 0)
2255061da546Spatrick continue;
2256061da546Spatrick
2257061da546Spatrick // Iterate over children looking for members with matching field names. If
2258061da546Spatrick // all the field names match, this is likely the struct we want.
2259061da546Spatrick // TODO: This could be made more robust by also checking children data
2260061da546Spatrick // sizes, or array size
2261061da546Spatrick bool found = true;
2262061da546Spatrick for (size_t i = 0; i < num_children; ++i) {
2263061da546Spatrick ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
2264061da546Spatrick if (!child || (child->GetName() != elem.children[i].type_name)) {
2265061da546Spatrick found = false;
2266061da546Spatrick break;
2267061da546Spatrick }
2268061da546Spatrick }
2269061da546Spatrick
2270061da546Spatrick // RS can add extra struct members for padding in the format
2271061da546Spatrick // '#rs_padding_[0-9]+'
2272061da546Spatrick if (found && num_children < elem.children.size()) {
2273061da546Spatrick const uint32_t size_diff = elem.children.size() - num_children;
2274061da546Spatrick LLDB_LOGF(log, "%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2275061da546Spatrick size_diff);
2276061da546Spatrick
2277061da546Spatrick for (uint32_t i = 0; i < size_diff; ++i) {
2278061da546Spatrick ConstString name = elem.children[num_children + i].type_name;
2279061da546Spatrick if (strcmp(name.AsCString(), "#rs_padding") < 0)
2280061da546Spatrick found = false;
2281061da546Spatrick }
2282061da546Spatrick }
2283061da546Spatrick
2284061da546Spatrick // We've found a global variable with matching type
2285061da546Spatrick if (found) {
2286061da546Spatrick // Dereference since our Element type isn't a pointer.
2287061da546Spatrick if (valobj_sp->IsPointerType()) {
2288061da546Spatrick Status err;
2289061da546Spatrick ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
2290061da546Spatrick if (!err.Fail())
2291061da546Spatrick valobj_sp = deref_valobj;
2292061da546Spatrick }
2293061da546Spatrick
2294061da546Spatrick // Save name of variable in Element.
2295061da546Spatrick elem.type_name = valobj_sp->GetTypeName();
2296061da546Spatrick LLDB_LOGF(log, "%s - element name set to %s", __FUNCTION__,
2297061da546Spatrick elem.type_name.AsCString());
2298061da546Spatrick
2299061da546Spatrick return;
2300061da546Spatrick }
2301061da546Spatrick }
2302061da546Spatrick }
2303061da546Spatrick
2304061da546Spatrick // Function sets the datum_size member of Element. Representing the size of a
2305061da546Spatrick // single instance including padding. Assumes the relevant allocation
2306061da546Spatrick // information has already been jitted.
SetElementSize(Element & elem)2307061da546Spatrick void RenderScriptRuntime::SetElementSize(Element &elem) {
2308*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
2309061da546Spatrick const Element::DataType type = *elem.type.get();
2310061da546Spatrick assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2311061da546Spatrick "Invalid allocation type");
2312061da546Spatrick
2313061da546Spatrick const uint32_t vec_size = *elem.type_vec_size.get();
2314061da546Spatrick uint32_t data_size = 0;
2315061da546Spatrick uint32_t padding = 0;
2316061da546Spatrick
2317061da546Spatrick // Element is of a struct type, calculate size recursively.
2318061da546Spatrick if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2319061da546Spatrick for (Element &child : elem.children) {
2320061da546Spatrick SetElementSize(child);
2321061da546Spatrick const uint32_t array_size =
2322061da546Spatrick child.array_size.isValid() ? *child.array_size.get() : 1;
2323061da546Spatrick data_size += *child.datum_size.get() * array_size;
2324061da546Spatrick }
2325061da546Spatrick }
2326061da546Spatrick // These have been packed already
2327061da546Spatrick else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2328061da546Spatrick type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2329061da546Spatrick type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
2330061da546Spatrick data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2331061da546Spatrick } else if (type < Element::RS_TYPE_ELEMENT) {
2332061da546Spatrick data_size =
2333061da546Spatrick vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
2334061da546Spatrick if (vec_size == 3)
2335061da546Spatrick padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2336061da546Spatrick } else
2337061da546Spatrick data_size =
2338061da546Spatrick GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
2339061da546Spatrick
2340061da546Spatrick elem.padding = padding;
2341061da546Spatrick elem.datum_size = data_size + padding;
2342061da546Spatrick LLDB_LOGF(log, "%s - element size set to %" PRIu32, __FUNCTION__,
2343061da546Spatrick data_size + padding);
2344061da546Spatrick }
2345061da546Spatrick
2346061da546Spatrick // Given an allocation, this function copies the allocation contents from
2347061da546Spatrick // device into a buffer on the heap. Returning a shared pointer to the buffer
2348061da546Spatrick // containing the data.
2349061da546Spatrick std::shared_ptr<uint8_t>
GetAllocationData(AllocationDetails * alloc,StackFrame * frame_ptr)2350061da546Spatrick RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2351061da546Spatrick StackFrame *frame_ptr) {
2352*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
2353061da546Spatrick
2354061da546Spatrick // JIT all the allocation details
2355061da546Spatrick if (alloc->ShouldRefresh()) {
2356061da546Spatrick LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info",
2357061da546Spatrick __FUNCTION__);
2358061da546Spatrick
2359061da546Spatrick if (!RefreshAllocation(alloc, frame_ptr)) {
2360061da546Spatrick LLDB_LOGF(log, "%s - couldn't JIT allocation details", __FUNCTION__);
2361061da546Spatrick return nullptr;
2362061da546Spatrick }
2363061da546Spatrick }
2364061da546Spatrick
2365061da546Spatrick assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2366061da546Spatrick alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2367061da546Spatrick "Allocation information not available");
2368061da546Spatrick
2369061da546Spatrick // Allocate a buffer to copy data into
2370061da546Spatrick const uint32_t size = *alloc->size.get();
2371061da546Spatrick std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2372061da546Spatrick if (!buffer) {
2373061da546Spatrick LLDB_LOGF(log, "%s - couldn't allocate a %" PRIu32 " byte buffer",
2374061da546Spatrick __FUNCTION__, size);
2375061da546Spatrick return nullptr;
2376061da546Spatrick }
2377061da546Spatrick
2378061da546Spatrick // Read the inferior memory
2379061da546Spatrick Status err;
2380061da546Spatrick lldb::addr_t data_ptr = *alloc->data_ptr.get();
2381061da546Spatrick GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
2382061da546Spatrick if (err.Fail()) {
2383061da546Spatrick LLDB_LOGF(log,
2384061da546Spatrick "%s - '%s' Couldn't read %" PRIu32
2385061da546Spatrick " bytes of allocation data from 0x%" PRIx64,
2386061da546Spatrick __FUNCTION__, err.AsCString(), size, data_ptr);
2387061da546Spatrick return nullptr;
2388061da546Spatrick }
2389061da546Spatrick
2390061da546Spatrick return buffer;
2391061da546Spatrick }
2392061da546Spatrick
2393061da546Spatrick // Function copies data from a binary file into an allocation. There is a
2394061da546Spatrick // header at the start of the file, FileHeader, before the data content itself.
2395061da546Spatrick // Information from this header is used to display warnings to the user about
2396061da546Spatrick // incompatibilities
LoadAllocation(Stream & strm,const uint32_t alloc_id,const char * path,StackFrame * frame_ptr)2397061da546Spatrick bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
2398061da546Spatrick const char *path,
2399061da546Spatrick StackFrame *frame_ptr) {
2400*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
2401061da546Spatrick
2402061da546Spatrick // Find allocation with the given id
2403061da546Spatrick AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2404061da546Spatrick if (!alloc)
2405061da546Spatrick return false;
2406061da546Spatrick
2407061da546Spatrick LLDB_LOGF(log, "%s - found allocation 0x%" PRIx64, __FUNCTION__,
2408061da546Spatrick *alloc->address.get());
2409061da546Spatrick
2410061da546Spatrick // JIT all the allocation details
2411061da546Spatrick if (alloc->ShouldRefresh()) {
2412061da546Spatrick LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info.",
2413061da546Spatrick __FUNCTION__);
2414061da546Spatrick
2415061da546Spatrick if (!RefreshAllocation(alloc, frame_ptr)) {
2416061da546Spatrick LLDB_LOGF(log, "%s - couldn't JIT allocation details", __FUNCTION__);
2417061da546Spatrick return false;
2418061da546Spatrick }
2419061da546Spatrick }
2420061da546Spatrick
2421061da546Spatrick assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2422061da546Spatrick alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2423061da546Spatrick alloc->element.datum_size.isValid() &&
2424061da546Spatrick "Allocation information not available");
2425061da546Spatrick
2426061da546Spatrick // Check we can read from file
2427061da546Spatrick FileSpec file(path);
2428061da546Spatrick FileSystem::Instance().Resolve(file);
2429061da546Spatrick if (!FileSystem::Instance().Exists(file)) {
2430061da546Spatrick strm.Printf("Error: File %s does not exist", path);
2431061da546Spatrick strm.EOL();
2432061da546Spatrick return false;
2433061da546Spatrick }
2434061da546Spatrick
2435061da546Spatrick if (!FileSystem::Instance().Readable(file)) {
2436061da546Spatrick strm.Printf("Error: File %s does not have readable permissions", path);
2437061da546Spatrick strm.EOL();
2438061da546Spatrick return false;
2439061da546Spatrick }
2440061da546Spatrick
2441061da546Spatrick // Read file into data buffer
2442061da546Spatrick auto data_sp = FileSystem::Instance().CreateDataBuffer(file.GetPath());
2443061da546Spatrick
2444061da546Spatrick // Cast start of buffer to FileHeader and use pointer to read metadata
2445*f6aab3d8Srobert const void *file_buf = data_sp->GetBytes();
2446061da546Spatrick if (file_buf == nullptr ||
2447061da546Spatrick data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2448061da546Spatrick sizeof(AllocationDetails::ElementHeader))) {
2449061da546Spatrick strm.Printf("Error: File %s does not contain enough data for header", path);
2450061da546Spatrick strm.EOL();
2451061da546Spatrick return false;
2452061da546Spatrick }
2453061da546Spatrick const AllocationDetails::FileHeader *file_header =
2454*f6aab3d8Srobert static_cast<const AllocationDetails::FileHeader *>(file_buf);
2455061da546Spatrick
2456061da546Spatrick // Check file starts with ascii characters "RSAD"
2457061da546Spatrick if (memcmp(file_header->ident, "RSAD", 4)) {
2458061da546Spatrick strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2459061da546Spatrick "dump. Are you sure this is the correct file?");
2460061da546Spatrick strm.EOL();
2461061da546Spatrick return false;
2462061da546Spatrick }
2463061da546Spatrick
2464061da546Spatrick // Look at the type of the root element in the header
2465061da546Spatrick AllocationDetails::ElementHeader root_el_hdr;
2466*f6aab3d8Srobert memcpy(&root_el_hdr,
2467*f6aab3d8Srobert static_cast<const uint8_t *>(file_buf) +
2468061da546Spatrick sizeof(AllocationDetails::FileHeader),
2469061da546Spatrick sizeof(AllocationDetails::ElementHeader));
2470061da546Spatrick
2471061da546Spatrick LLDB_LOGF(log, "%s - header type %" PRIu32 ", element size %" PRIu32,
2472061da546Spatrick __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
2473061da546Spatrick
2474061da546Spatrick // Check if the target allocation and file both have the same number of bytes
2475061da546Spatrick // for an Element
2476061da546Spatrick if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2477061da546Spatrick strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2478061da546Spatrick " bytes, allocation %" PRIu32 " bytes",
2479061da546Spatrick root_el_hdr.element_size, *alloc->element.datum_size.get());
2480061da546Spatrick strm.EOL();
2481061da546Spatrick }
2482061da546Spatrick
2483061da546Spatrick // Check if the target allocation and file both have the same type
2484061da546Spatrick const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
2485061da546Spatrick const uint32_t file_type = root_el_hdr.type;
2486061da546Spatrick
2487061da546Spatrick if (file_type > Element::RS_TYPE_FONT) {
2488061da546Spatrick strm.Printf("Warning: File has unknown allocation type");
2489061da546Spatrick strm.EOL();
2490061da546Spatrick } else if (alloc_type != file_type) {
2491061da546Spatrick // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2492061da546Spatrick // array
2493061da546Spatrick uint32_t target_type_name_idx = alloc_type;
2494061da546Spatrick uint32_t head_type_name_idx = file_type;
2495061da546Spatrick if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2496061da546Spatrick alloc_type <= Element::RS_TYPE_FONT)
2497061da546Spatrick target_type_name_idx = static_cast<Element::DataType>(
2498061da546Spatrick (alloc_type - Element::RS_TYPE_ELEMENT) +
2499061da546Spatrick Element::RS_TYPE_MATRIX_2X2 + 1);
2500061da546Spatrick
2501061da546Spatrick if (file_type >= Element::RS_TYPE_ELEMENT &&
2502061da546Spatrick file_type <= Element::RS_TYPE_FONT)
2503061da546Spatrick head_type_name_idx = static_cast<Element::DataType>(
2504061da546Spatrick (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2505061da546Spatrick 1);
2506061da546Spatrick
2507061da546Spatrick const char *head_type_name =
2508061da546Spatrick AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
2509061da546Spatrick const char *target_type_name =
2510061da546Spatrick AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
2511061da546Spatrick
2512061da546Spatrick strm.Printf(
2513061da546Spatrick "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
2514061da546Spatrick head_type_name, target_type_name);
2515061da546Spatrick strm.EOL();
2516061da546Spatrick }
2517061da546Spatrick
2518061da546Spatrick // Advance buffer past header
2519*f6aab3d8Srobert file_buf = static_cast<const uint8_t *>(file_buf) + file_header->hdr_size;
2520061da546Spatrick
2521061da546Spatrick // Calculate size of allocation data in file
2522061da546Spatrick size_t size = data_sp->GetByteSize() - file_header->hdr_size;
2523061da546Spatrick
2524061da546Spatrick // Check if the target allocation and file both have the same total data
2525061da546Spatrick // size.
2526061da546Spatrick const uint32_t alloc_size = *alloc->size.get();
2527061da546Spatrick if (alloc_size != size) {
2528061da546Spatrick strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2529061da546Spatrick " bytes, allocation 0x%" PRIx32 " bytes",
2530061da546Spatrick (uint64_t)size, alloc_size);
2531061da546Spatrick strm.EOL();
2532061da546Spatrick // Set length to copy to minimum
2533061da546Spatrick size = alloc_size < size ? alloc_size : size;
2534061da546Spatrick }
2535061da546Spatrick
2536061da546Spatrick // Copy file data from our buffer into the target allocation.
2537061da546Spatrick lldb::addr_t alloc_data = *alloc->data_ptr.get();
2538061da546Spatrick Status err;
2539061da546Spatrick size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
2540061da546Spatrick if (!err.Success() || written != size) {
2541061da546Spatrick strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
2542061da546Spatrick strm.EOL();
2543061da546Spatrick return false;
2544061da546Spatrick }
2545061da546Spatrick
2546061da546Spatrick strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2547061da546Spatrick alloc->id);
2548061da546Spatrick strm.EOL();
2549061da546Spatrick
2550061da546Spatrick return true;
2551061da546Spatrick }
2552061da546Spatrick
2553061da546Spatrick // Function takes as parameters a byte buffer, which will eventually be written
2554061da546Spatrick // to file as the element header, an offset into that buffer, and an Element
2555061da546Spatrick // that will be saved into the buffer at the parametrised offset. Return value
2556061da546Spatrick // is the new offset after writing the element into the buffer. Elements are
2557061da546Spatrick // saved to the file as the ElementHeader struct followed by offsets to the
2558061da546Spatrick // structs of all the element's children.
PopulateElementHeaders(const std::shared_ptr<uint8_t> header_buffer,size_t offset,const Element & elem)2559061da546Spatrick size_t RenderScriptRuntime::PopulateElementHeaders(
2560061da546Spatrick const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2561061da546Spatrick const Element &elem) {
2562061da546Spatrick // File struct for an element header with all the relevant details copied
2563061da546Spatrick // from elem. We assume members are valid already.
2564061da546Spatrick AllocationDetails::ElementHeader elem_header;
2565061da546Spatrick elem_header.type = *elem.type.get();
2566061da546Spatrick elem_header.kind = *elem.type_kind.get();
2567061da546Spatrick elem_header.element_size = *elem.datum_size.get();
2568061da546Spatrick elem_header.vector_size = *elem.type_vec_size.get();
2569061da546Spatrick elem_header.array_size =
2570061da546Spatrick elem.array_size.isValid() ? *elem.array_size.get() : 0;
2571061da546Spatrick const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
2572061da546Spatrick
2573061da546Spatrick // Copy struct into buffer and advance offset We assume that header_buffer
2574061da546Spatrick // has been checked for nullptr before this method is called
2575061da546Spatrick memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
2576061da546Spatrick offset += elem_header_size;
2577061da546Spatrick
2578061da546Spatrick // Starting offset of child ElementHeader struct
2579061da546Spatrick size_t child_offset =
2580061da546Spatrick offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2581061da546Spatrick for (const RenderScriptRuntime::Element &child : elem.children) {
2582061da546Spatrick // Recursively populate the buffer with the element header structs of
2583061da546Spatrick // children. Then save the offsets where they were set after the parent
2584061da546Spatrick // element header.
2585061da546Spatrick memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
2586061da546Spatrick offset += sizeof(uint32_t);
2587061da546Spatrick
2588061da546Spatrick child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
2589061da546Spatrick }
2590061da546Spatrick
2591061da546Spatrick // Zero indicates no more children
2592061da546Spatrick memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
2593061da546Spatrick
2594061da546Spatrick return child_offset;
2595061da546Spatrick }
2596061da546Spatrick
2597061da546Spatrick // Given an Element object this function returns the total size needed in the
2598061da546Spatrick // file header to store the element's details. Taking into account the size of
2599061da546Spatrick // the element header struct, plus the offsets to all the element's children.
2600061da546Spatrick // Function is recursive so that the size of all ancestors is taken into
2601061da546Spatrick // account.
CalculateElementHeaderSize(const Element & elem)2602061da546Spatrick size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
2603061da546Spatrick // Offsets to children plus zero terminator
2604061da546Spatrick size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
2605061da546Spatrick // Size of header struct with type details
2606061da546Spatrick size += sizeof(AllocationDetails::ElementHeader);
2607061da546Spatrick
2608061da546Spatrick // Calculate recursively for all descendants
2609061da546Spatrick for (const Element &child : elem.children)
2610061da546Spatrick size += CalculateElementHeaderSize(child);
2611061da546Spatrick
2612061da546Spatrick return size;
2613061da546Spatrick }
2614061da546Spatrick
2615061da546Spatrick // Function copies allocation contents into a binary file. This file can then
2616061da546Spatrick // be loaded later into a different allocation. There is a header, FileHeader,
2617061da546Spatrick // before the allocation data containing meta-data.
SaveAllocation(Stream & strm,const uint32_t alloc_id,const char * path,StackFrame * frame_ptr)2618061da546Spatrick bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
2619061da546Spatrick const char *path,
2620061da546Spatrick StackFrame *frame_ptr) {
2621*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
2622061da546Spatrick
2623061da546Spatrick // Find allocation with the given id
2624061da546Spatrick AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2625061da546Spatrick if (!alloc)
2626061da546Spatrick return false;
2627061da546Spatrick
2628061da546Spatrick LLDB_LOGF(log, "%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2629061da546Spatrick *alloc->address.get());
2630061da546Spatrick
2631061da546Spatrick // JIT all the allocation details
2632061da546Spatrick if (alloc->ShouldRefresh()) {
2633061da546Spatrick LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info.",
2634061da546Spatrick __FUNCTION__);
2635061da546Spatrick
2636061da546Spatrick if (!RefreshAllocation(alloc, frame_ptr)) {
2637061da546Spatrick LLDB_LOGF(log, "%s - couldn't JIT allocation details.", __FUNCTION__);
2638061da546Spatrick return false;
2639061da546Spatrick }
2640061da546Spatrick }
2641061da546Spatrick
2642061da546Spatrick assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2643061da546Spatrick alloc->element.type_vec_size.isValid() &&
2644061da546Spatrick alloc->element.datum_size.get() &&
2645061da546Spatrick alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2646061da546Spatrick "Allocation information not available");
2647061da546Spatrick
2648061da546Spatrick // Check we can create writable file
2649061da546Spatrick FileSpec file_spec(path);
2650061da546Spatrick FileSystem::Instance().Resolve(file_spec);
2651061da546Spatrick auto file = FileSystem::Instance().Open(
2652*f6aab3d8Srobert file_spec, File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate |
2653061da546Spatrick File::eOpenOptionTruncate);
2654061da546Spatrick
2655061da546Spatrick if (!file) {
2656061da546Spatrick std::string error = llvm::toString(file.takeError());
2657061da546Spatrick strm.Printf("Error: Failed to open '%s' for writing: %s", path,
2658061da546Spatrick error.c_str());
2659061da546Spatrick strm.EOL();
2660061da546Spatrick return false;
2661061da546Spatrick }
2662061da546Spatrick
2663061da546Spatrick // Read allocation into buffer of heap memory
2664061da546Spatrick const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2665061da546Spatrick if (!buffer) {
2666061da546Spatrick strm.Printf("Error: Couldn't read allocation data into buffer");
2667061da546Spatrick strm.EOL();
2668061da546Spatrick return false;
2669061da546Spatrick }
2670061da546Spatrick
2671061da546Spatrick // Create the file header
2672061da546Spatrick AllocationDetails::FileHeader head;
2673061da546Spatrick memcpy(head.ident, "RSAD", 4);
2674061da546Spatrick head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
2675061da546Spatrick head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
2676061da546Spatrick head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
2677061da546Spatrick
2678061da546Spatrick const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2679061da546Spatrick assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2680061da546Spatrick UINT16_MAX &&
2681061da546Spatrick "Element header too large");
2682061da546Spatrick head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2683061da546Spatrick element_header_size);
2684061da546Spatrick
2685061da546Spatrick // Write the file header
2686061da546Spatrick size_t num_bytes = sizeof(AllocationDetails::FileHeader);
2687061da546Spatrick LLDB_LOGF(log, "%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2688061da546Spatrick (uint64_t)num_bytes);
2689061da546Spatrick
2690061da546Spatrick Status err = file.get()->Write(&head, num_bytes);
2691061da546Spatrick if (!err.Success()) {
2692061da546Spatrick strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2693061da546Spatrick strm.EOL();
2694061da546Spatrick return false;
2695061da546Spatrick }
2696061da546Spatrick
2697061da546Spatrick // Create the headers describing the element type of the allocation.
2698061da546Spatrick std::shared_ptr<uint8_t> element_header_buffer(
2699061da546Spatrick new uint8_t[element_header_size]);
2700061da546Spatrick if (element_header_buffer == nullptr) {
2701061da546Spatrick strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2702061da546Spatrick " bytes on the heap",
2703061da546Spatrick (uint64_t)element_header_size);
2704061da546Spatrick strm.EOL();
2705061da546Spatrick return false;
2706061da546Spatrick }
2707061da546Spatrick
2708061da546Spatrick PopulateElementHeaders(element_header_buffer, 0, alloc->element);
2709061da546Spatrick
2710061da546Spatrick // Write headers for allocation element type to file
2711061da546Spatrick num_bytes = element_header_size;
2712061da546Spatrick LLDB_LOGF(log, "%s - writing element headers, 0x%" PRIx64 " bytes.",
2713061da546Spatrick __FUNCTION__, (uint64_t)num_bytes);
2714061da546Spatrick
2715061da546Spatrick err = file.get()->Write(element_header_buffer.get(), num_bytes);
2716061da546Spatrick if (!err.Success()) {
2717061da546Spatrick strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2718061da546Spatrick strm.EOL();
2719061da546Spatrick return false;
2720061da546Spatrick }
2721061da546Spatrick
2722061da546Spatrick // Write allocation data to file
2723061da546Spatrick num_bytes = static_cast<size_t>(*alloc->size.get());
2724061da546Spatrick LLDB_LOGF(log, "%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2725061da546Spatrick (uint64_t)num_bytes);
2726061da546Spatrick
2727061da546Spatrick err = file.get()->Write(buffer.get(), num_bytes);
2728061da546Spatrick if (!err.Success()) {
2729061da546Spatrick strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2730061da546Spatrick strm.EOL();
2731061da546Spatrick return false;
2732061da546Spatrick }
2733061da546Spatrick
2734061da546Spatrick strm.Printf("Allocation written to file '%s'", path);
2735061da546Spatrick strm.EOL();
2736061da546Spatrick return true;
2737061da546Spatrick }
2738061da546Spatrick
LoadModule(const lldb::ModuleSP & module_sp)2739061da546Spatrick bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
2740*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
2741061da546Spatrick
2742061da546Spatrick if (module_sp) {
2743061da546Spatrick for (const auto &rs_module : m_rsmodules) {
2744061da546Spatrick if (rs_module->m_module == module_sp) {
2745061da546Spatrick // Check if the user has enabled automatically breaking on all RS
2746061da546Spatrick // kernels.
2747061da546Spatrick if (m_breakAllKernels)
2748061da546Spatrick BreakOnModuleKernels(rs_module);
2749061da546Spatrick
2750061da546Spatrick return false;
2751061da546Spatrick }
2752061da546Spatrick }
2753061da546Spatrick bool module_loaded = false;
2754061da546Spatrick switch (GetModuleKind(module_sp)) {
2755061da546Spatrick case eModuleKindKernelObj: {
2756061da546Spatrick RSModuleDescriptorSP module_desc;
2757061da546Spatrick module_desc = std::make_shared<RSModuleDescriptor>(module_sp);
2758061da546Spatrick if (module_desc->ParseRSInfo()) {
2759061da546Spatrick m_rsmodules.push_back(module_desc);
2760061da546Spatrick module_desc->WarnIfVersionMismatch(GetProcess()
2761061da546Spatrick ->GetTarget()
2762061da546Spatrick .GetDebugger()
2763061da546Spatrick .GetAsyncOutputStream()
2764061da546Spatrick .get());
2765061da546Spatrick module_loaded = true;
2766061da546Spatrick }
2767061da546Spatrick if (module_loaded) {
2768061da546Spatrick FixupScriptDetails(module_desc);
2769061da546Spatrick }
2770061da546Spatrick break;
2771061da546Spatrick }
2772061da546Spatrick case eModuleKindDriver: {
2773061da546Spatrick if (!m_libRSDriver) {
2774061da546Spatrick m_libRSDriver = module_sp;
2775061da546Spatrick LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
2776061da546Spatrick }
2777061da546Spatrick break;
2778061da546Spatrick }
2779061da546Spatrick case eModuleKindImpl: {
2780061da546Spatrick if (!m_libRSCpuRef) {
2781061da546Spatrick m_libRSCpuRef = module_sp;
2782061da546Spatrick LoadRuntimeHooks(m_libRSCpuRef, RenderScriptRuntime::eModuleKindImpl);
2783061da546Spatrick }
2784061da546Spatrick break;
2785061da546Spatrick }
2786061da546Spatrick case eModuleKindLibRS: {
2787061da546Spatrick if (!m_libRS) {
2788061da546Spatrick m_libRS = module_sp;
2789061da546Spatrick static ConstString gDbgPresentStr("gDebuggerPresent");
2790061da546Spatrick const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2791061da546Spatrick gDbgPresentStr, eSymbolTypeData);
2792061da546Spatrick if (debug_present) {
2793061da546Spatrick Status err;
2794061da546Spatrick uint32_t flag = 0x00000001U;
2795061da546Spatrick Target &target = GetProcess()->GetTarget();
2796061da546Spatrick addr_t addr = debug_present->GetLoadAddress(&target);
2797061da546Spatrick GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
2798061da546Spatrick if (err.Success()) {
2799061da546Spatrick LLDB_LOGF(log, "%s - debugger present flag set on debugee.",
2800061da546Spatrick __FUNCTION__);
2801061da546Spatrick
2802061da546Spatrick m_debuggerPresentFlagged = true;
2803061da546Spatrick } else if (log) {
2804061da546Spatrick LLDB_LOGF(log, "%s - error writing debugger present flags '%s' ",
2805061da546Spatrick __FUNCTION__, err.AsCString());
2806061da546Spatrick }
2807061da546Spatrick } else if (log) {
2808061da546Spatrick LLDB_LOGF(
2809061da546Spatrick log,
2810061da546Spatrick "%s - error writing debugger present flags - symbol not found",
2811061da546Spatrick __FUNCTION__);
2812061da546Spatrick }
2813061da546Spatrick }
2814061da546Spatrick break;
2815061da546Spatrick }
2816061da546Spatrick default:
2817061da546Spatrick break;
2818061da546Spatrick }
2819061da546Spatrick if (module_loaded)
2820061da546Spatrick Update();
2821061da546Spatrick return module_loaded;
2822061da546Spatrick }
2823061da546Spatrick return false;
2824061da546Spatrick }
2825061da546Spatrick
Update()2826061da546Spatrick void RenderScriptRuntime::Update() {
2827061da546Spatrick if (m_rsmodules.size() > 0) {
2828061da546Spatrick if (!m_initiated) {
2829061da546Spatrick Initiate();
2830061da546Spatrick }
2831061da546Spatrick }
2832061da546Spatrick }
2833061da546Spatrick
WarnIfVersionMismatch(lldb_private::Stream * s) const2834061da546Spatrick void RSModuleDescriptor::WarnIfVersionMismatch(lldb_private::Stream *s) const {
2835061da546Spatrick if (!s)
2836061da546Spatrick return;
2837061da546Spatrick
2838061da546Spatrick if (m_slang_version.empty() || m_bcc_version.empty()) {
2839061da546Spatrick s->PutCString("WARNING: Unknown bcc or slang (llvm-rs-cc) version; debug "
2840061da546Spatrick "experience may be unreliable");
2841061da546Spatrick s->EOL();
2842061da546Spatrick } else if (m_slang_version != m_bcc_version) {
2843061da546Spatrick s->Printf("WARNING: The debug info emitted by the slang frontend "
2844061da546Spatrick "(llvm-rs-cc) used to build this module (%s) does not match the "
2845061da546Spatrick "version of bcc used to generate the debug information (%s). "
2846061da546Spatrick "This is an unsupported configuration and may result in a poor "
2847061da546Spatrick "debugging experience; proceed with caution",
2848061da546Spatrick m_slang_version.c_str(), m_bcc_version.c_str());
2849061da546Spatrick s->EOL();
2850061da546Spatrick }
2851061da546Spatrick }
2852061da546Spatrick
ParsePragmaCount(llvm::StringRef * lines,size_t n_lines)2853061da546Spatrick bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
2854061da546Spatrick size_t n_lines) {
2855061da546Spatrick // Skip the pragma prototype line
2856061da546Spatrick ++lines;
2857061da546Spatrick for (; n_lines--; ++lines) {
2858061da546Spatrick const auto kv_pair = lines->split(" - ");
2859061da546Spatrick m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
2860061da546Spatrick }
2861061da546Spatrick return true;
2862061da546Spatrick }
2863061da546Spatrick
ParseExportReduceCount(llvm::StringRef * lines,size_t n_lines)2864061da546Spatrick bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
2865061da546Spatrick size_t n_lines) {
2866061da546Spatrick // The list of reduction kernels in the `.rs.info` symbol is of the form
2867061da546Spatrick // "signature - accumulatordatasize - reduction_name - initializer_name -
2868061da546Spatrick // accumulator_name - combiner_name - outconverter_name - halter_name" Where
2869061da546Spatrick // a function is not explicitly named by the user, or is not generated by the
2870061da546Spatrick // compiler, it is named "." so the dash separated list should always be 8
2871061da546Spatrick // items long
2872*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
2873061da546Spatrick // Skip the exportReduceCount line
2874061da546Spatrick ++lines;
2875061da546Spatrick for (; n_lines--; ++lines) {
2876061da546Spatrick llvm::SmallVector<llvm::StringRef, 8> spec;
2877061da546Spatrick lines->split(spec, " - ");
2878061da546Spatrick if (spec.size() != 8) {
2879061da546Spatrick if (spec.size() < 8) {
2880061da546Spatrick if (log)
2881061da546Spatrick log->Error("Error parsing RenderScript reduction spec. wrong number "
2882061da546Spatrick "of fields");
2883061da546Spatrick return false;
2884061da546Spatrick } else if (log)
2885061da546Spatrick log->Warning("Extraneous members in reduction spec: '%s'",
2886061da546Spatrick lines->str().c_str());
2887061da546Spatrick }
2888061da546Spatrick
2889061da546Spatrick const auto sig_s = spec[0];
2890061da546Spatrick uint32_t sig;
2891061da546Spatrick if (sig_s.getAsInteger(10, sig)) {
2892061da546Spatrick if (log)
2893061da546Spatrick log->Error("Error parsing Renderscript reduction spec: invalid kernel "
2894061da546Spatrick "signature: '%s'",
2895061da546Spatrick sig_s.str().c_str());
2896061da546Spatrick return false;
2897061da546Spatrick }
2898061da546Spatrick
2899061da546Spatrick const auto accum_data_size_s = spec[1];
2900061da546Spatrick uint32_t accum_data_size;
2901061da546Spatrick if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
2902061da546Spatrick if (log)
2903061da546Spatrick log->Error("Error parsing Renderscript reduction spec: invalid "
2904061da546Spatrick "accumulator data size %s",
2905061da546Spatrick accum_data_size_s.str().c_str());
2906061da546Spatrick return false;
2907061da546Spatrick }
2908061da546Spatrick
2909061da546Spatrick LLDB_LOGF(log, "Found RenderScript reduction '%s'", spec[2].str().c_str());
2910061da546Spatrick
2911061da546Spatrick m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
2912061da546Spatrick spec[2], spec[3], spec[4],
2913061da546Spatrick spec[5], spec[6], spec[7]));
2914061da546Spatrick }
2915061da546Spatrick return true;
2916061da546Spatrick }
2917061da546Spatrick
ParseVersionInfo(llvm::StringRef * lines,size_t n_lines)2918061da546Spatrick bool RSModuleDescriptor::ParseVersionInfo(llvm::StringRef *lines,
2919061da546Spatrick size_t n_lines) {
2920061da546Spatrick // Skip the versionInfo line
2921061da546Spatrick ++lines;
2922061da546Spatrick for (; n_lines--; ++lines) {
2923061da546Spatrick // We're only interested in bcc and slang versions, and ignore all other
2924061da546Spatrick // versionInfo lines
2925061da546Spatrick const auto kv_pair = lines->split(" - ");
2926061da546Spatrick if (kv_pair.first == "slang")
2927061da546Spatrick m_slang_version = kv_pair.second.str();
2928061da546Spatrick else if (kv_pair.first == "bcc")
2929061da546Spatrick m_bcc_version = kv_pair.second.str();
2930061da546Spatrick }
2931061da546Spatrick return true;
2932061da546Spatrick }
2933061da546Spatrick
ParseExportForeachCount(llvm::StringRef * lines,size_t n_lines)2934061da546Spatrick bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
2935061da546Spatrick size_t n_lines) {
2936061da546Spatrick // Skip the exportForeachCount line
2937061da546Spatrick ++lines;
2938061da546Spatrick for (; n_lines--; ++lines) {
2939061da546Spatrick uint32_t slot;
2940061da546Spatrick // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
2941061da546Spatrick // pair per line
2942061da546Spatrick const auto kv_pair = lines->split(" - ");
2943061da546Spatrick if (kv_pair.first.getAsInteger(10, slot))
2944061da546Spatrick return false;
2945061da546Spatrick m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
2946061da546Spatrick }
2947061da546Spatrick return true;
2948061da546Spatrick }
2949061da546Spatrick
ParseExportVarCount(llvm::StringRef * lines,size_t n_lines)2950061da546Spatrick bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
2951061da546Spatrick size_t n_lines) {
2952061da546Spatrick // Skip the ExportVarCount line
2953061da546Spatrick ++lines;
2954061da546Spatrick for (; n_lines--; ++lines)
2955061da546Spatrick m_globals.push_back(RSGlobalDescriptor(this, *lines));
2956061da546Spatrick return true;
2957061da546Spatrick }
2958061da546Spatrick
2959061da546Spatrick // The .rs.info symbol in renderscript modules contains a string which needs to
2960061da546Spatrick // be parsed. The string is basic and is parsed on a line by line basis.
ParseRSInfo()2961061da546Spatrick bool RSModuleDescriptor::ParseRSInfo() {
2962061da546Spatrick assert(m_module);
2963*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
2964061da546Spatrick const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
2965061da546Spatrick ConstString(".rs.info"), eSymbolTypeData);
2966061da546Spatrick if (!info_sym)
2967061da546Spatrick return false;
2968061da546Spatrick
2969061da546Spatrick const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
2970061da546Spatrick if (addr == LLDB_INVALID_ADDRESS)
2971061da546Spatrick return false;
2972061da546Spatrick
2973061da546Spatrick const addr_t size = info_sym->GetByteSize();
2974061da546Spatrick const FileSpec fs = m_module->GetFileSpec();
2975061da546Spatrick
2976061da546Spatrick auto buffer =
2977061da546Spatrick FileSystem::Instance().CreateDataBuffer(fs.GetPath(), size, addr);
2978061da546Spatrick if (!buffer)
2979061da546Spatrick return false;
2980061da546Spatrick
2981061da546Spatrick // split rs.info. contents into lines
2982061da546Spatrick llvm::SmallVector<llvm::StringRef, 128> info_lines;
2983061da546Spatrick {
2984061da546Spatrick const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
2985061da546Spatrick raw_rs_info.split(info_lines, '\n');
2986061da546Spatrick LLDB_LOGF(log, "'.rs.info symbol for '%s':\n%s",
2987*f6aab3d8Srobert m_module->GetFileSpec().GetPath().c_str(),
2988*f6aab3d8Srobert raw_rs_info.str().c_str());
2989061da546Spatrick }
2990061da546Spatrick
2991061da546Spatrick enum {
2992061da546Spatrick eExportVar,
2993061da546Spatrick eExportForEach,
2994061da546Spatrick eExportReduce,
2995061da546Spatrick ePragma,
2996061da546Spatrick eBuildChecksum,
2997061da546Spatrick eObjectSlot,
2998061da546Spatrick eVersionInfo,
2999061da546Spatrick };
3000061da546Spatrick
3001061da546Spatrick const auto rs_info_handler = [](llvm::StringRef name) -> int {
3002061da546Spatrick return llvm::StringSwitch<int>(name)
3003061da546Spatrick // The number of visible global variables in the script
3004061da546Spatrick .Case("exportVarCount", eExportVar)
3005061da546Spatrick // The number of RenderScrip `forEach` kernels __attribute__((kernel))
3006061da546Spatrick .Case("exportForEachCount", eExportForEach)
3007061da546Spatrick // The number of generalreductions: This marked in the script by
3008061da546Spatrick // `#pragma reduce()`
3009061da546Spatrick .Case("exportReduceCount", eExportReduce)
3010061da546Spatrick // Total count of all RenderScript specific `#pragmas` used in the
3011061da546Spatrick // script
3012061da546Spatrick .Case("pragmaCount", ePragma)
3013061da546Spatrick .Case("objectSlotCount", eObjectSlot)
3014061da546Spatrick .Case("versionInfo", eVersionInfo)
3015061da546Spatrick .Default(-1);
3016061da546Spatrick };
3017061da546Spatrick
3018061da546Spatrick // parse all text lines of .rs.info
3019061da546Spatrick for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
3020061da546Spatrick const auto kv_pair = line->split(": ");
3021061da546Spatrick const auto key = kv_pair.first;
3022061da546Spatrick const auto val = kv_pair.second.trim();
3023061da546Spatrick
3024061da546Spatrick const auto handler = rs_info_handler(key);
3025061da546Spatrick if (handler == -1)
3026061da546Spatrick continue;
3027061da546Spatrick // getAsInteger returns `true` on an error condition - we're only
3028061da546Spatrick // interested in numeric fields at the moment
3029061da546Spatrick uint64_t n_lines;
3030061da546Spatrick if (val.getAsInteger(10, n_lines)) {
3031061da546Spatrick LLDB_LOGV(log, "Failed to parse non-numeric '.rs.info' section {0}",
3032061da546Spatrick line->str());
3033061da546Spatrick continue;
3034061da546Spatrick }
3035061da546Spatrick if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
3036061da546Spatrick return false;
3037061da546Spatrick
3038061da546Spatrick bool success = false;
3039061da546Spatrick switch (handler) {
3040061da546Spatrick case eExportVar:
3041061da546Spatrick success = ParseExportVarCount(line, n_lines);
3042061da546Spatrick break;
3043061da546Spatrick case eExportForEach:
3044061da546Spatrick success = ParseExportForeachCount(line, n_lines);
3045061da546Spatrick break;
3046061da546Spatrick case eExportReduce:
3047061da546Spatrick success = ParseExportReduceCount(line, n_lines);
3048061da546Spatrick break;
3049061da546Spatrick case ePragma:
3050061da546Spatrick success = ParsePragmaCount(line, n_lines);
3051061da546Spatrick break;
3052061da546Spatrick case eVersionInfo:
3053061da546Spatrick success = ParseVersionInfo(line, n_lines);
3054061da546Spatrick break;
3055061da546Spatrick default: {
3056061da546Spatrick LLDB_LOGF(log, "%s - skipping .rs.info field '%s'", __FUNCTION__,
3057061da546Spatrick line->str().c_str());
3058061da546Spatrick continue;
3059061da546Spatrick }
3060061da546Spatrick }
3061061da546Spatrick if (!success)
3062061da546Spatrick return false;
3063061da546Spatrick line += n_lines;
3064061da546Spatrick }
3065061da546Spatrick return info_lines.size() > 0;
3066061da546Spatrick }
3067061da546Spatrick
DumpStatus(Stream & strm) const3068061da546Spatrick void RenderScriptRuntime::DumpStatus(Stream &strm) const {
3069061da546Spatrick if (m_libRS) {
3070061da546Spatrick strm.Printf("Runtime Library discovered.");
3071061da546Spatrick strm.EOL();
3072061da546Spatrick }
3073061da546Spatrick if (m_libRSDriver) {
3074061da546Spatrick strm.Printf("Runtime Driver discovered.");
3075061da546Spatrick strm.EOL();
3076061da546Spatrick }
3077061da546Spatrick if (m_libRSCpuRef) {
3078061da546Spatrick strm.Printf("CPU Reference Implementation discovered.");
3079061da546Spatrick strm.EOL();
3080061da546Spatrick }
3081061da546Spatrick
3082061da546Spatrick if (m_runtimeHooks.size()) {
3083061da546Spatrick strm.Printf("Runtime functions hooked:");
3084061da546Spatrick strm.EOL();
3085061da546Spatrick for (auto b : m_runtimeHooks) {
3086061da546Spatrick strm.Indent(b.second->defn->name);
3087061da546Spatrick strm.EOL();
3088061da546Spatrick }
3089061da546Spatrick } else {
3090061da546Spatrick strm.Printf("Runtime is not hooked.");
3091061da546Spatrick strm.EOL();
3092061da546Spatrick }
3093061da546Spatrick }
3094061da546Spatrick
DumpContexts(Stream & strm) const3095061da546Spatrick void RenderScriptRuntime::DumpContexts(Stream &strm) const {
3096061da546Spatrick strm.Printf("Inferred RenderScript Contexts:");
3097061da546Spatrick strm.EOL();
3098061da546Spatrick strm.IndentMore();
3099061da546Spatrick
3100061da546Spatrick std::map<addr_t, uint64_t> contextReferences;
3101061da546Spatrick
3102061da546Spatrick // Iterate over all of the currently discovered scripts. Note: We cant push
3103061da546Spatrick // or pop from m_scripts inside this loop or it may invalidate script.
3104061da546Spatrick for (const auto &script : m_scripts) {
3105061da546Spatrick if (!script->context.isValid())
3106061da546Spatrick continue;
3107061da546Spatrick lldb::addr_t context = *script->context;
3108061da546Spatrick
3109061da546Spatrick if (contextReferences.find(context) != contextReferences.end()) {
3110061da546Spatrick contextReferences[context]++;
3111061da546Spatrick } else {
3112061da546Spatrick contextReferences[context] = 1;
3113061da546Spatrick }
3114061da546Spatrick }
3115061da546Spatrick
3116061da546Spatrick for (const auto &cRef : contextReferences) {
3117061da546Spatrick strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
3118061da546Spatrick cRef.first, cRef.second);
3119061da546Spatrick strm.EOL();
3120061da546Spatrick }
3121061da546Spatrick strm.IndentLess();
3122061da546Spatrick }
3123061da546Spatrick
DumpKernels(Stream & strm) const3124061da546Spatrick void RenderScriptRuntime::DumpKernels(Stream &strm) const {
3125061da546Spatrick strm.Printf("RenderScript Kernels:");
3126061da546Spatrick strm.EOL();
3127061da546Spatrick strm.IndentMore();
3128061da546Spatrick for (const auto &module : m_rsmodules) {
3129061da546Spatrick strm.Printf("Resource '%s':", module->m_resname.c_str());
3130061da546Spatrick strm.EOL();
3131061da546Spatrick for (const auto &kernel : module->m_kernels) {
3132dda28197Spatrick strm.Indent(kernel.m_name.GetStringRef());
3133061da546Spatrick strm.EOL();
3134061da546Spatrick }
3135061da546Spatrick }
3136061da546Spatrick strm.IndentLess();
3137061da546Spatrick }
3138061da546Spatrick
3139061da546Spatrick RenderScriptRuntime::AllocationDetails *
FindAllocByID(Stream & strm,const uint32_t alloc_id)3140061da546Spatrick RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
3141061da546Spatrick AllocationDetails *alloc = nullptr;
3142061da546Spatrick
3143061da546Spatrick // See if we can find allocation using id as an index;
3144061da546Spatrick if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
3145061da546Spatrick m_allocations[alloc_id - 1]->id == alloc_id) {
3146061da546Spatrick alloc = m_allocations[alloc_id - 1].get();
3147061da546Spatrick return alloc;
3148061da546Spatrick }
3149061da546Spatrick
3150061da546Spatrick // Fallback to searching
3151061da546Spatrick for (const auto &a : m_allocations) {
3152061da546Spatrick if (a->id == alloc_id) {
3153061da546Spatrick alloc = a.get();
3154061da546Spatrick break;
3155061da546Spatrick }
3156061da546Spatrick }
3157061da546Spatrick
3158061da546Spatrick if (alloc == nullptr) {
3159061da546Spatrick strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
3160061da546Spatrick alloc_id);
3161061da546Spatrick strm.EOL();
3162061da546Spatrick }
3163061da546Spatrick
3164061da546Spatrick return alloc;
3165061da546Spatrick }
3166061da546Spatrick
3167061da546Spatrick // Prints the contents of an allocation to the output stream, which may be a
3168061da546Spatrick // file
DumpAllocation(Stream & strm,StackFrame * frame_ptr,const uint32_t id)3169061da546Spatrick bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
3170061da546Spatrick const uint32_t id) {
3171*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
3172061da546Spatrick
3173061da546Spatrick // Check we can find the desired allocation
3174061da546Spatrick AllocationDetails *alloc = FindAllocByID(strm, id);
3175061da546Spatrick if (!alloc)
3176061da546Spatrick return false; // FindAllocByID() will print error message for us here
3177061da546Spatrick
3178061da546Spatrick LLDB_LOGF(log, "%s - found allocation 0x%" PRIx64, __FUNCTION__,
3179061da546Spatrick *alloc->address.get());
3180061da546Spatrick
3181061da546Spatrick // Check we have information about the allocation, if not calculate it
3182061da546Spatrick if (alloc->ShouldRefresh()) {
3183061da546Spatrick LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info.",
3184061da546Spatrick __FUNCTION__);
3185061da546Spatrick
3186061da546Spatrick // JIT all the allocation information
3187061da546Spatrick if (!RefreshAllocation(alloc, frame_ptr)) {
3188061da546Spatrick strm.Printf("Error: Couldn't JIT allocation details");
3189061da546Spatrick strm.EOL();
3190061da546Spatrick return false;
3191061da546Spatrick }
3192061da546Spatrick }
3193061da546Spatrick
3194061da546Spatrick // Establish format and size of each data element
3195061da546Spatrick const uint32_t vec_size = *alloc->element.type_vec_size.get();
3196061da546Spatrick const Element::DataType type = *alloc->element.type.get();
3197061da546Spatrick
3198061da546Spatrick assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
3199061da546Spatrick "Invalid allocation type");
3200061da546Spatrick
3201061da546Spatrick lldb::Format format;
3202061da546Spatrick if (type >= Element::RS_TYPE_ELEMENT)
3203061da546Spatrick format = eFormatHex;
3204061da546Spatrick else
3205061da546Spatrick format = vec_size == 1
3206061da546Spatrick ? static_cast<lldb::Format>(
3207061da546Spatrick AllocationDetails::RSTypeToFormat[type][eFormatSingle])
3208061da546Spatrick : static_cast<lldb::Format>(
3209061da546Spatrick AllocationDetails::RSTypeToFormat[type][eFormatVector]);
3210061da546Spatrick
3211061da546Spatrick const uint32_t data_size = *alloc->element.datum_size.get();
3212061da546Spatrick
3213061da546Spatrick LLDB_LOGF(log, "%s - element size %" PRIu32 " bytes, including padding",
3214061da546Spatrick __FUNCTION__, data_size);
3215061da546Spatrick
3216061da546Spatrick // Allocate a buffer to copy data into
3217061da546Spatrick std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3218061da546Spatrick if (!buffer) {
3219061da546Spatrick strm.Printf("Error: Couldn't read allocation data");
3220061da546Spatrick strm.EOL();
3221061da546Spatrick return false;
3222061da546Spatrick }
3223061da546Spatrick
3224061da546Spatrick // Calculate stride between rows as there may be padding at end of rows since
3225061da546Spatrick // allocated memory is 16-byte aligned
3226061da546Spatrick if (!alloc->stride.isValid()) {
3227061da546Spatrick if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
3228061da546Spatrick alloc->stride = 0;
3229061da546Spatrick else if (!JITAllocationStride(alloc, frame_ptr)) {
3230061da546Spatrick strm.Printf("Error: Couldn't calculate allocation row stride");
3231061da546Spatrick strm.EOL();
3232061da546Spatrick return false;
3233061da546Spatrick }
3234061da546Spatrick }
3235061da546Spatrick const uint32_t stride = *alloc->stride.get();
3236061da546Spatrick const uint32_t size = *alloc->size.get(); // Size of whole allocation
3237061da546Spatrick const uint32_t padding =
3238061da546Spatrick alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3239061da546Spatrick LLDB_LOGF(log,
3240061da546Spatrick "%s - stride %" PRIu32 " bytes, size %" PRIu32
3241061da546Spatrick " bytes, padding %" PRIu32,
3242061da546Spatrick __FUNCTION__, stride, size, padding);
3243061da546Spatrick
3244061da546Spatrick // Find dimensions used to index loops, so need to be non-zero
3245061da546Spatrick uint32_t dim_x = alloc->dimension.get()->dim_1;
3246061da546Spatrick dim_x = dim_x == 0 ? 1 : dim_x;
3247061da546Spatrick
3248061da546Spatrick uint32_t dim_y = alloc->dimension.get()->dim_2;
3249061da546Spatrick dim_y = dim_y == 0 ? 1 : dim_y;
3250061da546Spatrick
3251061da546Spatrick uint32_t dim_z = alloc->dimension.get()->dim_3;
3252061da546Spatrick dim_z = dim_z == 0 ? 1 : dim_z;
3253061da546Spatrick
3254061da546Spatrick // Use data extractor to format output
3255061da546Spatrick const uint32_t target_ptr_size =
3256061da546Spatrick GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3257061da546Spatrick DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
3258061da546Spatrick target_ptr_size);
3259061da546Spatrick
3260061da546Spatrick uint32_t offset = 0; // Offset in buffer to next element to be printed
3261061da546Spatrick uint32_t prev_row = 0; // Offset to the start of the previous row
3262061da546Spatrick
3263061da546Spatrick // Iterate over allocation dimensions, printing results to user
3264061da546Spatrick strm.Printf("Data (X, Y, Z):");
3265061da546Spatrick for (uint32_t z = 0; z < dim_z; ++z) {
3266061da546Spatrick for (uint32_t y = 0; y < dim_y; ++y) {
3267061da546Spatrick // Use stride to index start of next row.
3268061da546Spatrick if (!(y == 0 && z == 0))
3269061da546Spatrick offset = prev_row + stride;
3270061da546Spatrick prev_row = offset;
3271061da546Spatrick
3272061da546Spatrick // Print each element in the row individually
3273061da546Spatrick for (uint32_t x = 0; x < dim_x; ++x) {
3274061da546Spatrick strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3275061da546Spatrick if ((type == Element::RS_TYPE_NONE) &&
3276061da546Spatrick (alloc->element.children.size() > 0) &&
3277061da546Spatrick (alloc->element.type_name != Element::GetFallbackStructName())) {
3278061da546Spatrick // Here we are dumping an Element of struct type. This is done using
3279061da546Spatrick // expression evaluation with the name of the struct type and pointer
3280061da546Spatrick // to element. Don't print the name of the resulting expression,
3281061da546Spatrick // since this will be '$[0-9]+'
3282061da546Spatrick DumpValueObjectOptions expr_options;
3283061da546Spatrick expr_options.SetHideName(true);
3284061da546Spatrick
3285061da546Spatrick // Setup expression as dereferencing a pointer cast to element
3286061da546Spatrick // address.
3287061da546Spatrick char expr_char_buffer[jit_max_expr_size];
3288061da546Spatrick int written =
3289061da546Spatrick snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3290061da546Spatrick alloc->element.type_name.AsCString(),
3291061da546Spatrick *alloc->data_ptr.get() + offset);
3292061da546Spatrick
3293061da546Spatrick if (written < 0 || written >= jit_max_expr_size) {
3294061da546Spatrick LLDB_LOGF(log, "%s - error in snprintf().", __FUNCTION__);
3295061da546Spatrick continue;
3296061da546Spatrick }
3297061da546Spatrick
3298061da546Spatrick // Evaluate expression
3299061da546Spatrick ValueObjectSP expr_result;
3300061da546Spatrick GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3301061da546Spatrick frame_ptr, expr_result);
3302061da546Spatrick
3303061da546Spatrick // Print the results to our stream.
3304061da546Spatrick expr_result->Dump(strm, expr_options);
3305061da546Spatrick } else {
3306061da546Spatrick DumpDataExtractor(alloc_data, &strm, offset, format,
3307061da546Spatrick data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0,
3308061da546Spatrick 0);
3309061da546Spatrick }
3310061da546Spatrick offset += data_size;
3311061da546Spatrick }
3312061da546Spatrick }
3313061da546Spatrick }
3314061da546Spatrick strm.EOL();
3315061da546Spatrick
3316061da546Spatrick return true;
3317061da546Spatrick }
3318061da546Spatrick
3319061da546Spatrick // Function recalculates all our cached information about allocations by
3320061da546Spatrick // jitting the RS runtime regarding each allocation we know about. Returns true
3321061da546Spatrick // if all allocations could be recomputed, false otherwise.
RecomputeAllAllocations(Stream & strm,StackFrame * frame_ptr)3322061da546Spatrick bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3323061da546Spatrick StackFrame *frame_ptr) {
3324061da546Spatrick bool success = true;
3325061da546Spatrick for (auto &alloc : m_allocations) {
3326061da546Spatrick // JIT current allocation information
3327061da546Spatrick if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3328061da546Spatrick strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3329061da546Spatrick "\n",
3330061da546Spatrick alloc->id);
3331061da546Spatrick success = false;
3332061da546Spatrick }
3333061da546Spatrick }
3334061da546Spatrick
3335061da546Spatrick if (success)
3336061da546Spatrick strm.Printf("All allocations successfully recomputed");
3337061da546Spatrick strm.EOL();
3338061da546Spatrick
3339061da546Spatrick return success;
3340061da546Spatrick }
3341061da546Spatrick
3342061da546Spatrick // Prints information regarding currently loaded allocations. These details are
3343061da546Spatrick // gathered by jitting the runtime, which has as latency. Index parameter
3344061da546Spatrick // specifies a single allocation ID to print, or a zero value to print them all
ListAllocations(Stream & strm,StackFrame * frame_ptr,const uint32_t index)3345061da546Spatrick void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3346061da546Spatrick const uint32_t index) {
3347061da546Spatrick strm.Printf("RenderScript Allocations:");
3348061da546Spatrick strm.EOL();
3349061da546Spatrick strm.IndentMore();
3350061da546Spatrick
3351061da546Spatrick for (auto &alloc : m_allocations) {
3352061da546Spatrick // index will only be zero if we want to print all allocations
3353061da546Spatrick if (index != 0 && index != alloc->id)
3354061da546Spatrick continue;
3355061da546Spatrick
3356061da546Spatrick // JIT current allocation information
3357061da546Spatrick if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3358061da546Spatrick strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3359061da546Spatrick alloc->id);
3360061da546Spatrick strm.EOL();
3361061da546Spatrick continue;
3362061da546Spatrick }
3363061da546Spatrick
3364061da546Spatrick strm.Printf("%" PRIu32 ":", alloc->id);
3365061da546Spatrick strm.EOL();
3366061da546Spatrick strm.IndentMore();
3367061da546Spatrick
3368061da546Spatrick strm.Indent("Context: ");
3369061da546Spatrick if (!alloc->context.isValid())
3370061da546Spatrick strm.Printf("unknown\n");
3371061da546Spatrick else
3372061da546Spatrick strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
3373061da546Spatrick
3374061da546Spatrick strm.Indent("Address: ");
3375061da546Spatrick if (!alloc->address.isValid())
3376061da546Spatrick strm.Printf("unknown\n");
3377061da546Spatrick else
3378061da546Spatrick strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
3379061da546Spatrick
3380061da546Spatrick strm.Indent("Data pointer: ");
3381061da546Spatrick if (!alloc->data_ptr.isValid())
3382061da546Spatrick strm.Printf("unknown\n");
3383061da546Spatrick else
3384061da546Spatrick strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
3385061da546Spatrick
3386061da546Spatrick strm.Indent("Dimensions: ");
3387061da546Spatrick if (!alloc->dimension.isValid())
3388061da546Spatrick strm.Printf("unknown\n");
3389061da546Spatrick else
3390061da546Spatrick strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3391061da546Spatrick alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3392061da546Spatrick alloc->dimension.get()->dim_3);
3393061da546Spatrick
3394061da546Spatrick strm.Indent("Data Type: ");
3395061da546Spatrick if (!alloc->element.type.isValid() ||
3396061da546Spatrick !alloc->element.type_vec_size.isValid())
3397061da546Spatrick strm.Printf("unknown\n");
3398061da546Spatrick else {
3399061da546Spatrick const int vector_size = *alloc->element.type_vec_size.get();
3400061da546Spatrick Element::DataType type = *alloc->element.type.get();
3401061da546Spatrick
3402061da546Spatrick if (!alloc->element.type_name.IsEmpty())
3403061da546Spatrick strm.Printf("%s\n", alloc->element.type_name.AsCString());
3404061da546Spatrick else {
3405061da546Spatrick // Enum value isn't monotonous, so doesn't always index
3406061da546Spatrick // RsDataTypeToString array
3407061da546Spatrick if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3408061da546Spatrick type =
3409061da546Spatrick static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3410061da546Spatrick Element::RS_TYPE_MATRIX_2X2 + 1);
3411061da546Spatrick
3412061da546Spatrick if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3413061da546Spatrick sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3414061da546Spatrick vector_size > 4 || vector_size < 1)
3415061da546Spatrick strm.Printf("invalid type\n");
3416061da546Spatrick else
3417061da546Spatrick strm.Printf(
3418061da546Spatrick "%s\n",
3419061da546Spatrick AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3420061da546Spatrick [vector_size - 1]);
3421061da546Spatrick }
3422061da546Spatrick }
3423061da546Spatrick
3424061da546Spatrick strm.Indent("Data Kind: ");
3425061da546Spatrick if (!alloc->element.type_kind.isValid())
3426061da546Spatrick strm.Printf("unknown\n");
3427061da546Spatrick else {
3428061da546Spatrick const Element::DataKind kind = *alloc->element.type_kind.get();
3429061da546Spatrick if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
3430061da546Spatrick strm.Printf("invalid kind\n");
3431061da546Spatrick else
3432061da546Spatrick strm.Printf(
3433061da546Spatrick "%s\n",
3434061da546Spatrick AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
3435061da546Spatrick }
3436061da546Spatrick
3437061da546Spatrick strm.EOL();
3438061da546Spatrick strm.IndentLess();
3439061da546Spatrick }
3440061da546Spatrick strm.IndentLess();
3441061da546Spatrick }
3442061da546Spatrick
3443061da546Spatrick // Set breakpoints on every kernel found in RS module
BreakOnModuleKernels(const RSModuleDescriptorSP rsmodule_sp)3444061da546Spatrick void RenderScriptRuntime::BreakOnModuleKernels(
3445061da546Spatrick const RSModuleDescriptorSP rsmodule_sp) {
3446061da546Spatrick for (const auto &kernel : rsmodule_sp->m_kernels) {
3447061da546Spatrick // Don't set breakpoint on 'root' kernel
3448061da546Spatrick if (strcmp(kernel.m_name.AsCString(), "root") == 0)
3449061da546Spatrick continue;
3450061da546Spatrick
3451061da546Spatrick CreateKernelBreakpoint(kernel.m_name);
3452061da546Spatrick }
3453061da546Spatrick }
3454061da546Spatrick
3455061da546Spatrick // Method is internally called by the 'kernel breakpoint all' command to enable
3456061da546Spatrick // or disable breaking on all kernels. When do_break is true we want to enable
3457061da546Spatrick // this functionality. When do_break is false we want to disable it.
SetBreakAllKernels(bool do_break,TargetSP target)3458061da546Spatrick void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3459*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3460061da546Spatrick
3461061da546Spatrick InitSearchFilter(target);
3462061da546Spatrick
3463061da546Spatrick // Set breakpoints on all the kernels
3464061da546Spatrick if (do_break && !m_breakAllKernels) {
3465061da546Spatrick m_breakAllKernels = true;
3466061da546Spatrick
3467061da546Spatrick for (const auto &module : m_rsmodules)
3468061da546Spatrick BreakOnModuleKernels(module);
3469061da546Spatrick
3470061da546Spatrick LLDB_LOGF(log,
3471061da546Spatrick "%s(True) - breakpoints set on all currently loaded kernels.",
3472061da546Spatrick __FUNCTION__);
3473061da546Spatrick } else if (!do_break &&
3474061da546Spatrick m_breakAllKernels) // Breakpoints won't be set on any new kernels.
3475061da546Spatrick {
3476061da546Spatrick m_breakAllKernels = false;
3477061da546Spatrick
3478061da546Spatrick LLDB_LOGF(log, "%s(False) - breakpoints no longer automatically set.",
3479061da546Spatrick __FUNCTION__);
3480061da546Spatrick }
3481061da546Spatrick }
3482061da546Spatrick
3483061da546Spatrick // Given the name of a kernel this function creates a breakpoint using our own
3484061da546Spatrick // breakpoint resolver, and returns the Breakpoint shared pointer.
3485061da546Spatrick BreakpointSP
CreateKernelBreakpoint(ConstString name)3486061da546Spatrick RenderScriptRuntime::CreateKernelBreakpoint(ConstString name) {
3487*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3488061da546Spatrick
3489061da546Spatrick if (!m_filtersp) {
3490061da546Spatrick LLDB_LOGF(log, "%s - error, no breakpoint search filter set.",
3491061da546Spatrick __FUNCTION__);
3492061da546Spatrick return nullptr;
3493061da546Spatrick }
3494061da546Spatrick
3495061da546Spatrick BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3496061da546Spatrick Target &target = GetProcess()->GetTarget();
3497061da546Spatrick BreakpointSP bp = target.CreateBreakpoint(
3498061da546Spatrick m_filtersp, resolver_sp, false, false, false);
3499061da546Spatrick
3500061da546Spatrick // Give RS breakpoints a specific name, so the user can manipulate them as a
3501061da546Spatrick // group.
3502061da546Spatrick Status err;
3503061da546Spatrick target.AddNameToBreakpoint(bp, "RenderScriptKernel", err);
3504061da546Spatrick if (err.Fail() && log)
3505061da546Spatrick LLDB_LOGF(log, "%s - error setting break name, '%s'.", __FUNCTION__,
3506061da546Spatrick err.AsCString());
3507061da546Spatrick
3508061da546Spatrick return bp;
3509061da546Spatrick }
3510061da546Spatrick
3511061da546Spatrick BreakpointSP
CreateReductionBreakpoint(ConstString name,int kernel_types)3512061da546Spatrick RenderScriptRuntime::CreateReductionBreakpoint(ConstString name,
3513061da546Spatrick int kernel_types) {
3514*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3515061da546Spatrick
3516061da546Spatrick if (!m_filtersp) {
3517061da546Spatrick LLDB_LOGF(log, "%s - error, no breakpoint search filter set.",
3518061da546Spatrick __FUNCTION__);
3519061da546Spatrick return nullptr;
3520061da546Spatrick }
3521061da546Spatrick
3522061da546Spatrick BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3523061da546Spatrick nullptr, name, &m_rsmodules, kernel_types));
3524061da546Spatrick Target &target = GetProcess()->GetTarget();
3525061da546Spatrick BreakpointSP bp = target.CreateBreakpoint(
3526061da546Spatrick m_filtersp, resolver_sp, false, false, false);
3527061da546Spatrick
3528061da546Spatrick // Give RS breakpoints a specific name, so the user can manipulate them as a
3529061da546Spatrick // group.
3530061da546Spatrick Status err;
3531061da546Spatrick target.AddNameToBreakpoint(bp, "RenderScriptReduction", err);
3532061da546Spatrick if (err.Fail() && log)
3533061da546Spatrick LLDB_LOGF(log, "%s - error setting break name, '%s'.", __FUNCTION__,
3534061da546Spatrick err.AsCString());
3535061da546Spatrick
3536061da546Spatrick return bp;
3537061da546Spatrick }
3538061da546Spatrick
3539061da546Spatrick // Given an expression for a variable this function tries to calculate the
3540061da546Spatrick // variable's value. If this is possible it returns true and sets the uint64_t
3541061da546Spatrick // parameter to the variables unsigned value. Otherwise function returns false.
GetFrameVarAsUnsigned(const StackFrameSP frame_sp,const char * var_name,uint64_t & val)3542061da546Spatrick bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3543061da546Spatrick const char *var_name,
3544061da546Spatrick uint64_t &val) {
3545*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
3546061da546Spatrick Status err;
3547061da546Spatrick VariableSP var_sp;
3548061da546Spatrick
3549061da546Spatrick // Find variable in stack frame
3550061da546Spatrick ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3551061da546Spatrick var_name, eNoDynamicValues,
3552061da546Spatrick StackFrame::eExpressionPathOptionCheckPtrVsMember |
3553061da546Spatrick StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3554061da546Spatrick var_sp, err));
3555061da546Spatrick if (!err.Success()) {
3556061da546Spatrick LLDB_LOGF(log, "%s - error, couldn't find '%s' in frame", __FUNCTION__,
3557061da546Spatrick var_name);
3558061da546Spatrick return false;
3559061da546Spatrick }
3560061da546Spatrick
3561061da546Spatrick // Find the uint32_t value for the variable
3562061da546Spatrick bool success = false;
3563061da546Spatrick val = value_sp->GetValueAsUnsigned(0, &success);
3564061da546Spatrick if (!success) {
3565061da546Spatrick LLDB_LOGF(log, "%s - error, couldn't parse '%s' as an uint32_t.",
3566061da546Spatrick __FUNCTION__, var_name);
3567061da546Spatrick return false;
3568061da546Spatrick }
3569061da546Spatrick
3570061da546Spatrick return true;
3571061da546Spatrick }
3572061da546Spatrick
3573061da546Spatrick // Function attempts to find the current coordinate of a kernel invocation by
3574061da546Spatrick // investigating the values of frame variables in the .expand function. These
3575061da546Spatrick // coordinates are returned via the coord array reference parameter. Returns
3576061da546Spatrick // true if the coordinates could be found, and false otherwise.
GetKernelCoordinate(RSCoordinate & coord,Thread * thread_ptr)3577061da546Spatrick bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3578061da546Spatrick Thread *thread_ptr) {
3579061da546Spatrick static const char *const x_expr = "rsIndex";
3580061da546Spatrick static const char *const y_expr = "p->current.y";
3581061da546Spatrick static const char *const z_expr = "p->current.z";
3582061da546Spatrick
3583*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
3584061da546Spatrick
3585061da546Spatrick if (!thread_ptr) {
3586061da546Spatrick LLDB_LOGF(log, "%s - Error, No thread pointer", __FUNCTION__);
3587061da546Spatrick
3588061da546Spatrick return false;
3589061da546Spatrick }
3590061da546Spatrick
3591061da546Spatrick // Walk the call stack looking for a function whose name has the suffix
3592061da546Spatrick // '.expand' and contains the variables we're looking for.
3593061da546Spatrick for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
3594061da546Spatrick if (!thread_ptr->SetSelectedFrameByIndex(i))
3595061da546Spatrick continue;
3596061da546Spatrick
3597061da546Spatrick StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
3598061da546Spatrick if (!frame_sp)
3599061da546Spatrick continue;
3600061da546Spatrick
3601061da546Spatrick // Find the function name
3602061da546Spatrick const SymbolContext sym_ctx =
3603061da546Spatrick frame_sp->GetSymbolContext(eSymbolContextFunction);
3604061da546Spatrick const ConstString func_name = sym_ctx.GetFunctionName();
3605061da546Spatrick if (!func_name)
3606061da546Spatrick continue;
3607061da546Spatrick
3608061da546Spatrick LLDB_LOGF(log, "%s - Inspecting function '%s'", __FUNCTION__,
3609061da546Spatrick func_name.GetCString());
3610061da546Spatrick
3611061da546Spatrick // Check if function name has .expand suffix
3612061da546Spatrick if (!func_name.GetStringRef().endswith(".expand"))
3613061da546Spatrick continue;
3614061da546Spatrick
3615061da546Spatrick LLDB_LOGF(log, "%s - Found .expand function '%s'", __FUNCTION__,
3616061da546Spatrick func_name.GetCString());
3617061da546Spatrick
3618061da546Spatrick // Get values for variables in .expand frame that tell us the current
3619061da546Spatrick // kernel invocation
3620061da546Spatrick uint64_t x, y, z;
3621061da546Spatrick bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
3622061da546Spatrick GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
3623061da546Spatrick GetFrameVarAsUnsigned(frame_sp, z_expr, z);
3624061da546Spatrick
3625061da546Spatrick if (found) {
3626061da546Spatrick // The RenderScript runtime uses uint32_t for these vars. If they're not
3627061da546Spatrick // within bounds, our frame parsing is garbage
3628061da546Spatrick assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
3629061da546Spatrick coord.x = (uint32_t)x;
3630061da546Spatrick coord.y = (uint32_t)y;
3631061da546Spatrick coord.z = (uint32_t)z;
3632061da546Spatrick return true;
3633061da546Spatrick }
3634061da546Spatrick }
3635061da546Spatrick return false;
3636061da546Spatrick }
3637061da546Spatrick
3638061da546Spatrick // Callback when a kernel breakpoint hits and we're looking for a specific
3639061da546Spatrick // coordinate. Baton parameter contains a pointer to the target coordinate we
3640061da546Spatrick // want to break on. Function then checks the .expand frame for the current
3641061da546Spatrick // coordinate and breaks to user if it matches. Parameter 'break_id' is the id
3642061da546Spatrick // of the Breakpoint which made the callback. Parameter 'break_loc_id' is the
3643061da546Spatrick // id for the BreakpointLocation which was hit, a single logical breakpoint can
3644061da546Spatrick // have multiple addresses.
KernelBreakpointHit(void * baton,StoppointCallbackContext * ctx,user_id_t break_id,user_id_t break_loc_id)3645061da546Spatrick bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3646061da546Spatrick StoppointCallbackContext *ctx,
3647061da546Spatrick user_id_t break_id,
3648061da546Spatrick user_id_t break_loc_id) {
3649*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3650061da546Spatrick
3651061da546Spatrick assert(baton &&
3652061da546Spatrick "Error: null baton in conditional kernel breakpoint callback");
3653061da546Spatrick
3654061da546Spatrick // Coordinate we want to stop on
3655061da546Spatrick RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3656061da546Spatrick
3657061da546Spatrick LLDB_LOGF(log, "%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__,
3658061da546Spatrick break_id, target_coord.x, target_coord.y, target_coord.z);
3659061da546Spatrick
3660061da546Spatrick // Select current thread
3661061da546Spatrick ExecutionContext context(ctx->exe_ctx_ref);
3662061da546Spatrick Thread *thread_ptr = context.GetThreadPtr();
3663061da546Spatrick assert(thread_ptr && "Null thread pointer");
3664061da546Spatrick
3665061da546Spatrick // Find current kernel invocation from .expand frame variables
3666061da546Spatrick RSCoordinate current_coord{};
3667061da546Spatrick if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3668061da546Spatrick LLDB_LOGF(log, "%s - Error, couldn't select .expand stack frame",
3669061da546Spatrick __FUNCTION__);
3670061da546Spatrick return false;
3671061da546Spatrick }
3672061da546Spatrick
3673061da546Spatrick LLDB_LOGF(log, "%s - " FMT_COORD, __FUNCTION__, current_coord.x,
3674061da546Spatrick current_coord.y, current_coord.z);
3675061da546Spatrick
3676061da546Spatrick // Check if the current kernel invocation coordinate matches our target
3677061da546Spatrick // coordinate
3678061da546Spatrick if (target_coord == current_coord) {
3679061da546Spatrick LLDB_LOGF(log, "%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
3680061da546Spatrick current_coord.y, current_coord.z);
3681061da546Spatrick
3682061da546Spatrick BreakpointSP breakpoint_sp =
3683061da546Spatrick context.GetTargetPtr()->GetBreakpointByID(break_id);
3684061da546Spatrick assert(breakpoint_sp != nullptr &&
3685061da546Spatrick "Error: Couldn't find breakpoint matching break id for callback");
3686061da546Spatrick breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3687061da546Spatrick // should only be hit once.
3688061da546Spatrick return true;
3689061da546Spatrick }
3690061da546Spatrick
3691061da546Spatrick // No match on coordinate
3692061da546Spatrick return false;
3693061da546Spatrick }
3694061da546Spatrick
SetConditional(BreakpointSP bp,Stream & messages,const RSCoordinate & coord)3695061da546Spatrick void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
3696061da546Spatrick const RSCoordinate &coord) {
3697061da546Spatrick messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
3698061da546Spatrick coord.x, coord.y, coord.z);
3699061da546Spatrick messages.EOL();
3700061da546Spatrick
3701061da546Spatrick // Allocate memory for the baton, and copy over coordinate
3702061da546Spatrick RSCoordinate *baton = new RSCoordinate(coord);
3703061da546Spatrick
3704061da546Spatrick // Create a callback that will be invoked every time the breakpoint is hit.
3705061da546Spatrick // The baton object passed to the handler is the target coordinate we want to
3706061da546Spatrick // break on.
3707061da546Spatrick bp->SetCallback(KernelBreakpointHit, baton, true);
3708061da546Spatrick
3709061da546Spatrick // Store a shared pointer to the baton, so the memory will eventually be
3710061da546Spatrick // cleaned up after destruction
3711061da546Spatrick m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
3712061da546Spatrick }
3713061da546Spatrick
3714061da546Spatrick // Tries to set a breakpoint on the start of a kernel, resolved using the
3715061da546Spatrick // kernel name. Argument 'coords', represents a three dimensional coordinate
3716061da546Spatrick // which can be used to specify a single kernel instance to break on. If this
3717061da546Spatrick // is set then we add a callback to the breakpoint.
PlaceBreakpointOnKernel(TargetSP target,Stream & messages,const char * name,const RSCoordinate * coord)3718061da546Spatrick bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
3719061da546Spatrick Stream &messages,
3720061da546Spatrick const char *name,
3721061da546Spatrick const RSCoordinate *coord) {
3722061da546Spatrick if (!name)
3723061da546Spatrick return false;
3724061da546Spatrick
3725061da546Spatrick InitSearchFilter(target);
3726061da546Spatrick
3727061da546Spatrick ConstString kernel_name(name);
3728061da546Spatrick BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
3729061da546Spatrick if (!bp)
3730061da546Spatrick return false;
3731061da546Spatrick
3732061da546Spatrick // We have a conditional breakpoint on a specific coordinate
3733061da546Spatrick if (coord)
3734061da546Spatrick SetConditional(bp, messages, *coord);
3735061da546Spatrick
3736061da546Spatrick bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3737061da546Spatrick
3738061da546Spatrick return true;
3739061da546Spatrick }
3740061da546Spatrick
3741061da546Spatrick BreakpointSP
CreateScriptGroupBreakpoint(ConstString name,bool stop_on_all)3742061da546Spatrick RenderScriptRuntime::CreateScriptGroupBreakpoint(ConstString name,
3743061da546Spatrick bool stop_on_all) {
3744*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3745061da546Spatrick
3746061da546Spatrick if (!m_filtersp) {
3747061da546Spatrick LLDB_LOGF(log, "%s - error, no breakpoint search filter set.",
3748061da546Spatrick __FUNCTION__);
3749061da546Spatrick return nullptr;
3750061da546Spatrick }
3751061da546Spatrick
3752061da546Spatrick BreakpointResolverSP resolver_sp(new RSScriptGroupBreakpointResolver(
3753061da546Spatrick nullptr, name, m_scriptGroups, stop_on_all));
3754061da546Spatrick Target &target = GetProcess()->GetTarget();
3755061da546Spatrick BreakpointSP bp = target.CreateBreakpoint(
3756061da546Spatrick m_filtersp, resolver_sp, false, false, false);
3757061da546Spatrick // Give RS breakpoints a specific name, so the user can manipulate them as a
3758061da546Spatrick // group.
3759061da546Spatrick Status err;
3760061da546Spatrick target.AddNameToBreakpoint(bp, name.GetCString(), err);
3761061da546Spatrick if (err.Fail() && log)
3762061da546Spatrick LLDB_LOGF(log, "%s - error setting break name, '%s'.", __FUNCTION__,
3763061da546Spatrick err.AsCString());
3764061da546Spatrick // ask the breakpoint to resolve itself
3765061da546Spatrick bp->ResolveBreakpoint();
3766061da546Spatrick return bp;
3767061da546Spatrick }
3768061da546Spatrick
PlaceBreakpointOnScriptGroup(TargetSP target,Stream & strm,ConstString name,bool multi)3769061da546Spatrick bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target,
3770061da546Spatrick Stream &strm,
3771061da546Spatrick ConstString name,
3772061da546Spatrick bool multi) {
3773061da546Spatrick InitSearchFilter(target);
3774061da546Spatrick BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi);
3775061da546Spatrick if (bp)
3776061da546Spatrick bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
3777061da546Spatrick return bool(bp);
3778061da546Spatrick }
3779061da546Spatrick
PlaceBreakpointOnReduction(TargetSP target,Stream & messages,const char * reduce_name,const RSCoordinate * coord,int kernel_types)3780061da546Spatrick bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3781061da546Spatrick Stream &messages,
3782061da546Spatrick const char *reduce_name,
3783061da546Spatrick const RSCoordinate *coord,
3784061da546Spatrick int kernel_types) {
3785061da546Spatrick if (!reduce_name)
3786061da546Spatrick return false;
3787061da546Spatrick
3788061da546Spatrick InitSearchFilter(target);
3789061da546Spatrick BreakpointSP bp =
3790061da546Spatrick CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3791061da546Spatrick if (!bp)
3792061da546Spatrick return false;
3793061da546Spatrick
3794061da546Spatrick if (coord)
3795061da546Spatrick SetConditional(bp, messages, *coord);
3796061da546Spatrick
3797061da546Spatrick bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3798061da546Spatrick
3799061da546Spatrick return true;
3800061da546Spatrick }
3801061da546Spatrick
DumpModules(Stream & strm) const3802061da546Spatrick void RenderScriptRuntime::DumpModules(Stream &strm) const {
3803061da546Spatrick strm.Printf("RenderScript Modules:");
3804061da546Spatrick strm.EOL();
3805061da546Spatrick strm.IndentMore();
3806061da546Spatrick for (const auto &module : m_rsmodules) {
3807061da546Spatrick module->Dump(strm);
3808061da546Spatrick }
3809061da546Spatrick strm.IndentLess();
3810061da546Spatrick }
3811061da546Spatrick
3812061da546Spatrick RenderScriptRuntime::ScriptDetails *
LookUpScript(addr_t address,bool create)3813061da546Spatrick RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3814061da546Spatrick for (const auto &s : m_scripts) {
3815061da546Spatrick if (s->script.isValid())
3816061da546Spatrick if (*s->script == address)
3817061da546Spatrick return s.get();
3818061da546Spatrick }
3819061da546Spatrick if (create) {
3820061da546Spatrick std::unique_ptr<ScriptDetails> s(new ScriptDetails);
3821061da546Spatrick s->script = address;
3822061da546Spatrick m_scripts.push_back(std::move(s));
3823061da546Spatrick return m_scripts.back().get();
3824061da546Spatrick }
3825061da546Spatrick return nullptr;
3826061da546Spatrick }
3827061da546Spatrick
3828061da546Spatrick RenderScriptRuntime::AllocationDetails *
LookUpAllocation(addr_t address)3829061da546Spatrick RenderScriptRuntime::LookUpAllocation(addr_t address) {
3830061da546Spatrick for (const auto &a : m_allocations) {
3831061da546Spatrick if (a->address.isValid())
3832061da546Spatrick if (*a->address == address)
3833061da546Spatrick return a.get();
3834061da546Spatrick }
3835061da546Spatrick return nullptr;
3836061da546Spatrick }
3837061da546Spatrick
3838061da546Spatrick RenderScriptRuntime::AllocationDetails *
CreateAllocation(addr_t address)3839061da546Spatrick RenderScriptRuntime::CreateAllocation(addr_t address) {
3840*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Language);
3841061da546Spatrick
3842061da546Spatrick // Remove any previous allocation which contains the same address
3843061da546Spatrick auto it = m_allocations.begin();
3844061da546Spatrick while (it != m_allocations.end()) {
3845061da546Spatrick if (*((*it)->address) == address) {
3846061da546Spatrick LLDB_LOGF(log, "%s - Removing allocation id: %d, address: 0x%" PRIx64,
3847061da546Spatrick __FUNCTION__, (*it)->id, address);
3848061da546Spatrick
3849061da546Spatrick it = m_allocations.erase(it);
3850061da546Spatrick } else {
3851061da546Spatrick it++;
3852061da546Spatrick }
3853061da546Spatrick }
3854061da546Spatrick
3855061da546Spatrick std::unique_ptr<AllocationDetails> a(new AllocationDetails);
3856061da546Spatrick a->address = address;
3857061da546Spatrick m_allocations.push_back(std::move(a));
3858061da546Spatrick return m_allocations.back().get();
3859061da546Spatrick }
3860061da546Spatrick
ResolveKernelName(lldb::addr_t kernel_addr,ConstString & name)3861061da546Spatrick bool RenderScriptRuntime::ResolveKernelName(lldb::addr_t kernel_addr,
3862061da546Spatrick ConstString &name) {
3863*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Symbols);
3864061da546Spatrick
3865061da546Spatrick Target &target = GetProcess()->GetTarget();
3866061da546Spatrick Address resolved;
3867061da546Spatrick // RenderScript module
3868061da546Spatrick if (!target.GetSectionLoadList().ResolveLoadAddress(kernel_addr, resolved)) {
3869061da546Spatrick LLDB_LOGF(log, "%s: unable to resolve 0x%" PRIx64 " to a loaded symbol",
3870061da546Spatrick __FUNCTION__, kernel_addr);
3871061da546Spatrick return false;
3872061da546Spatrick }
3873061da546Spatrick
3874061da546Spatrick Symbol *sym = resolved.CalculateSymbolContextSymbol();
3875061da546Spatrick if (!sym)
3876061da546Spatrick return false;
3877061da546Spatrick
3878061da546Spatrick name = sym->GetName();
3879061da546Spatrick assert(IsRenderScriptModule(resolved.CalculateSymbolContextModule()));
3880061da546Spatrick LLDB_LOGF(log, "%s: 0x%" PRIx64 " resolved to the symbol '%s'", __FUNCTION__,
3881061da546Spatrick kernel_addr, name.GetCString());
3882061da546Spatrick return true;
3883061da546Spatrick }
3884061da546Spatrick
Dump(Stream & strm) const3885061da546Spatrick void RSModuleDescriptor::Dump(Stream &strm) const {
3886061da546Spatrick int indent = strm.GetIndentLevel();
3887061da546Spatrick
3888061da546Spatrick strm.Indent();
3889061da546Spatrick m_module->GetFileSpec().Dump(strm.AsRawOstream());
3890061da546Spatrick strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
3891061da546Spatrick : "Debug info does not exist.");
3892061da546Spatrick strm.EOL();
3893061da546Spatrick strm.IndentMore();
3894061da546Spatrick
3895061da546Spatrick strm.Indent();
3896061da546Spatrick strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
3897061da546Spatrick strm.EOL();
3898061da546Spatrick strm.IndentMore();
3899061da546Spatrick for (const auto &global : m_globals) {
3900061da546Spatrick global.Dump(strm);
3901061da546Spatrick }
3902061da546Spatrick strm.IndentLess();
3903061da546Spatrick
3904061da546Spatrick strm.Indent();
3905061da546Spatrick strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
3906061da546Spatrick strm.EOL();
3907061da546Spatrick strm.IndentMore();
3908061da546Spatrick for (const auto &kernel : m_kernels) {
3909061da546Spatrick kernel.Dump(strm);
3910061da546Spatrick }
3911061da546Spatrick strm.IndentLess();
3912061da546Spatrick
3913061da546Spatrick strm.Indent();
3914061da546Spatrick strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
3915061da546Spatrick strm.EOL();
3916061da546Spatrick strm.IndentMore();
3917061da546Spatrick for (const auto &key_val : m_pragmas) {
3918061da546Spatrick strm.Indent();
3919061da546Spatrick strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
3920061da546Spatrick strm.EOL();
3921061da546Spatrick }
3922061da546Spatrick strm.IndentLess();
3923061da546Spatrick
3924061da546Spatrick strm.Indent();
3925061da546Spatrick strm.Printf("Reductions: %" PRIu64,
3926061da546Spatrick static_cast<uint64_t>(m_reductions.size()));
3927061da546Spatrick strm.EOL();
3928061da546Spatrick strm.IndentMore();
3929061da546Spatrick for (const auto &reduction : m_reductions) {
3930061da546Spatrick reduction.Dump(strm);
3931061da546Spatrick }
3932061da546Spatrick
3933061da546Spatrick strm.SetIndentLevel(indent);
3934061da546Spatrick }
3935061da546Spatrick
Dump(Stream & strm) const3936061da546Spatrick void RSGlobalDescriptor::Dump(Stream &strm) const {
3937dda28197Spatrick strm.Indent(m_name.GetStringRef());
3938061da546Spatrick VariableList var_list;
3939dda28197Spatrick m_module->m_module->FindGlobalVariables(m_name, CompilerDeclContext(), 1U,
3940dda28197Spatrick var_list);
3941061da546Spatrick if (var_list.GetSize() == 1) {
3942061da546Spatrick auto var = var_list.GetVariableAtIndex(0);
3943061da546Spatrick auto type = var->GetType();
3944061da546Spatrick if (type) {
3945061da546Spatrick strm.Printf(" - ");
3946061da546Spatrick type->DumpTypeName(&strm);
3947061da546Spatrick } else {
3948061da546Spatrick strm.Printf(" - Unknown Type");
3949061da546Spatrick }
3950061da546Spatrick } else {
3951061da546Spatrick strm.Printf(" - variable identified, but not found in binary");
3952061da546Spatrick const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
3953061da546Spatrick m_name, eSymbolTypeData);
3954061da546Spatrick if (s) {
3955061da546Spatrick strm.Printf(" (symbol exists) ");
3956061da546Spatrick }
3957061da546Spatrick }
3958061da546Spatrick
3959061da546Spatrick strm.EOL();
3960061da546Spatrick }
3961061da546Spatrick
Dump(Stream & strm) const3962061da546Spatrick void RSKernelDescriptor::Dump(Stream &strm) const {
3963dda28197Spatrick strm.Indent(m_name.GetStringRef());
3964061da546Spatrick strm.EOL();
3965061da546Spatrick }
3966061da546Spatrick
Dump(lldb_private::Stream & stream) const3967061da546Spatrick void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
3968dda28197Spatrick stream.Indent(m_reduce_name.GetStringRef());
3969061da546Spatrick stream.IndentMore();
3970061da546Spatrick stream.EOL();
3971061da546Spatrick stream.Indent();
3972061da546Spatrick stream.Printf("accumulator: %s", m_accum_name.AsCString());
3973061da546Spatrick stream.EOL();
3974061da546Spatrick stream.Indent();
3975061da546Spatrick stream.Printf("initializer: %s", m_init_name.AsCString());
3976061da546Spatrick stream.EOL();
3977061da546Spatrick stream.Indent();
3978061da546Spatrick stream.Printf("combiner: %s", m_comb_name.AsCString());
3979061da546Spatrick stream.EOL();
3980061da546Spatrick stream.Indent();
3981061da546Spatrick stream.Printf("outconverter: %s", m_outc_name.AsCString());
3982061da546Spatrick stream.EOL();
3983061da546Spatrick // XXX This is currently unspecified by RenderScript, and unused
3984061da546Spatrick // stream.Indent();
3985061da546Spatrick // stream.Printf("halter: '%s'", m_init_name.AsCString());
3986061da546Spatrick // stream.EOL();
3987061da546Spatrick stream.IndentLess();
3988061da546Spatrick }
3989061da546Spatrick
3990061da546Spatrick class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
3991061da546Spatrick public:
CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter & interpreter)3992061da546Spatrick CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
3993061da546Spatrick : CommandObjectParsed(
3994061da546Spatrick interpreter, "renderscript module dump",
3995061da546Spatrick "Dumps renderscript specific information for all modules.",
3996061da546Spatrick "renderscript module dump",
3997061da546Spatrick eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
3998061da546Spatrick
3999061da546Spatrick ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
4000061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4001061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4002061da546Spatrick RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4003061da546Spatrick m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4004061da546Spatrick eLanguageTypeExtRenderScript));
4005061da546Spatrick runtime->DumpModules(result.GetOutputStream());
4006061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4007061da546Spatrick return true;
4008061da546Spatrick }
4009061da546Spatrick };
4010061da546Spatrick
4011061da546Spatrick class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
4012061da546Spatrick public:
CommandObjectRenderScriptRuntimeModule(CommandInterpreter & interpreter)4013061da546Spatrick CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
4014061da546Spatrick : CommandObjectMultiword(interpreter, "renderscript module",
4015061da546Spatrick "Commands that deal with RenderScript modules.",
4016061da546Spatrick nullptr) {
4017061da546Spatrick LoadSubCommand(
4018061da546Spatrick "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
4019061da546Spatrick interpreter)));
4020061da546Spatrick }
4021061da546Spatrick
4022061da546Spatrick ~CommandObjectRenderScriptRuntimeModule() override = default;
4023061da546Spatrick };
4024061da546Spatrick
4025061da546Spatrick class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
4026061da546Spatrick public:
CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter & interpreter)4027061da546Spatrick CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
4028061da546Spatrick : CommandObjectParsed(
4029061da546Spatrick interpreter, "renderscript kernel list",
4030061da546Spatrick "Lists renderscript kernel names and associated script resources.",
4031061da546Spatrick "renderscript kernel list",
4032061da546Spatrick eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4033061da546Spatrick
4034061da546Spatrick ~CommandObjectRenderScriptRuntimeKernelList() override = default;
4035061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4036061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4037061da546Spatrick RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4038061da546Spatrick m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4039061da546Spatrick eLanguageTypeExtRenderScript));
4040061da546Spatrick runtime->DumpKernels(result.GetOutputStream());
4041061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4042061da546Spatrick return true;
4043061da546Spatrick }
4044061da546Spatrick };
4045061da546Spatrick
4046061da546Spatrick static constexpr OptionDefinition g_renderscript_reduction_bp_set_options[] = {
4047061da546Spatrick {LLDB_OPT_SET_1, false, "function-role", 't',
4048061da546Spatrick OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOneLiner,
4049061da546Spatrick "Break on a comma separated set of reduction kernel types "
4050061da546Spatrick "(accumulator,outcoverter,combiner,initializer"},
4051061da546Spatrick {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4052061da546Spatrick nullptr, {}, 0, eArgTypeValue,
4053061da546Spatrick "Set a breakpoint on a single invocation of the kernel with specified "
4054061da546Spatrick "coordinate.\n"
4055061da546Spatrick "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4056061da546Spatrick "integers representing kernel dimensions. "
4057061da546Spatrick "Any unset dimensions will be defaulted to zero."}};
4058061da546Spatrick
4059061da546Spatrick class CommandObjectRenderScriptRuntimeReductionBreakpointSet
4060061da546Spatrick : public CommandObjectParsed {
4061061da546Spatrick public:
CommandObjectRenderScriptRuntimeReductionBreakpointSet(CommandInterpreter & interpreter)4062061da546Spatrick CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4063061da546Spatrick CommandInterpreter &interpreter)
4064061da546Spatrick : CommandObjectParsed(
4065061da546Spatrick interpreter, "renderscript reduction breakpoint set",
4066061da546Spatrick "Set a breakpoint on named RenderScript general reductions",
4067061da546Spatrick "renderscript reduction breakpoint set <kernel_name> [-t "
4068061da546Spatrick "<reduction_kernel_type,...>]",
4069061da546Spatrick eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4070061da546Spatrick eCommandProcessMustBePaused),
4071*f6aab3d8Srobert m_options() {
4072*f6aab3d8Srobert CommandArgumentData name_arg{eArgTypeName, eArgRepeatPlain};
4073*f6aab3d8Srobert m_arguments.push_back({name_arg});
4074*f6aab3d8Srobert };
4075061da546Spatrick
4076061da546Spatrick class CommandOptions : public Options {
4077061da546Spatrick public:
CommandOptions()4078be691f3bSpatrick CommandOptions() : Options() {}
4079061da546Spatrick
4080061da546Spatrick ~CommandOptions() override = default;
4081061da546Spatrick
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * exe_ctx)4082061da546Spatrick Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4083061da546Spatrick ExecutionContext *exe_ctx) override {
4084061da546Spatrick Status err;
4085061da546Spatrick StreamString err_str;
4086061da546Spatrick const int short_option = m_getopt_table[option_idx].val;
4087061da546Spatrick switch (short_option) {
4088061da546Spatrick case 't':
4089061da546Spatrick if (!ParseReductionTypes(option_arg, err_str))
4090061da546Spatrick err.SetErrorStringWithFormat(
4091061da546Spatrick "Unable to deduce reduction types for %s: %s",
4092061da546Spatrick option_arg.str().c_str(), err_str.GetData());
4093061da546Spatrick break;
4094061da546Spatrick case 'c': {
4095061da546Spatrick auto coord = RSCoordinate{};
4096061da546Spatrick if (!ParseCoordinate(option_arg, coord))
4097061da546Spatrick err.SetErrorStringWithFormat("unable to parse coordinate for %s",
4098061da546Spatrick option_arg.str().c_str());
4099061da546Spatrick else {
4100061da546Spatrick m_have_coord = true;
4101061da546Spatrick m_coord = coord;
4102061da546Spatrick }
4103061da546Spatrick break;
4104061da546Spatrick }
4105061da546Spatrick default:
4106061da546Spatrick err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
4107061da546Spatrick }
4108061da546Spatrick return err;
4109061da546Spatrick }
4110061da546Spatrick
OptionParsingStarting(ExecutionContext * exe_ctx)4111061da546Spatrick void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4112061da546Spatrick m_have_coord = false;
4113061da546Spatrick }
4114061da546Spatrick
GetDefinitions()4115061da546Spatrick llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4116*f6aab3d8Srobert return llvm::ArrayRef(g_renderscript_reduction_bp_set_options);
4117061da546Spatrick }
4118061da546Spatrick
ParseReductionTypes(llvm::StringRef option_val,StreamString & err_str)4119061da546Spatrick bool ParseReductionTypes(llvm::StringRef option_val,
4120061da546Spatrick StreamString &err_str) {
4121061da546Spatrick m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
4122061da546Spatrick const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
4123061da546Spatrick return llvm::StringSwitch<int>(name)
4124061da546Spatrick .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
4125061da546Spatrick .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
4126061da546Spatrick .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
4127061da546Spatrick .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
4128061da546Spatrick .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
4129061da546Spatrick // Currently not exposed by the runtime
4130061da546Spatrick // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
4131061da546Spatrick .Default(0);
4132061da546Spatrick };
4133061da546Spatrick
4134061da546Spatrick // Matching a comma separated list of known words is fairly
4135061da546Spatrick // straightforward with PCRE, but we're using ERE, so we end up with a
4136061da546Spatrick // little ugliness...
4137061da546Spatrick RegularExpression match_type_list(
4138061da546Spatrick llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
4139061da546Spatrick
4140061da546Spatrick assert(match_type_list.IsValid());
4141061da546Spatrick
4142061da546Spatrick if (!match_type_list.Execute(option_val)) {
4143061da546Spatrick err_str.PutCString(
4144061da546Spatrick "a comma-separated list of kernel types is required");
4145061da546Spatrick return false;
4146061da546Spatrick }
4147061da546Spatrick
4148061da546Spatrick // splitting on commas is much easier with llvm::StringRef than regex
4149061da546Spatrick llvm::SmallVector<llvm::StringRef, 5> type_names;
4150061da546Spatrick llvm::StringRef(option_val).split(type_names, ',');
4151061da546Spatrick
4152061da546Spatrick for (const auto &name : type_names) {
4153061da546Spatrick const int type = reduce_name_to_type(name);
4154061da546Spatrick if (!type) {
4155061da546Spatrick err_str.Printf("unknown kernel type name %s", name.str().c_str());
4156061da546Spatrick return false;
4157061da546Spatrick }
4158061da546Spatrick m_kernel_types |= type;
4159061da546Spatrick }
4160061da546Spatrick
4161061da546Spatrick return true;
4162061da546Spatrick }
4163061da546Spatrick
4164be691f3bSpatrick int m_kernel_types = RSReduceBreakpointResolver::eKernelTypeAll;
4165061da546Spatrick llvm::StringRef m_reduce_name;
4166061da546Spatrick RSCoordinate m_coord;
4167*f6aab3d8Srobert bool m_have_coord = false;
4168061da546Spatrick };
4169061da546Spatrick
GetOptions()4170061da546Spatrick Options *GetOptions() override { return &m_options; }
4171061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4172061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4173061da546Spatrick const size_t argc = command.GetArgumentCount();
4174061da546Spatrick if (argc < 1) {
4175061da546Spatrick result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
4176061da546Spatrick "and an optional kernel type list",
4177061da546Spatrick m_cmd_name.c_str());
4178061da546Spatrick return false;
4179061da546Spatrick }
4180061da546Spatrick
4181061da546Spatrick RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4182061da546Spatrick m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4183061da546Spatrick eLanguageTypeExtRenderScript));
4184061da546Spatrick
4185061da546Spatrick auto &outstream = result.GetOutputStream();
4186061da546Spatrick auto name = command.GetArgumentAtIndex(0);
4187061da546Spatrick auto &target = m_exe_ctx.GetTargetSP();
4188061da546Spatrick auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4189061da546Spatrick if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
4190061da546Spatrick m_options.m_kernel_types)) {
4191061da546Spatrick result.AppendError("Error: unable to place breakpoint on reduction");
4192061da546Spatrick return false;
4193061da546Spatrick }
4194061da546Spatrick result.AppendMessage("Breakpoint(s) created");
4195061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4196061da546Spatrick return true;
4197061da546Spatrick }
4198061da546Spatrick
4199061da546Spatrick private:
4200061da546Spatrick CommandOptions m_options;
4201061da546Spatrick };
4202061da546Spatrick
4203061da546Spatrick static constexpr OptionDefinition g_renderscript_kernel_bp_set_options[] = {
4204061da546Spatrick {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4205061da546Spatrick nullptr, {}, 0, eArgTypeValue,
4206061da546Spatrick "Set a breakpoint on a single invocation of the kernel with specified "
4207061da546Spatrick "coordinate.\n"
4208061da546Spatrick "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4209061da546Spatrick "integers representing kernel dimensions. "
4210061da546Spatrick "Any unset dimensions will be defaulted to zero."}};
4211061da546Spatrick
4212061da546Spatrick class CommandObjectRenderScriptRuntimeKernelBreakpointSet
4213061da546Spatrick : public CommandObjectParsed {
4214061da546Spatrick public:
CommandObjectRenderScriptRuntimeKernelBreakpointSet(CommandInterpreter & interpreter)4215061da546Spatrick CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4216061da546Spatrick CommandInterpreter &interpreter)
4217061da546Spatrick : CommandObjectParsed(
4218061da546Spatrick interpreter, "renderscript kernel breakpoint set",
4219061da546Spatrick "Sets a breakpoint on a renderscript kernel.",
4220061da546Spatrick "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
4221061da546Spatrick eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4222061da546Spatrick eCommandProcessMustBePaused),
4223*f6aab3d8Srobert m_options() {
4224*f6aab3d8Srobert CommandArgumentData name_arg{eArgTypeName, eArgRepeatPlain};
4225*f6aab3d8Srobert m_arguments.push_back({name_arg});
4226*f6aab3d8Srobert }
4227061da546Spatrick
4228061da546Spatrick ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
4229061da546Spatrick
GetOptions()4230061da546Spatrick Options *GetOptions() override { return &m_options; }
4231061da546Spatrick
4232061da546Spatrick class CommandOptions : public Options {
4233061da546Spatrick public:
CommandOptions()4234061da546Spatrick CommandOptions() : Options() {}
4235061da546Spatrick
4236061da546Spatrick ~CommandOptions() override = default;
4237061da546Spatrick
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * exe_ctx)4238061da546Spatrick Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4239061da546Spatrick ExecutionContext *exe_ctx) override {
4240061da546Spatrick Status err;
4241061da546Spatrick const int short_option = m_getopt_table[option_idx].val;
4242061da546Spatrick
4243061da546Spatrick switch (short_option) {
4244061da546Spatrick case 'c': {
4245061da546Spatrick auto coord = RSCoordinate{};
4246061da546Spatrick if (!ParseCoordinate(option_arg, coord))
4247061da546Spatrick err.SetErrorStringWithFormat(
4248061da546Spatrick "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
4249061da546Spatrick option_arg.str().c_str());
4250061da546Spatrick else {
4251061da546Spatrick m_have_coord = true;
4252061da546Spatrick m_coord = coord;
4253061da546Spatrick }
4254061da546Spatrick break;
4255061da546Spatrick }
4256061da546Spatrick default:
4257061da546Spatrick err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4258061da546Spatrick break;
4259061da546Spatrick }
4260061da546Spatrick return err;
4261061da546Spatrick }
4262061da546Spatrick
OptionParsingStarting(ExecutionContext * exe_ctx)4263061da546Spatrick void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4264061da546Spatrick m_have_coord = false;
4265061da546Spatrick }
4266061da546Spatrick
GetDefinitions()4267061da546Spatrick llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4268*f6aab3d8Srobert return llvm::ArrayRef(g_renderscript_kernel_bp_set_options);
4269061da546Spatrick }
4270061da546Spatrick
4271061da546Spatrick RSCoordinate m_coord;
4272*f6aab3d8Srobert bool m_have_coord = false;
4273061da546Spatrick };
4274061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4275061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4276061da546Spatrick const size_t argc = command.GetArgumentCount();
4277061da546Spatrick if (argc < 1) {
4278061da546Spatrick result.AppendErrorWithFormat(
4279061da546Spatrick "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4280061da546Spatrick m_cmd_name.c_str());
4281061da546Spatrick return false;
4282061da546Spatrick }
4283061da546Spatrick
4284061da546Spatrick RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4285061da546Spatrick m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4286061da546Spatrick eLanguageTypeExtRenderScript));
4287061da546Spatrick
4288061da546Spatrick auto &outstream = result.GetOutputStream();
4289061da546Spatrick auto &target = m_exe_ctx.GetTargetSP();
4290061da546Spatrick auto name = command.GetArgumentAtIndex(0);
4291061da546Spatrick auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4292061da546Spatrick if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
4293061da546Spatrick result.AppendErrorWithFormat(
4294061da546Spatrick "Error: unable to set breakpoint on kernel '%s'", name);
4295061da546Spatrick return false;
4296061da546Spatrick }
4297061da546Spatrick
4298061da546Spatrick result.AppendMessage("Breakpoint(s) created");
4299061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4300061da546Spatrick return true;
4301061da546Spatrick }
4302061da546Spatrick
4303061da546Spatrick private:
4304061da546Spatrick CommandOptions m_options;
4305061da546Spatrick };
4306061da546Spatrick
4307061da546Spatrick class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4308061da546Spatrick : public CommandObjectParsed {
4309061da546Spatrick public:
CommandObjectRenderScriptRuntimeKernelBreakpointAll(CommandInterpreter & interpreter)4310061da546Spatrick CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4311061da546Spatrick CommandInterpreter &interpreter)
4312061da546Spatrick : CommandObjectParsed(
4313061da546Spatrick interpreter, "renderscript kernel breakpoint all",
4314061da546Spatrick "Automatically sets a breakpoint on all renderscript kernels that "
4315061da546Spatrick "are or will be loaded.\n"
4316061da546Spatrick "Disabling option means breakpoints will no longer be set on any "
4317061da546Spatrick "kernels loaded in the future, "
4318061da546Spatrick "but does not remove currently set breakpoints.",
4319061da546Spatrick "renderscript kernel breakpoint all <enable/disable>",
4320061da546Spatrick eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4321*f6aab3d8Srobert eCommandProcessMustBePaused) {
4322*f6aab3d8Srobert CommandArgumentData enable_arg{eArgTypeNone, eArgRepeatPlain};
4323*f6aab3d8Srobert m_arguments.push_back({enable_arg});
4324*f6aab3d8Srobert }
4325061da546Spatrick
4326061da546Spatrick ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
4327061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4328061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4329061da546Spatrick const size_t argc = command.GetArgumentCount();
4330061da546Spatrick if (argc != 1) {
4331061da546Spatrick result.AppendErrorWithFormat(
4332061da546Spatrick "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
4333061da546Spatrick return false;
4334061da546Spatrick }
4335061da546Spatrick
4336061da546Spatrick RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4337061da546Spatrick m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4338061da546Spatrick eLanguageTypeExtRenderScript));
4339061da546Spatrick
4340061da546Spatrick bool do_break = false;
4341061da546Spatrick const char *argument = command.GetArgumentAtIndex(0);
4342061da546Spatrick if (strcmp(argument, "enable") == 0) {
4343061da546Spatrick do_break = true;
4344061da546Spatrick result.AppendMessage("Breakpoints will be set on all kernels.");
4345061da546Spatrick } else if (strcmp(argument, "disable") == 0) {
4346061da546Spatrick do_break = false;
4347061da546Spatrick result.AppendMessage("Breakpoints will not be set on any new kernels.");
4348061da546Spatrick } else {
4349061da546Spatrick result.AppendErrorWithFormat(
4350061da546Spatrick "Argument must be either 'enable' or 'disable'");
4351061da546Spatrick return false;
4352061da546Spatrick }
4353061da546Spatrick
4354061da546Spatrick runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
4355061da546Spatrick
4356061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4357061da546Spatrick return true;
4358061da546Spatrick }
4359061da546Spatrick };
4360061da546Spatrick
4361061da546Spatrick class CommandObjectRenderScriptRuntimeReductionBreakpoint
4362061da546Spatrick : public CommandObjectMultiword {
4363061da546Spatrick public:
CommandObjectRenderScriptRuntimeReductionBreakpoint(CommandInterpreter & interpreter)4364061da546Spatrick CommandObjectRenderScriptRuntimeReductionBreakpoint(
4365061da546Spatrick CommandInterpreter &interpreter)
4366061da546Spatrick : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4367061da546Spatrick "Commands that manipulate breakpoints on "
4368061da546Spatrick "renderscript general reductions.",
4369061da546Spatrick nullptr) {
4370061da546Spatrick LoadSubCommand(
4371061da546Spatrick "set", CommandObjectSP(
4372061da546Spatrick new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4373061da546Spatrick interpreter)));
4374061da546Spatrick }
4375061da546Spatrick
4376061da546Spatrick ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4377061da546Spatrick };
4378061da546Spatrick
4379061da546Spatrick class CommandObjectRenderScriptRuntimeKernelCoordinate
4380061da546Spatrick : public CommandObjectParsed {
4381061da546Spatrick public:
CommandObjectRenderScriptRuntimeKernelCoordinate(CommandInterpreter & interpreter)4382061da546Spatrick CommandObjectRenderScriptRuntimeKernelCoordinate(
4383061da546Spatrick CommandInterpreter &interpreter)
4384061da546Spatrick : CommandObjectParsed(
4385061da546Spatrick interpreter, "renderscript kernel coordinate",
4386061da546Spatrick "Shows the (x,y,z) coordinate of the current kernel invocation.",
4387061da546Spatrick "renderscript kernel coordinate",
4388061da546Spatrick eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4389061da546Spatrick eCommandProcessMustBePaused) {}
4390061da546Spatrick
4391061da546Spatrick ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
4392061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4393061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4394061da546Spatrick RSCoordinate coord{};
4395061da546Spatrick bool success = RenderScriptRuntime::GetKernelCoordinate(
4396061da546Spatrick coord, m_exe_ctx.GetThreadPtr());
4397061da546Spatrick Stream &stream = result.GetOutputStream();
4398061da546Spatrick
4399061da546Spatrick if (success) {
4400061da546Spatrick stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
4401061da546Spatrick stream.EOL();
4402061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4403061da546Spatrick } else {
4404061da546Spatrick stream.Printf("Error: Coordinate could not be found.");
4405061da546Spatrick stream.EOL();
4406061da546Spatrick result.SetStatus(eReturnStatusFailed);
4407061da546Spatrick }
4408061da546Spatrick return true;
4409061da546Spatrick }
4410061da546Spatrick };
4411061da546Spatrick
4412061da546Spatrick class CommandObjectRenderScriptRuntimeKernelBreakpoint
4413061da546Spatrick : public CommandObjectMultiword {
4414061da546Spatrick public:
CommandObjectRenderScriptRuntimeKernelBreakpoint(CommandInterpreter & interpreter)4415061da546Spatrick CommandObjectRenderScriptRuntimeKernelBreakpoint(
4416061da546Spatrick CommandInterpreter &interpreter)
4417061da546Spatrick : CommandObjectMultiword(
4418061da546Spatrick interpreter, "renderscript kernel",
4419061da546Spatrick "Commands that generate breakpoints on renderscript kernels.",
4420061da546Spatrick nullptr) {
4421061da546Spatrick LoadSubCommand(
4422061da546Spatrick "set",
4423061da546Spatrick CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4424061da546Spatrick interpreter)));
4425061da546Spatrick LoadSubCommand(
4426061da546Spatrick "all",
4427061da546Spatrick CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4428061da546Spatrick interpreter)));
4429061da546Spatrick }
4430061da546Spatrick
4431061da546Spatrick ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
4432061da546Spatrick };
4433061da546Spatrick
4434061da546Spatrick class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
4435061da546Spatrick public:
CommandObjectRenderScriptRuntimeKernel(CommandInterpreter & interpreter)4436061da546Spatrick CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4437061da546Spatrick : CommandObjectMultiword(interpreter, "renderscript kernel",
4438061da546Spatrick "Commands that deal with RenderScript kernels.",
4439061da546Spatrick nullptr) {
4440061da546Spatrick LoadSubCommand(
4441061da546Spatrick "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4442061da546Spatrick interpreter)));
4443061da546Spatrick LoadSubCommand(
4444061da546Spatrick "coordinate",
4445061da546Spatrick CommandObjectSP(
4446061da546Spatrick new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4447061da546Spatrick LoadSubCommand(
4448061da546Spatrick "breakpoint",
4449061da546Spatrick CommandObjectSP(
4450061da546Spatrick new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
4451061da546Spatrick }
4452061da546Spatrick
4453061da546Spatrick ~CommandObjectRenderScriptRuntimeKernel() override = default;
4454061da546Spatrick };
4455061da546Spatrick
4456061da546Spatrick class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
4457061da546Spatrick public:
CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter & interpreter)4458061da546Spatrick CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4459061da546Spatrick : CommandObjectParsed(interpreter, "renderscript context dump",
4460061da546Spatrick "Dumps renderscript context information.",
4461061da546Spatrick "renderscript context dump",
4462061da546Spatrick eCommandRequiresProcess |
4463061da546Spatrick eCommandProcessMustBeLaunched) {}
4464061da546Spatrick
4465061da546Spatrick ~CommandObjectRenderScriptRuntimeContextDump() override = default;
4466061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4467061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4468061da546Spatrick RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4469061da546Spatrick m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4470061da546Spatrick eLanguageTypeExtRenderScript));
4471061da546Spatrick runtime->DumpContexts(result.GetOutputStream());
4472061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4473061da546Spatrick return true;
4474061da546Spatrick }
4475061da546Spatrick };
4476061da546Spatrick
4477061da546Spatrick static constexpr OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
4478061da546Spatrick {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
4479061da546Spatrick nullptr, {}, 0, eArgTypeFilename,
4480061da546Spatrick "Print results to specified file instead of command line."}};
4481061da546Spatrick
4482061da546Spatrick class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
4483061da546Spatrick public:
CommandObjectRenderScriptRuntimeContext(CommandInterpreter & interpreter)4484061da546Spatrick CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4485061da546Spatrick : CommandObjectMultiword(interpreter, "renderscript context",
4486061da546Spatrick "Commands that deal with RenderScript contexts.",
4487061da546Spatrick nullptr) {
4488061da546Spatrick LoadSubCommand(
4489061da546Spatrick "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4490061da546Spatrick interpreter)));
4491061da546Spatrick }
4492061da546Spatrick
4493061da546Spatrick ~CommandObjectRenderScriptRuntimeContext() override = default;
4494061da546Spatrick };
4495061da546Spatrick
4496061da546Spatrick class CommandObjectRenderScriptRuntimeAllocationDump
4497061da546Spatrick : public CommandObjectParsed {
4498061da546Spatrick public:
CommandObjectRenderScriptRuntimeAllocationDump(CommandInterpreter & interpreter)4499061da546Spatrick CommandObjectRenderScriptRuntimeAllocationDump(
4500061da546Spatrick CommandInterpreter &interpreter)
4501061da546Spatrick : CommandObjectParsed(interpreter, "renderscript allocation dump",
4502061da546Spatrick "Displays the contents of a particular allocation",
4503061da546Spatrick "renderscript allocation dump <ID>",
4504061da546Spatrick eCommandRequiresProcess |
4505061da546Spatrick eCommandProcessMustBeLaunched),
4506*f6aab3d8Srobert m_options() {
4507*f6aab3d8Srobert CommandArgumentData id_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
4508*f6aab3d8Srobert m_arguments.push_back({id_arg});
4509*f6aab3d8Srobert }
4510061da546Spatrick
4511061da546Spatrick ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4512061da546Spatrick
GetOptions()4513061da546Spatrick Options *GetOptions() override { return &m_options; }
4514061da546Spatrick
4515061da546Spatrick class CommandOptions : public Options {
4516061da546Spatrick public:
CommandOptions()4517061da546Spatrick CommandOptions() : Options() {}
4518061da546Spatrick
4519061da546Spatrick ~CommandOptions() override = default;
4520061da546Spatrick
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * exe_ctx)4521061da546Spatrick Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4522061da546Spatrick ExecutionContext *exe_ctx) override {
4523061da546Spatrick Status err;
4524061da546Spatrick const int short_option = m_getopt_table[option_idx].val;
4525061da546Spatrick
4526061da546Spatrick switch (short_option) {
4527061da546Spatrick case 'f':
4528061da546Spatrick m_outfile.SetFile(option_arg, FileSpec::Style::native);
4529061da546Spatrick FileSystem::Instance().Resolve(m_outfile);
4530061da546Spatrick if (FileSystem::Instance().Exists(m_outfile)) {
4531061da546Spatrick m_outfile.Clear();
4532061da546Spatrick err.SetErrorStringWithFormat("file already exists: '%s'",
4533061da546Spatrick option_arg.str().c_str());
4534061da546Spatrick }
4535061da546Spatrick break;
4536061da546Spatrick default:
4537061da546Spatrick err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4538061da546Spatrick break;
4539061da546Spatrick }
4540061da546Spatrick return err;
4541061da546Spatrick }
4542061da546Spatrick
OptionParsingStarting(ExecutionContext * exe_ctx)4543061da546Spatrick void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4544061da546Spatrick m_outfile.Clear();
4545061da546Spatrick }
4546061da546Spatrick
GetDefinitions()4547061da546Spatrick llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4548*f6aab3d8Srobert return llvm::ArrayRef(g_renderscript_runtime_alloc_dump_options);
4549061da546Spatrick }
4550061da546Spatrick
4551061da546Spatrick FileSpec m_outfile;
4552061da546Spatrick };
4553061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4554061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4555061da546Spatrick const size_t argc = command.GetArgumentCount();
4556061da546Spatrick if (argc < 1) {
4557061da546Spatrick result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4558061da546Spatrick "As well as an optional -f argument",
4559061da546Spatrick m_cmd_name.c_str());
4560061da546Spatrick return false;
4561061da546Spatrick }
4562061da546Spatrick
4563061da546Spatrick RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4564061da546Spatrick m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4565061da546Spatrick eLanguageTypeExtRenderScript));
4566061da546Spatrick
4567061da546Spatrick const char *id_cstr = command.GetArgumentAtIndex(0);
4568*f6aab3d8Srobert uint32_t id;
4569*f6aab3d8Srobert if (!llvm::to_integer(id_cstr, id)) {
4570061da546Spatrick result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4571061da546Spatrick id_cstr);
4572061da546Spatrick return false;
4573061da546Spatrick }
4574061da546Spatrick
4575061da546Spatrick Stream *output_stream_p = nullptr;
4576061da546Spatrick std::unique_ptr<Stream> output_stream_storage;
4577061da546Spatrick
4578061da546Spatrick const FileSpec &outfile_spec =
4579061da546Spatrick m_options.m_outfile; // Dump allocation to file instead
4580061da546Spatrick if (outfile_spec) {
4581061da546Spatrick // Open output file
4582061da546Spatrick std::string path = outfile_spec.GetPath();
4583*f6aab3d8Srobert auto file = FileSystem::Instance().Open(outfile_spec,
4584*f6aab3d8Srobert File::eOpenOptionWriteOnly |
4585*f6aab3d8Srobert File::eOpenOptionCanCreate);
4586061da546Spatrick if (file) {
4587061da546Spatrick output_stream_storage =
4588061da546Spatrick std::make_unique<StreamFile>(std::move(file.get()));
4589061da546Spatrick output_stream_p = output_stream_storage.get();
4590061da546Spatrick result.GetOutputStream().Printf("Results written to '%s'",
4591061da546Spatrick path.c_str());
4592061da546Spatrick result.GetOutputStream().EOL();
4593061da546Spatrick } else {
4594061da546Spatrick std::string error = llvm::toString(file.takeError());
4595061da546Spatrick result.AppendErrorWithFormat("Couldn't open file '%s': %s",
4596061da546Spatrick path.c_str(), error.c_str());
4597061da546Spatrick return false;
4598061da546Spatrick }
4599061da546Spatrick } else
4600061da546Spatrick output_stream_p = &result.GetOutputStream();
4601061da546Spatrick
4602061da546Spatrick assert(output_stream_p != nullptr);
4603061da546Spatrick bool dumped =
4604061da546Spatrick runtime->DumpAllocation(*output_stream_p, m_exe_ctx.GetFramePtr(), id);
4605061da546Spatrick
4606061da546Spatrick if (dumped)
4607061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4608061da546Spatrick else
4609061da546Spatrick result.SetStatus(eReturnStatusFailed);
4610061da546Spatrick
4611061da546Spatrick return true;
4612061da546Spatrick }
4613061da546Spatrick
4614061da546Spatrick private:
4615061da546Spatrick CommandOptions m_options;
4616061da546Spatrick };
4617061da546Spatrick
4618061da546Spatrick static constexpr OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
4619061da546Spatrick {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
4620061da546Spatrick {}, 0, eArgTypeIndex,
4621061da546Spatrick "Only show details of a single allocation with specified id."}};
4622061da546Spatrick
4623061da546Spatrick class CommandObjectRenderScriptRuntimeAllocationList
4624061da546Spatrick : public CommandObjectParsed {
4625061da546Spatrick public:
CommandObjectRenderScriptRuntimeAllocationList(CommandInterpreter & interpreter)4626061da546Spatrick CommandObjectRenderScriptRuntimeAllocationList(
4627061da546Spatrick CommandInterpreter &interpreter)
4628061da546Spatrick : CommandObjectParsed(
4629061da546Spatrick interpreter, "renderscript allocation list",
4630061da546Spatrick "List renderscript allocations and their information.",
4631061da546Spatrick "renderscript allocation list",
4632061da546Spatrick eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4633061da546Spatrick m_options() {}
4634061da546Spatrick
4635061da546Spatrick ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4636061da546Spatrick
GetOptions()4637061da546Spatrick Options *GetOptions() override { return &m_options; }
4638061da546Spatrick
4639061da546Spatrick class CommandOptions : public Options {
4640061da546Spatrick public:
CommandOptions()4641be691f3bSpatrick CommandOptions() : Options() {}
4642061da546Spatrick
4643061da546Spatrick ~CommandOptions() override = default;
4644061da546Spatrick
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * exe_ctx)4645061da546Spatrick Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4646061da546Spatrick ExecutionContext *exe_ctx) override {
4647061da546Spatrick Status err;
4648061da546Spatrick const int short_option = m_getopt_table[option_idx].val;
4649061da546Spatrick
4650061da546Spatrick switch (short_option) {
4651061da546Spatrick case 'i':
4652061da546Spatrick if (option_arg.getAsInteger(0, m_id))
4653061da546Spatrick err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4654061da546Spatrick short_option);
4655061da546Spatrick break;
4656061da546Spatrick default:
4657061da546Spatrick err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4658061da546Spatrick break;
4659061da546Spatrick }
4660061da546Spatrick return err;
4661061da546Spatrick }
4662061da546Spatrick
OptionParsingStarting(ExecutionContext * exe_ctx)4663061da546Spatrick void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
4664061da546Spatrick
GetDefinitions()4665061da546Spatrick llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4666*f6aab3d8Srobert return llvm::ArrayRef(g_renderscript_runtime_alloc_list_options);
4667061da546Spatrick }
4668061da546Spatrick
4669be691f3bSpatrick uint32_t m_id = 0;
4670061da546Spatrick };
4671061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4672061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4673061da546Spatrick RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4674061da546Spatrick m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4675061da546Spatrick eLanguageTypeExtRenderScript));
4676061da546Spatrick runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4677061da546Spatrick m_options.m_id);
4678061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4679061da546Spatrick return true;
4680061da546Spatrick }
4681061da546Spatrick
4682061da546Spatrick private:
4683061da546Spatrick CommandOptions m_options;
4684061da546Spatrick };
4685061da546Spatrick
4686061da546Spatrick class CommandObjectRenderScriptRuntimeAllocationLoad
4687061da546Spatrick : public CommandObjectParsed {
4688061da546Spatrick public:
CommandObjectRenderScriptRuntimeAllocationLoad(CommandInterpreter & interpreter)4689061da546Spatrick CommandObjectRenderScriptRuntimeAllocationLoad(
4690061da546Spatrick CommandInterpreter &interpreter)
4691061da546Spatrick : CommandObjectParsed(
4692061da546Spatrick interpreter, "renderscript allocation load",
4693061da546Spatrick "Loads renderscript allocation contents from a file.",
4694061da546Spatrick "renderscript allocation load <ID> <filename>",
4695*f6aab3d8Srobert eCommandRequiresProcess | eCommandProcessMustBeLaunched) {
4696*f6aab3d8Srobert CommandArgumentData id_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
4697*f6aab3d8Srobert CommandArgumentData name_arg{eArgTypeFilename, eArgRepeatPlain};
4698*f6aab3d8Srobert m_arguments.push_back({id_arg});
4699*f6aab3d8Srobert m_arguments.push_back({name_arg});
4700*f6aab3d8Srobert }
4701061da546Spatrick
4702061da546Spatrick ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
4703061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4704061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4705061da546Spatrick const size_t argc = command.GetArgumentCount();
4706061da546Spatrick if (argc != 2) {
4707061da546Spatrick result.AppendErrorWithFormat(
4708061da546Spatrick "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4709061da546Spatrick m_cmd_name.c_str());
4710061da546Spatrick return false;
4711061da546Spatrick }
4712061da546Spatrick
4713061da546Spatrick RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4714061da546Spatrick m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4715061da546Spatrick eLanguageTypeExtRenderScript));
4716061da546Spatrick
4717061da546Spatrick const char *id_cstr = command.GetArgumentAtIndex(0);
4718*f6aab3d8Srobert uint32_t id;
4719*f6aab3d8Srobert if (!llvm::to_integer(id_cstr, id)) {
4720061da546Spatrick result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4721061da546Spatrick id_cstr);
4722061da546Spatrick return false;
4723061da546Spatrick }
4724061da546Spatrick
4725061da546Spatrick const char *path = command.GetArgumentAtIndex(1);
4726061da546Spatrick bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
4727061da546Spatrick m_exe_ctx.GetFramePtr());
4728061da546Spatrick
4729061da546Spatrick if (loaded)
4730061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4731061da546Spatrick else
4732061da546Spatrick result.SetStatus(eReturnStatusFailed);
4733061da546Spatrick
4734061da546Spatrick return true;
4735061da546Spatrick }
4736061da546Spatrick };
4737061da546Spatrick
4738061da546Spatrick class CommandObjectRenderScriptRuntimeAllocationSave
4739061da546Spatrick : public CommandObjectParsed {
4740061da546Spatrick public:
CommandObjectRenderScriptRuntimeAllocationSave(CommandInterpreter & interpreter)4741061da546Spatrick CommandObjectRenderScriptRuntimeAllocationSave(
4742061da546Spatrick CommandInterpreter &interpreter)
4743061da546Spatrick : CommandObjectParsed(interpreter, "renderscript allocation save",
4744061da546Spatrick "Write renderscript allocation contents to a file.",
4745061da546Spatrick "renderscript allocation save <ID> <filename>",
4746061da546Spatrick eCommandRequiresProcess |
4747*f6aab3d8Srobert eCommandProcessMustBeLaunched) {
4748*f6aab3d8Srobert CommandArgumentData id_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
4749*f6aab3d8Srobert CommandArgumentData name_arg{eArgTypeFilename, eArgRepeatPlain};
4750*f6aab3d8Srobert m_arguments.push_back({id_arg});
4751*f6aab3d8Srobert m_arguments.push_back({name_arg});
4752*f6aab3d8Srobert }
4753061da546Spatrick
4754061da546Spatrick ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
4755061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4756061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4757061da546Spatrick const size_t argc = command.GetArgumentCount();
4758061da546Spatrick if (argc != 2) {
4759061da546Spatrick result.AppendErrorWithFormat(
4760061da546Spatrick "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4761061da546Spatrick m_cmd_name.c_str());
4762061da546Spatrick return false;
4763061da546Spatrick }
4764061da546Spatrick
4765061da546Spatrick RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4766061da546Spatrick m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4767061da546Spatrick eLanguageTypeExtRenderScript));
4768061da546Spatrick
4769061da546Spatrick const char *id_cstr = command.GetArgumentAtIndex(0);
4770*f6aab3d8Srobert uint32_t id;
4771*f6aab3d8Srobert if (!llvm::to_integer(id_cstr, id)) {
4772061da546Spatrick result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4773061da546Spatrick id_cstr);
4774061da546Spatrick return false;
4775061da546Spatrick }
4776061da546Spatrick
4777061da546Spatrick const char *path = command.GetArgumentAtIndex(1);
4778061da546Spatrick bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
4779061da546Spatrick m_exe_ctx.GetFramePtr());
4780061da546Spatrick
4781061da546Spatrick if (saved)
4782061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4783061da546Spatrick else
4784061da546Spatrick result.SetStatus(eReturnStatusFailed);
4785061da546Spatrick
4786061da546Spatrick return true;
4787061da546Spatrick }
4788061da546Spatrick };
4789061da546Spatrick
4790061da546Spatrick class CommandObjectRenderScriptRuntimeAllocationRefresh
4791061da546Spatrick : public CommandObjectParsed {
4792061da546Spatrick public:
CommandObjectRenderScriptRuntimeAllocationRefresh(CommandInterpreter & interpreter)4793061da546Spatrick CommandObjectRenderScriptRuntimeAllocationRefresh(
4794061da546Spatrick CommandInterpreter &interpreter)
4795061da546Spatrick : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4796061da546Spatrick "Recomputes the details of all allocations.",
4797061da546Spatrick "renderscript allocation refresh",
4798061da546Spatrick eCommandRequiresProcess |
4799061da546Spatrick eCommandProcessMustBeLaunched) {}
4800061da546Spatrick
4801061da546Spatrick ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
4802061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4803061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4804061da546Spatrick RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4805061da546Spatrick m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4806061da546Spatrick eLanguageTypeExtRenderScript));
4807061da546Spatrick
4808061da546Spatrick bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4809061da546Spatrick m_exe_ctx.GetFramePtr());
4810061da546Spatrick
4811061da546Spatrick if (success) {
4812061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4813061da546Spatrick return true;
4814061da546Spatrick } else {
4815061da546Spatrick result.SetStatus(eReturnStatusFailed);
4816061da546Spatrick return false;
4817061da546Spatrick }
4818061da546Spatrick }
4819061da546Spatrick };
4820061da546Spatrick
4821061da546Spatrick class CommandObjectRenderScriptRuntimeAllocation
4822061da546Spatrick : public CommandObjectMultiword {
4823061da546Spatrick public:
CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter & interpreter)4824061da546Spatrick CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4825061da546Spatrick : CommandObjectMultiword(
4826061da546Spatrick interpreter, "renderscript allocation",
4827061da546Spatrick "Commands that deal with RenderScript allocations.", nullptr) {
4828061da546Spatrick LoadSubCommand(
4829061da546Spatrick "list",
4830061da546Spatrick CommandObjectSP(
4831061da546Spatrick new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4832061da546Spatrick LoadSubCommand(
4833061da546Spatrick "dump",
4834061da546Spatrick CommandObjectSP(
4835061da546Spatrick new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4836061da546Spatrick LoadSubCommand(
4837061da546Spatrick "save",
4838061da546Spatrick CommandObjectSP(
4839061da546Spatrick new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4840061da546Spatrick LoadSubCommand(
4841061da546Spatrick "load",
4842061da546Spatrick CommandObjectSP(
4843061da546Spatrick new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4844061da546Spatrick LoadSubCommand(
4845061da546Spatrick "refresh",
4846061da546Spatrick CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4847061da546Spatrick interpreter)));
4848061da546Spatrick }
4849061da546Spatrick
4850061da546Spatrick ~CommandObjectRenderScriptRuntimeAllocation() override = default;
4851061da546Spatrick };
4852061da546Spatrick
4853061da546Spatrick class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
4854061da546Spatrick public:
CommandObjectRenderScriptRuntimeStatus(CommandInterpreter & interpreter)4855061da546Spatrick CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4856061da546Spatrick : CommandObjectParsed(interpreter, "renderscript status",
4857061da546Spatrick "Displays current RenderScript runtime status.",
4858061da546Spatrick "renderscript status",
4859061da546Spatrick eCommandRequiresProcess |
4860061da546Spatrick eCommandProcessMustBeLaunched) {}
4861061da546Spatrick
4862061da546Spatrick ~CommandObjectRenderScriptRuntimeStatus() override = default;
4863061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4864061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4865061da546Spatrick RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4866061da546Spatrick m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4867061da546Spatrick eLanguageTypeExtRenderScript));
4868061da546Spatrick runtime->DumpStatus(result.GetOutputStream());
4869061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4870061da546Spatrick return true;
4871061da546Spatrick }
4872061da546Spatrick };
4873061da546Spatrick
4874061da546Spatrick class CommandObjectRenderScriptRuntimeReduction
4875061da546Spatrick : public CommandObjectMultiword {
4876061da546Spatrick public:
CommandObjectRenderScriptRuntimeReduction(CommandInterpreter & interpreter)4877061da546Spatrick CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
4878061da546Spatrick : CommandObjectMultiword(interpreter, "renderscript reduction",
4879061da546Spatrick "Commands that handle general reduction kernels",
4880061da546Spatrick nullptr) {
4881061da546Spatrick LoadSubCommand(
4882061da546Spatrick "breakpoint",
4883061da546Spatrick CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
4884061da546Spatrick interpreter)));
4885061da546Spatrick }
4886061da546Spatrick ~CommandObjectRenderScriptRuntimeReduction() override = default;
4887061da546Spatrick };
4888061da546Spatrick
4889061da546Spatrick class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
4890061da546Spatrick public:
CommandObjectRenderScriptRuntime(CommandInterpreter & interpreter)4891061da546Spatrick CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
4892061da546Spatrick : CommandObjectMultiword(
4893061da546Spatrick interpreter, "renderscript",
4894061da546Spatrick "Commands for operating on the RenderScript runtime.",
4895061da546Spatrick "renderscript <subcommand> [<subcommand-options>]") {
4896061da546Spatrick LoadSubCommand(
4897061da546Spatrick "module", CommandObjectSP(
4898061da546Spatrick new CommandObjectRenderScriptRuntimeModule(interpreter)));
4899061da546Spatrick LoadSubCommand(
4900061da546Spatrick "status", CommandObjectSP(
4901061da546Spatrick new CommandObjectRenderScriptRuntimeStatus(interpreter)));
4902061da546Spatrick LoadSubCommand(
4903061da546Spatrick "kernel", CommandObjectSP(
4904061da546Spatrick new CommandObjectRenderScriptRuntimeKernel(interpreter)));
4905061da546Spatrick LoadSubCommand("context",
4906061da546Spatrick CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
4907061da546Spatrick interpreter)));
4908061da546Spatrick LoadSubCommand(
4909061da546Spatrick "allocation",
4910061da546Spatrick CommandObjectSP(
4911061da546Spatrick new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
4912061da546Spatrick LoadSubCommand("scriptgroup",
4913061da546Spatrick NewCommandObjectRenderScriptScriptGroup(interpreter));
4914061da546Spatrick LoadSubCommand(
4915061da546Spatrick "reduction",
4916061da546Spatrick CommandObjectSP(
4917061da546Spatrick new CommandObjectRenderScriptRuntimeReduction(interpreter)));
4918061da546Spatrick }
4919061da546Spatrick
4920061da546Spatrick ~CommandObjectRenderScriptRuntime() override = default;
4921061da546Spatrick };
4922061da546Spatrick
Initiate()4923061da546Spatrick void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
4924061da546Spatrick
RenderScriptRuntime(Process * process)4925061da546Spatrick RenderScriptRuntime::RenderScriptRuntime(Process *process)
4926061da546Spatrick : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
4927061da546Spatrick m_debuggerPresentFlagged(false), m_breakAllKernels(false),
4928061da546Spatrick m_ir_passes(nullptr) {
4929061da546Spatrick ModulesDidLoad(process->GetTarget().GetImages());
4930061da546Spatrick }
4931061da546Spatrick
GetCommandObject(lldb_private::CommandInterpreter & interpreter)4932061da546Spatrick lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
4933061da546Spatrick lldb_private::CommandInterpreter &interpreter) {
4934061da546Spatrick return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
4935061da546Spatrick }
4936061da546Spatrick
4937061da546Spatrick RenderScriptRuntime::~RenderScriptRuntime() = default;
4938