blob: 08f375c974c2cb5e830bdb291be451a8ecd89ca0 [file] [log] [blame]
Colin Riley5ec532a2015-04-09 16:49:25 +00001//===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Eugene Zelenko222b9372015-10-27 00:45:06 +000010// C Includes
11// C++ Includes
12// Other libraries and framework includes
13// Project includes
Colin Riley5ec532a2015-04-09 16:49:25 +000014#include "RenderScriptRuntime.h"
15
Aidan Doddsb3f7f692016-01-28 16:39:44 +000016#include "lldb/Breakpoint/StoppointCallbackContext.h"
Colin Riley5ec532a2015-04-09 16:49:25 +000017#include "lldb/Core/ConstString.h"
18#include "lldb/Core/Debugger.h"
19#include "lldb/Core/Error.h"
20#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
Ewan Crawford018f5a7e2015-10-26 14:04:37 +000022#include "lldb/Core/RegularExpression.h"
Aidan Doddsb3f7f692016-01-28 16:39:44 +000023#include "lldb/Core/ValueObjectVariable.h"
Ewan Crawford8b244e22015-11-30 10:29:49 +000024#include "lldb/DataFormatters/DumpValueObjectOptions.h"
Aidan Doddsb3f7f692016-01-28 16:39:44 +000025#include "lldb/Expression/UserExpression.h"
Ewan Crawforda0f08672015-10-16 08:28:47 +000026#include "lldb/Host/StringConvert.h"
Aidan Doddsb3f7f692016-01-28 16:39:44 +000027#include "lldb/Interpreter/Args.h"
28#include "lldb/Interpreter/CommandInterpreter.h"
29#include "lldb/Interpreter/CommandObjectMultiword.h"
30#include "lldb/Interpreter/CommandReturnObject.h"
31#include "lldb/Interpreter/Options.h"
Colin Riley5ec532a2015-04-09 16:49:25 +000032#include "lldb/Symbol/Symbol.h"
Colin Riley4640cde2015-06-01 18:23:41 +000033#include "lldb/Symbol/Type.h"
Aidan Doddsb3f7f692016-01-28 16:39:44 +000034#include "lldb/Symbol/VariableList.h"
Colin Riley5ec532a2015-04-09 16:49:25 +000035#include "lldb/Target/Process.h"
Aidan Doddsb3f7f692016-01-28 16:39:44 +000036#include "lldb/Target/RegisterContext.h"
Colin Riley5ec532a2015-04-09 16:49:25 +000037#include "lldb/Target/Target.h"
Ewan Crawford018f5a7e2015-10-26 14:04:37 +000038#include "lldb/Target/Thread.h"
Colin Riley5ec532a2015-04-09 16:49:25 +000039
40using namespace lldb;
41using namespace lldb_private;
Ewan Crawford98156582015-09-04 08:56:52 +000042using namespace lldb_renderscript;
Colin Riley5ec532a2015-04-09 16:49:25 +000043
Aidan Doddsb3f7f692016-01-28 16:39:44 +000044namespace
45{
Ewan Crawford78f339d2015-09-21 10:53:18 +000046
47// The empirical_type adds a basic level of validation to arbitrary data
48// allowing us to track if data has been discovered and stored or not.
49// An empirical_type will be marked as valid only if it has been explicitly assigned to.
Aidan Doddsb3f7f692016-01-28 16:39:44 +000050template <typename type_t> class empirical_type
Ewan Crawford78f339d2015-09-21 10:53:18 +000051{
Eugene Zelenko222b9372015-10-27 00:45:06 +000052public:
Ewan Crawford78f339d2015-09-21 10:53:18 +000053 // Ctor. Contents is invalid when constructed.
Aidan Doddsb3f7f692016-01-28 16:39:44 +000054 empirical_type() : valid(false) {}
Ewan Crawford78f339d2015-09-21 10:53:18 +000055
56 // Return true and copy contents to out if valid, else return false.
Aidan Doddsb3f7f692016-01-28 16:39:44 +000057 bool
58 get(type_t &out) const
Ewan Crawford78f339d2015-09-21 10:53:18 +000059 {
60 if (valid)
61 out = data;
62 return valid;
63 }
64
65 // Return a pointer to the contents or nullptr if it was not valid.
Aidan Doddsb3f7f692016-01-28 16:39:44 +000066 const type_t *
67 get() const
Ewan Crawford78f339d2015-09-21 10:53:18 +000068 {
69 return valid ? &data : nullptr;
70 }
71
72 // Assign data explicitly.
Aidan Doddsb3f7f692016-01-28 16:39:44 +000073 void
74 set(const type_t in)
Ewan Crawford78f339d2015-09-21 10:53:18 +000075 {
76 data = in;
77 valid = true;
78 }
79
80 // Mark contents as invalid.
Aidan Doddsb3f7f692016-01-28 16:39:44 +000081 void
82 invalidate()
Ewan Crawford78f339d2015-09-21 10:53:18 +000083 {
84 valid = false;
85 }
86
87 // Returns true if this type contains valid data.
Aidan Doddsb3f7f692016-01-28 16:39:44 +000088 bool
89 isValid() const
Ewan Crawford78f339d2015-09-21 10:53:18 +000090 {
91 return valid;
92 }
93
94 // Assignment operator.
Aidan Doddsb3f7f692016-01-28 16:39:44 +000095 empirical_type<type_t> &
96 operator=(const type_t in)
Ewan Crawford78f339d2015-09-21 10:53:18 +000097 {
98 set(in);
99 return *this;
100 }
101
102 // Dereference operator returns contents.
103 // Warning: Will assert if not valid so use only when you know data is valid.
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000104 const type_t &operator*() const
Ewan Crawford78f339d2015-09-21 10:53:18 +0000105 {
106 assert(valid);
107 return data;
108 }
109
Eugene Zelenko222b9372015-10-27 00:45:06 +0000110protected:
Ewan Crawford78f339d2015-09-21 10:53:18 +0000111 bool valid;
112 type_t data;
113};
114
Aidan Doddsf4786782016-02-11 15:16:37 +0000115// ArgItem is used by the GetArgs() function when reading function arguments from the target.
116struct ArgItem
117{
118 enum
119 {
120 ePointer,
121 eInt32,
122 eInt64,
123 eLong,
124 eBool
125 } type;
126
127 uint64_t value;
128
129 explicit operator uint64_t() const { return value; }
130};
131
132// Context structure to be passed into GetArgsXXX(), argument reading functions below.
133struct GetArgsCtx
134{
135 RegisterContext *reg_ctx;
136 Process *process;
137};
138
139bool
140GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
141{
142 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
143
144 // get the current stack pointer
145 uint64_t sp = ctx.reg_ctx->GetSP();
146
147 for (size_t i = 0; i < num_args; ++i)
148 {
149 ArgItem &arg = arg_list[i];
150 // advance up the stack by one argument
151 sp += sizeof(uint32_t);
152 // get the argument type size
153 size_t arg_size = sizeof(uint32_t);
154 // read the argument from memory
155 arg.value = 0;
156 Error error;
157 size_t read = ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), error);
158 if (read != arg_size || !error.Success())
159 {
160 if (log)
161 log->Printf("%s - error reading argument: %" PRIu64 " '%s'", __FUNCTION__, uint64_t(i),
162 error.AsCString());
163 return false;
164 }
165 }
166 return true;
167}
168
169bool
170GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
171{
172 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
173
174 // number of arguments passed in registers
175 static const uint32_t c_args_in_reg = 6;
176 // register passing order
Saleem Abdulrasool1ee07252016-02-15 21:50:28 +0000177 static const std::array<const char *, c_args_in_reg> c_reg_names{{"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
Aidan Doddsf4786782016-02-11 15:16:37 +0000178 // argument type to size mapping
Saleem Abdulrasool1ee07252016-02-15 21:50:28 +0000179 static const std::array<size_t, 5> arg_size{{
Aidan Doddsf4786782016-02-11 15:16:37 +0000180 8, // ePointer,
181 4, // eInt32,
182 8, // eInt64,
183 8, // eLong,
184 4, // eBool,
Saleem Abdulrasool1ee07252016-02-15 21:50:28 +0000185 }};
Aidan Doddsf4786782016-02-11 15:16:37 +0000186
187 // get the current stack pointer
188 uint64_t sp = ctx.reg_ctx->GetSP();
189 // step over the return address
190 sp += sizeof(uint64_t);
191
192 // check the stack alignment was correct (16 byte aligned)
193 if ((sp & 0xf) != 0x0)
194 {
195 if (log)
196 log->Printf("%s - stack misaligned", __FUNCTION__);
197 return false;
198 }
199
200 // find the start of arguments on the stack
201 uint64_t sp_offset = 0;
202 for (uint32_t i = c_args_in_reg; i < num_args; ++i)
203 {
204 sp_offset += arg_size[arg_list[i].type];
205 }
206 // round up to multiple of 16
207 sp_offset = (sp_offset + 0xf) & 0xf;
208 sp += sp_offset;
209
210 for (size_t i = 0; i < num_args; ++i)
211 {
212 bool success = false;
213 ArgItem &arg = arg_list[i];
214 // arguments passed in registers
215 if (i < c_args_in_reg)
216 {
217 const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoByName(c_reg_names[i]);
218 RegisterValue rVal;
219 if (ctx.reg_ctx->ReadRegister(rArg, rVal))
220 arg.value = rVal.GetAsUInt64(0, &success);
221 }
222 // arguments passed on the stack
223 else
224 {
225 // get the argument type size
226 const size_t size = arg_size[arg_list[i].type];
227 // read the argument from memory
228 arg.value = 0;
229 // note: due to little endian layout reading 4 or 8 bytes will give the correct value.
230 Error error;
231 size_t read = ctx.process->ReadMemory(sp, &arg.value, size, error);
232 success = (error.Success() && read==size);
233 // advance past this argument
234 sp -= size;
235 }
236 // fail if we couldn't read this argument
237 if (!success)
238 {
239 if (log)
240 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__, uint64_t(i));
241 return false;
242 }
243 }
244 return true;
245}
246
247bool
248GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
249{
250 // number of arguments passed in registers
251 static const uint32_t c_args_in_reg = 4;
252
253 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
254
255 // get the current stack pointer
256 uint64_t sp = ctx.reg_ctx->GetSP();
257
258 for (size_t i = 0; i < num_args; ++i)
259 {
260 bool success = false;
261 ArgItem &arg = arg_list[i];
262 // arguments passed in registers
263 if (i < c_args_in_reg)
264 {
265 const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
266 RegisterValue rVal;
267 if (ctx.reg_ctx->ReadRegister(rArg, rVal))
268 arg.value = rVal.GetAsUInt32(0, &success);
269 }
270 // arguments passed on the stack
271 else
272 {
273 // get the argument type size
274 const size_t arg_size = sizeof(uint32_t);
275 // clear all 64bits
276 arg.value = 0;
277 // read this argument from memory
278 Error error;
279 size_t bytes_read = ctx.process->ReadMemory(sp, &arg.value, arg_size, error);
280 success = (error.Success() && bytes_read == arg_size);
281 // advance the stack pointer
282 sp += sizeof(uint32_t);
283 }
284 // fail if we couldn't read this argument
285 if (!success)
286 {
287 if (log)
288 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__, uint64_t(i));
289 return false;
290 }
291 }
292 return true;
293}
294
295bool
296GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
297{
298 // number of arguments passed in registers
299 static const uint32_t c_args_in_reg = 8;
300
301 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
302
303 for (size_t i = 0; i < num_args; ++i)
304 {
305 bool success = false;
306 ArgItem &arg = arg_list[i];
307 // arguments passed in registers
308 if (i < c_args_in_reg)
309 {
310 const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
311 RegisterValue rVal;
312 if (ctx.reg_ctx->ReadRegister(rArg, rVal))
313 arg.value = rVal.GetAsUInt64(0, &success);
314 }
315 // arguments passed on the stack
316 else
317 {
318 if (log)
319 log->Printf("%s - reading arguments spilled to stack not implemented", __FUNCTION__);
320 }
321 // fail if we couldn't read this argument
322 if (!success)
323 {
324 if (log)
325 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__,
326 uint64_t(i));
327 return false;
328 }
329 }
330 return true;
331}
332
333bool
334GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
335{
336 // number of arguments passed in registers
337 static const uint32_t c_args_in_reg = 4;
338 // register file offset to first argument
339 static const uint32_t c_reg_offset = 4;
340
341 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
342
343 for (size_t i = 0; i < num_args; ++i)
344 {
345 bool success = false;
346 ArgItem &arg = arg_list[i];
347 // arguments passed in registers
348 if (i < c_args_in_reg)
349 {
350 const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i + c_reg_offset);
351 RegisterValue rVal;
352 if (ctx.reg_ctx->ReadRegister(rArg, rVal))
353 arg.value = rVal.GetAsUInt64(0, &success);
354 }
355 // arguments passed on the stack
356 else
357 {
358 if (log)
359 log->Printf("%s - reading arguments spilled to stack not implemented.", __FUNCTION__);
360 }
361 // fail if we couldn't read this argument
362 if (!success)
363 {
364 if (log)
365 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__, uint64_t(i));
366 return false;
367 }
368 }
369 return true;
370}
371
372bool
373GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
374{
375 // number of arguments passed in registers
376 static const uint32_t c_args_in_reg = 8;
377 // register file offset to first argument
378 static const uint32_t c_reg_offset = 4;
379
380 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
381
382 // get the current stack pointer
383 uint64_t sp = ctx.reg_ctx->GetSP();
384
385 for (size_t i = 0; i < num_args; ++i)
386 {
387 bool success = false;
388 ArgItem &arg = arg_list[i];
389 // arguments passed in registers
390 if (i < c_args_in_reg)
391 {
392 const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i + c_reg_offset);
393 RegisterValue rVal;
394 if (ctx.reg_ctx->ReadRegister(rArg, rVal))
Aidan Dodds72f77522016-02-11 17:17:12 +0000395 arg.value = rVal.GetAsUInt64(0, &success);
Aidan Doddsf4786782016-02-11 15:16:37 +0000396 }
397 // arguments passed on the stack
398 else
399 {
400 // get the argument type size
401 const size_t arg_size = sizeof(uint64_t);
402 // clear all 64bits
403 arg.value = 0;
404 // read this argument from memory
405 Error error;
406 size_t bytes_read = ctx.process->ReadMemory(sp, &arg.value, arg_size, error);
407 success = (error.Success() && bytes_read == arg_size);
408 // advance the stack pointer
409 sp += arg_size;
410 }
411 // fail if we couldn't read this argument
412 if (!success)
413 {
414 if (log)
415 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__, uint64_t(i));
416 return false;
417 }
418 }
419 return true;
420}
421
422bool
423GetArgs(ExecutionContext &context, ArgItem *arg_list, size_t num_args)
424{
425 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
426
427 // verify that we have a target
428 if (!context.GetTargetPtr())
429 {
430 if (log)
431 log->Printf("%s - invalid target", __FUNCTION__);
432 return false;
433 }
434
435 GetArgsCtx ctx = {context.GetRegisterContext(), context.GetProcessPtr()};
436 assert(ctx.reg_ctx && ctx.process);
437
438 // dispatch based on architecture
439 switch (context.GetTargetPtr()->GetArchitecture().GetMachine())
440 {
441 case llvm::Triple::ArchType::x86:
442 return GetArgsX86(ctx, arg_list, num_args);
443
444 case llvm::Triple::ArchType::x86_64:
445 return GetArgsX86_64(ctx, arg_list, num_args);
446
447 case llvm::Triple::ArchType::arm:
448 return GetArgsArm(ctx, arg_list, num_args);
449
450 case llvm::Triple::ArchType::aarch64:
451 return GetArgsAarch64(ctx, arg_list, num_args);
452
453 case llvm::Triple::ArchType::mipsel:
454 return GetArgsMipsel(ctx, arg_list, num_args);
455
456 case llvm::Triple::ArchType::mips64el:
457 return GetArgsMips64el(ctx, arg_list, num_args);
458
459 default:
460 // unsupported architecture
461 if (log)
462 {
463 log->Printf("%s - architecture not supported: '%s'", __FUNCTION__,
464 context.GetTargetRef().GetArchitecture().GetArchitectureName());
465 }
466 return false;
467 }
468}
Eugene Zelenko222b9372015-10-27 00:45:06 +0000469} // anonymous namespace
Ewan Crawford78f339d2015-09-21 10:53:18 +0000470
471// The ScriptDetails class collects data associated with a single script instance.
472struct RenderScriptRuntime::ScriptDetails
473{
Eugene Zelenko222b9372015-10-27 00:45:06 +0000474 ~ScriptDetails() = default;
Ewan Crawford78f339d2015-09-21 10:53:18 +0000475
476 enum ScriptType
477 {
478 eScript,
479 eScriptC
480 };
481
482 // The derived type of the script.
483 empirical_type<ScriptType> type;
484 // The name of the original source file.
485 empirical_type<std::string> resName;
486 // Path to script .so file on the device.
487 empirical_type<std::string> scriptDyLib;
488 // Directory where kernel objects are cached on device.
489 empirical_type<std::string> cacheDir;
490 // Pointer to the context which owns this script.
491 empirical_type<lldb::addr_t> context;
492 // Pointer to the script object itself.
493 empirical_type<lldb::addr_t> script;
494};
495
Ewan Crawford8b244e22015-11-30 10:29:49 +0000496// This Element class represents the Element object in RS,
497// defining the type associated with an Allocation.
498struct RenderScriptRuntime::Element
499{
500 // Taken from rsDefines.h
501 enum DataKind
502 {
503 RS_KIND_USER,
504 RS_KIND_PIXEL_L = 7,
505 RS_KIND_PIXEL_A,
506 RS_KIND_PIXEL_LA,
507 RS_KIND_PIXEL_RGB,
508 RS_KIND_PIXEL_RGBA,
509 RS_KIND_PIXEL_DEPTH,
510 RS_KIND_PIXEL_YUV,
511 RS_KIND_INVALID = 100
512 };
513
514 // Taken from rsDefines.h
515 enum DataType
516 {
517 RS_TYPE_NONE = 0,
518 RS_TYPE_FLOAT_16,
519 RS_TYPE_FLOAT_32,
520 RS_TYPE_FLOAT_64,
521 RS_TYPE_SIGNED_8,
522 RS_TYPE_SIGNED_16,
523 RS_TYPE_SIGNED_32,
524 RS_TYPE_SIGNED_64,
525 RS_TYPE_UNSIGNED_8,
526 RS_TYPE_UNSIGNED_16,
527 RS_TYPE_UNSIGNED_32,
528 RS_TYPE_UNSIGNED_64,
Ewan Crawford2e920712015-12-17 16:40:05 +0000529 RS_TYPE_BOOLEAN,
530
531 RS_TYPE_UNSIGNED_5_6_5,
532 RS_TYPE_UNSIGNED_5_5_5_1,
533 RS_TYPE_UNSIGNED_4_4_4_4,
534
535 RS_TYPE_MATRIX_4X4,
536 RS_TYPE_MATRIX_3X3,
537 RS_TYPE_MATRIX_2X2,
538
539 RS_TYPE_ELEMENT = 1000,
540 RS_TYPE_TYPE,
541 RS_TYPE_ALLOCATION,
542 RS_TYPE_SAMPLER,
543 RS_TYPE_SCRIPT,
544 RS_TYPE_MESH,
545 RS_TYPE_PROGRAM_FRAGMENT,
546 RS_TYPE_PROGRAM_VERTEX,
547 RS_TYPE_PROGRAM_RASTER,
548 RS_TYPE_PROGRAM_STORE,
549 RS_TYPE_FONT,
550
551 RS_TYPE_INVALID = 10000
Ewan Crawford8b244e22015-11-30 10:29:49 +0000552 };
553
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000554 std::vector<Element> children; // Child Element fields for structs
555 empirical_type<lldb::addr_t> element_ptr; // Pointer to the RS Element of the Type
556 empirical_type<DataType> type; // Type of each data pointer stored by the allocation
557 empirical_type<DataKind> type_kind; // Defines pixel type if Allocation is created from an image
558 empirical_type<uint32_t> type_vec_size; // Vector size of each data point, e.g '4' for uchar4
559 empirical_type<uint32_t> field_count; // Number of Subelements
560 empirical_type<uint32_t> datum_size; // Size of a single Element with padding
561 empirical_type<uint32_t> padding; // Number of padding bytes
562 empirical_type<uint32_t> array_size; // Number of items in array, only needed for strucrs
563 ConstString type_name; // Name of type, only needed for structs
Ewan Crawford8b244e22015-11-30 10:29:49 +0000564
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000565 static const ConstString &
566 GetFallbackStructName(); // Print this as the type name of a struct Element
567 // If we can't resolve the actual struct name
Ewan Crawford8b590622015-12-10 10:20:39 +0000568
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000569 bool
570 shouldRefresh() const
Ewan Crawford8b590622015-12-10 10:20:39 +0000571 {
572 const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
573 const bool valid_type = type.isValid() && type_vec_size.isValid() && type_kind.isValid();
574 return !valid_ptr || !valid_type || !datum_size.isValid();
575 }
Ewan Crawford8b244e22015-11-30 10:29:49 +0000576};
577
Ewan Crawford78f339d2015-09-21 10:53:18 +0000578// This AllocationDetails class collects data associated with a single
579// allocation instance.
580struct RenderScriptRuntime::AllocationDetails
581{
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000582 struct Dimension
Ewan Crawford78f339d2015-09-21 10:53:18 +0000583 {
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000584 uint32_t dim_1;
585 uint32_t dim_2;
586 uint32_t dim_3;
587 uint32_t cubeMap;
588
589 Dimension()
590 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000591 dim_1 = 0;
592 dim_2 = 0;
593 dim_3 = 0;
594 cubeMap = 0;
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000595 }
Ewan Crawford78f339d2015-09-21 10:53:18 +0000596 };
597
Ewan Crawford26e52a72016-01-07 10:19:09 +0000598 // The FileHeader struct specifies the header we use for writing allocations to a binary file.
599 // Our format begins with the ASCII characters "RSAD", identifying the file as an allocation dump.
600 // Member variables dims and hdr_size are then written consecutively, immediately followed by an instance of
601 // the ElementHeader struct. Because Elements can contain subelements, there may be more than one instance
602 // of the ElementHeader struct. With this first instance being the root element, and the other instances being
603 // the root's descendants. To identify which instances are an ElementHeader's children, each struct
604 // is immediately followed by a sequence of consecutive offsets to the start of its child structs.
605 // These offsets are 4 bytes in size, and the 0 offset signifies no more children.
Ewan Crawford55232f02015-10-21 08:50:42 +0000606 struct FileHeader
607 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000608 uint8_t ident[4]; // ASCII 'RSAD' identifying the file
609 uint32_t dims[3]; // Dimensions
610 uint16_t hdr_size; // Header size in bytes, including all element headers
Ewan Crawford26e52a72016-01-07 10:19:09 +0000611 };
612
613 struct ElementHeader
614 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000615 uint16_t type; // DataType enum
616 uint32_t kind; // DataKind enum
617 uint32_t element_size; // Size of a single element, including padding
618 uint16_t vector_size; // Vector width
619 uint32_t array_size; // Number of elements in array
Ewan Crawford55232f02015-10-21 08:50:42 +0000620 };
621
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000622 // Monotonically increasing from 1
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000623 static uint32_t ID;
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000624
625 // Maps Allocation DataType enum and vector size to printable strings
626 // using mapping from RenderScript numerical types summary documentation
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000627 static const char *RsDataTypeToString[][4];
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000628
629 // Maps Allocation DataKind enum to printable strings
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000630 static const char *RsDataKindToString[];
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000631
Ewan Crawforda0f08672015-10-16 08:28:47 +0000632 // Maps allocation types to format sizes for printing.
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000633 static const uint32_t RSTypeToFormat[][3];
Ewan Crawforda0f08672015-10-16 08:28:47 +0000634
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000635 // Give each allocation an ID as a way
636 // for commands to reference it.
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000637 const uint32_t id;
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000638
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000639 RenderScriptRuntime::Element element; // Allocation Element type
640 empirical_type<Dimension> dimension; // Dimensions of the Allocation
641 empirical_type<lldb::addr_t> address; // Pointer to address of the RS Allocation
642 empirical_type<lldb::addr_t> data_ptr; // Pointer to the data held by the Allocation
643 empirical_type<lldb::addr_t> type_ptr; // Pointer to the RS Type of the Allocation
644 empirical_type<lldb::addr_t> context; // Pointer to the RS Context of the Allocation
645 empirical_type<uint32_t> size; // Size of the allocation
646 empirical_type<uint32_t> stride; // Stride between rows of the allocation
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000647
648 // Give each allocation an id, so we can reference it in user commands.
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000649 AllocationDetails() : id(ID++) {}
Ewan Crawford8b590622015-12-10 10:20:39 +0000650
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000651 bool
652 shouldRefresh() const
Ewan Crawford8b590622015-12-10 10:20:39 +0000653 {
654 bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
655 valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
656 return !valid_ptrs || !dimension.isValid() || !size.isValid() || element.shouldRefresh();
657 }
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000658};
659
Adrian McCarthyfe06b5a2015-11-30 22:18:43 +0000660const ConstString &
661RenderScriptRuntime::Element::GetFallbackStructName()
662{
663 static const ConstString FallbackStructName("struct");
664 return FallbackStructName;
665}
Ewan Crawford8b244e22015-11-30 10:29:49 +0000666
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000667uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000668
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000669const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
670 "User",
671 "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7
672 "L Pixel", "A Pixel", "LA Pixel", "RGB Pixel",
673 "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000674
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000675const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000676 {"None", "None", "None", "None"},
677 {"half", "half2", "half3", "half4"},
678 {"float", "float2", "float3", "float4"},
679 {"double", "double2", "double3", "double4"},
680 {"char", "char2", "char3", "char4"},
681 {"short", "short2", "short3", "short4"},
682 {"int", "int2", "int3", "int4"},
683 {"long", "long2", "long3", "long4"},
684 {"uchar", "uchar2", "uchar3", "uchar4"},
685 {"ushort", "ushort2", "ushort3", "ushort4"},
686 {"uint", "uint2", "uint3", "uint4"},
687 {"ulong", "ulong2", "ulong3", "ulong4"},
Ewan Crawford2e920712015-12-17 16:40:05 +0000688 {"bool", "bool2", "bool3", "bool4"},
689 {"packed_565", "packed_565", "packed_565", "packed_565"},
690 {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
691 {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
692 {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
693 {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
694 {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
695
696 // Handlers
697 {"RS Element", "RS Element", "RS Element", "RS Element"},
698 {"RS Type", "RS Type", "RS Type", "RS Type"},
699 {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
700 {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
701 {"RS Script", "RS Script", "RS Script", "RS Script"},
702
703 // Deprecated
704 {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
705 {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment", "RS Program Fragment"},
706 {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex", "RS Program Vertex"},
707 {"RS Program Raster", "RS Program Raster", "RS Program Raster", "RS Program Raster"},
708 {"RS Program Store", "RS Program Store", "RS Program Store", "RS Program Store"},
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000709 {"RS Font", "RS Font", "RS Font", "RS Font"}};
Ewan Crawford78f339d2015-09-21 10:53:18 +0000710
Ewan Crawforda0f08672015-10-16 08:28:47 +0000711// Used as an index into the RSTypeToFormat array elements
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000712enum TypeToFormatIndex
713{
714 eFormatSingle = 0,
715 eFormatVector,
716 eElementSize
Ewan Crawforda0f08672015-10-16 08:28:47 +0000717};
718
719// { format enum of single element, format enum of element vector, size of element}
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000720const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
721 {eFormatHex, eFormatHex, 1}, // RS_TYPE_NONE
722 {eFormatFloat, eFormatVectorOfFloat16, 2}, // RS_TYPE_FLOAT_16
723 {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)}, // RS_TYPE_FLOAT_32
724 {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)}, // RS_TYPE_FLOAT_64
725 {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)}, // RS_TYPE_SIGNED_8
726 {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)}, // RS_TYPE_SIGNED_16
727 {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)}, // RS_TYPE_SIGNED_32
728 {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)}, // RS_TYPE_SIGNED_64
729 {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)}, // RS_TYPE_UNSIGNED_8
730 {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_16
731 {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)}, // RS_TYPE_UNSIGNED_32
732 {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)}, // RS_TYPE_UNSIGNED_64
733 {eFormatBoolean, eFormatBoolean, 1}, // RS_TYPE_BOOL
734 {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_5_6_5
735 {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_5_5_5_1
736 {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_4_4_4_4
Ewan Crawford2e920712015-12-17 16:40:05 +0000737 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16}, // RS_TYPE_MATRIX_4X4
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000738 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9}, // RS_TYPE_MATRIX_3X3
739 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4} // RS_TYPE_MATRIX_2X2
Ewan Crawforda0f08672015-10-16 08:28:47 +0000740};
741
Ewan Crawford4f8817c2016-01-20 12:03:29 +0000742const std::string RenderScriptRuntime::s_runtimeExpandSuffix(".expand");
Pavel Labatha9759592016-01-20 12:23:23 +0000743const std::array<const char *, 3> RenderScriptRuntime::s_runtimeCoordVars{{"rsIndex", "p->current.y", "p->current.z"}};
Colin Riley5ec532a2015-04-09 16:49:25 +0000744//------------------------------------------------------------------
745// Static Functions
746//------------------------------------------------------------------
747LanguageRuntime *
748RenderScriptRuntime::CreateInstance(Process *process, lldb::LanguageType language)
749{
750
751 if (language == eLanguageTypeExtRenderScript)
752 return new RenderScriptRuntime(process);
753 else
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000754 return nullptr;
Colin Riley5ec532a2015-04-09 16:49:25 +0000755}
756
Ewan Crawford98156582015-09-04 08:56:52 +0000757// Callback with a module to search for matching symbols.
758// We first check that the module contains RS kernels.
759// Then look for a symbol which matches our kernel name.
760// The breakpoint address is finally set using the address of this symbol.
761Searcher::CallbackReturn
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000762RSBreakpointResolver::SearchCallback(SearchFilter &filter, SymbolContext &context, Address *, bool)
Ewan Crawford98156582015-09-04 08:56:52 +0000763{
764 ModuleSP module = context.module_sp;
765
766 if (!module)
767 return Searcher::eCallbackReturnContinue;
768
769 // Is this a module containing renderscript kernels?
770 if (nullptr == module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData))
771 return Searcher::eCallbackReturnContinue;
772
773 // Attempt to set a breakpoint on the kernel name symbol within the module library.
774 // If it's not found, it's likely debug info is unavailable - try to set a
775 // breakpoint on <name>.expand.
776
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000777 const Symbol *kernel_sym = module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
Ewan Crawford98156582015-09-04 08:56:52 +0000778 if (!kernel_sym)
779 {
780 std::string kernel_name_expanded(m_kernel_name.AsCString());
781 kernel_name_expanded.append(".expand");
782 kernel_sym = module->FindFirstSymbolWithNameAndType(ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
783 }
784
785 if (kernel_sym)
786 {
787 Address bp_addr = kernel_sym->GetAddress();
788 if (filter.AddressPasses(bp_addr))
789 m_breakpoint->AddLocation(bp_addr);
790 }
791
792 return Searcher::eCallbackReturnContinue;
793}
794
Colin Riley5ec532a2015-04-09 16:49:25 +0000795void
796RenderScriptRuntime::Initialize()
797{
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000798 PluginManager::RegisterPlugin(GetPluginNameStatic(), "RenderScript language support", CreateInstance,
799 GetCommandObject);
Colin Riley5ec532a2015-04-09 16:49:25 +0000800}
801
802void
803RenderScriptRuntime::Terminate()
804{
805 PluginManager::UnregisterPlugin(CreateInstance);
806}
807
808lldb_private::ConstString
809RenderScriptRuntime::GetPluginNameStatic()
810{
811 static ConstString g_name("renderscript");
812 return g_name;
813}
814
Aidan Dodds35e7b1a2016-01-06 15:43:52 +0000815RenderScriptRuntime::ModuleKind
Colin Rileyef20b082015-04-14 07:39:24 +0000816RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp)
817{
818 if (module_sp)
819 {
820 // Is this a module containing renderscript kernels?
821 const Symbol *info_sym = module_sp->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
822 if (info_sym)
823 {
824 return eModuleKindKernelObj;
825 }
Colin Riley4640cde2015-06-01 18:23:41 +0000826
827 // Is this the main RS runtime library
828 const ConstString rs_lib("libRS.so");
829 if (module_sp->GetFileSpec().GetFilename() == rs_lib)
830 {
831 return eModuleKindLibRS;
832 }
833
834 const ConstString rs_driverlib("libRSDriver.so");
835 if (module_sp->GetFileSpec().GetFilename() == rs_driverlib)
836 {
837 return eModuleKindDriver;
838 }
839
Ewan Crawford15f2bd92015-10-06 08:42:32 +0000840 const ConstString rs_cpureflib("libRSCpuRef.so");
Colin Riley4640cde2015-06-01 18:23:41 +0000841 if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib)
842 {
843 return eModuleKindImpl;
844 }
Colin Rileyef20b082015-04-14 07:39:24 +0000845 }
846 return eModuleKindIgnored;
847}
848
849bool
850RenderScriptRuntime::IsRenderScriptModule(const lldb::ModuleSP &module_sp)
851{
852 return GetModuleKind(module_sp) != eModuleKindIgnored;
853}
854
Aidan Dodds35e7b1a2016-01-06 15:43:52 +0000855void
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000856RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list)
Colin Rileyef20b082015-04-14 07:39:24 +0000857{
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000858 Mutex::Locker locker(module_list.GetMutex());
Colin Rileyef20b082015-04-14 07:39:24 +0000859
860 size_t num_modules = module_list.GetSize();
861 for (size_t i = 0; i < num_modules; i++)
862 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000863 auto mod = module_list.GetModuleAtIndex(i);
864 if (IsRenderScriptModule(mod))
Colin Rileyef20b082015-04-14 07:39:24 +0000865 {
866 LoadModule(mod);
867 }
868 }
869}
870
Colin Riley5ec532a2015-04-09 16:49:25 +0000871//------------------------------------------------------------------
872// PluginInterface protocol
873//------------------------------------------------------------------
874lldb_private::ConstString
875RenderScriptRuntime::GetPluginName()
876{
877 return GetPluginNameStatic();
878}
879
880uint32_t
881RenderScriptRuntime::GetPluginVersion()
882{
883 return 1;
884}
885
886bool
887RenderScriptRuntime::IsVTableName(const char *name)
888{
889 return false;
890}
891
892bool
893RenderScriptRuntime::GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic,
Enrico Granata0b6003f2015-09-17 22:56:38 +0000894 TypeAndOrName &class_type_or_name, Address &address,
895 Value::ValueType &value_type)
Colin Riley5ec532a2015-04-09 16:49:25 +0000896{
897 return false;
898}
899
Enrico Granatac74275b2015-09-22 19:45:52 +0000900TypeAndOrName
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000901RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name, ValueObject &static_value)
Enrico Granatac74275b2015-09-22 19:45:52 +0000902{
903 return type_and_or_name;
904}
905
Colin Riley5ec532a2015-04-09 16:49:25 +0000906bool
907RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value)
908{
909 return false;
910}
911
912lldb::BreakpointResolverSP
913RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp, bool throw_bp)
914{
915 BreakpointResolverSP resolver_sp;
916 return resolver_sp;
917}
918
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000919const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] = {
920 // rsdScript
Aidan Dodds82780282015-09-18 16:49:39 +0000921 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000922 "rsdScriptInit",
923 "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhjj",
924 "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhmj",
925 0,
926 RenderScriptRuntime::eModuleKindDriver,
927 &lldb_private::RenderScriptRuntime::CaptureScriptInit
Aidan Dodds82780282015-09-18 16:49:39 +0000928 },
929 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000930 "rsdScriptInvokeForEachMulti",
931 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
932 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
933 0,
934 RenderScriptRuntime::eModuleKindDriver,
935 &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti
Aidan Dodds82780282015-09-18 16:49:39 +0000936 },
937 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000938 "rsdScriptSetGlobalVar",
939 "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvj",
940 "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvm",
941 0,
942 RenderScriptRuntime::eModuleKindDriver,
943 &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar
Aidan Dodds82780282015-09-18 16:49:39 +0000944 },
Colin Riley4640cde2015-06-01 18:23:41 +0000945
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000946 // rsdAllocation
Aidan Dodds82780282015-09-18 16:49:39 +0000947 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000948 "rsdAllocationInit",
949 "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb",
950 "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb",
951 0,
952 RenderScriptRuntime::eModuleKindDriver,
953 &lldb_private::RenderScriptRuntime::CaptureAllocationInit
Aidan Dodds82780282015-09-18 16:49:39 +0000954 },
955 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000956 "rsdAllocationRead2D",
957 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
958 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
959 0,
960 RenderScriptRuntime::eModuleKindDriver,
961 nullptr
Aidan Dodds82780282015-09-18 16:49:39 +0000962 },
Ewan Crawforde69df382015-12-09 16:01:58 +0000963 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000964 "rsdAllocationDestroy",
965 "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE",
966 "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE",
967 0,
968 RenderScriptRuntime::eModuleKindDriver,
969 &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy
Ewan Crawforde69df382015-12-09 16:01:58 +0000970 },
Colin Riley4640cde2015-06-01 18:23:41 +0000971};
Colin Riley4640cde2015-06-01 18:23:41 +0000972
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000973const size_t RenderScriptRuntime::s_runtimeHookCount = sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
Colin Riley4640cde2015-06-01 18:23:41 +0000974
975bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000976RenderScriptRuntime::HookCallback(void *baton, StoppointCallbackContext *ctx, lldb::user_id_t break_id,
977 lldb::user_id_t break_loc_id)
Colin Riley4640cde2015-06-01 18:23:41 +0000978{
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000979 RuntimeHook *hook_info = (RuntimeHook *)baton;
Colin Riley4640cde2015-06-01 18:23:41 +0000980 ExecutionContext context(ctx->exe_ctx_ref);
981
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000982 RenderScriptRuntime *lang_rt =
983 (RenderScriptRuntime *)context.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
Colin Riley4640cde2015-06-01 18:23:41 +0000984
985 lang_rt->HookCallback(hook_info, context);
Aidan Dodds35e7b1a2016-01-06 15:43:52 +0000986
Colin Riley4640cde2015-06-01 18:23:41 +0000987 return false;
988}
989
Aidan Dodds35e7b1a2016-01-06 15:43:52 +0000990void
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000991RenderScriptRuntime::HookCallback(RuntimeHook *hook_info, ExecutionContext &context)
Colin Riley4640cde2015-06-01 18:23:41 +0000992{
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000993 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Colin Riley4640cde2015-06-01 18:23:41 +0000994
Aidan Dodds82780282015-09-18 16:49:39 +0000995 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +0000996 log->Printf("%s - '%s'", __FUNCTION__, hook_info->defn->name);
Colin Riley4640cde2015-06-01 18:23:41 +0000997
Aidan Dodds35e7b1a2016-01-06 15:43:52 +0000998 if (hook_info->defn->grabber)
Colin Riley4640cde2015-06-01 18:23:41 +0000999 {
1000 (this->*(hook_info->defn->grabber))(hook_info, context);
1001 }
1002}
1003
Aidan Dodds35e7b1a2016-01-06 15:43:52 +00001004void
Aidan Doddse09c44b2016-01-14 15:39:28 +00001005RenderScriptRuntime::CaptureScriptInvokeForEachMulti(RuntimeHook* hook_info,
1006 ExecutionContext& context)
1007{
1008 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1009
Aidan Doddsf4786782016-02-11 15:16:37 +00001010 enum
Aidan Doddse09c44b2016-01-14 15:39:28 +00001011 {
Aidan Doddsf4786782016-02-11 15:16:37 +00001012 eRsContext = 0,
1013 eRsScript,
1014 eRsSlot,
1015 eRsAIns,
1016 eRsInLen,
1017 eRsAOut,
1018 eRsUsr,
1019 eRsUsrLen,
1020 eRsSc,
1021 };
Aidan Doddse09c44b2016-01-14 15:39:28 +00001022
Saleem Abdulrasool1ee07252016-02-15 21:50:28 +00001023 std::array<ArgItem, 9> args{{
Aidan Doddsf4786782016-02-11 15:16:37 +00001024 ArgItem{ArgItem::ePointer, 0}, // const Context *rsc
1025 ArgItem{ArgItem::ePointer, 0}, // Script *s
1026 ArgItem{ArgItem::eInt32, 0}, // uint32_t slot
1027 ArgItem{ArgItem::ePointer, 0}, // const Allocation **aIns
1028 ArgItem{ArgItem::eInt32, 0}, // size_t inLen
1029 ArgItem{ArgItem::ePointer, 0}, // Allocation *aout
1030 ArgItem{ArgItem::ePointer, 0}, // const void *usr
1031 ArgItem{ArgItem::eInt32, 0}, // size_t usrLen
1032 ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall *sc
Saleem Abdulrasool1ee07252016-02-15 21:50:28 +00001033 }};
Aidan Doddse09c44b2016-01-14 15:39:28 +00001034
Aidan Doddsf4786782016-02-11 15:16:37 +00001035 bool success = GetArgs(context, &args[0], args.size());
Aidan Doddse09c44b2016-01-14 15:39:28 +00001036 if (!success)
1037 {
1038 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001039 log->Printf("%s - Error while reading the function parameters", __FUNCTION__);
Aidan Doddse09c44b2016-01-14 15:39:28 +00001040 return;
1041 }
1042
1043 const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1044 Error error;
1045 std::vector<uint64_t> allocs;
1046
1047 // traverse allocation list
Aidan Doddsf4786782016-02-11 15:16:37 +00001048 for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i)
Aidan Doddse09c44b2016-01-14 15:39:28 +00001049 {
1050 // calculate offest to allocation pointer
Aidan Doddsf4786782016-02-11 15:16:37 +00001051 const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
Aidan Doddse09c44b2016-01-14 15:39:28 +00001052
1053 // Note: due to little endian layout, reading 32bits or 64bits into res64 will
1054 // give the correct results.
1055
1056 uint64_t res64 = 0;
1057 size_t read = m_process->ReadMemory(addr, &res64, target_ptr_size, error);
1058 if (read != target_ptr_size || !error.Success())
1059 {
1060 if (log)
Aidan Doddsf4786782016-02-11 15:16:37 +00001061 log->Printf("%s - Error while reading allocation list argument %" PRIu64, __FUNCTION__, i);
Aidan Doddse09c44b2016-01-14 15:39:28 +00001062 }
1063 else
1064 {
1065 allocs.push_back(res64);
1066 }
1067 }
1068
1069 // if there is an output allocation track it
Aidan Doddsf4786782016-02-11 15:16:37 +00001070 if (uint64_t aOut = uint64_t(args[eRsAOut]))
Aidan Doddse09c44b2016-01-14 15:39:28 +00001071 {
Aidan Doddsf4786782016-02-11 15:16:37 +00001072 allocs.push_back(aOut);
Aidan Doddse09c44b2016-01-14 15:39:28 +00001073 }
1074
1075 // for all allocations we have found
1076 for (const uint64_t alloc_addr : allocs)
1077 {
1078 AllocationDetails* alloc = LookUpAllocation(alloc_addr, true);
1079 if (alloc)
1080 {
1081 // save the allocation address
1082 if (alloc->address.isValid())
1083 {
1084 // check the allocation address we already have matches
1085 assert(*alloc->address.get() == alloc_addr);
1086 }
1087 else
1088 {
1089 alloc->address = alloc_addr;
1090 }
1091
1092 // save the context
1093 if (log)
1094 {
Aidan Doddsf4786782016-02-11 15:16:37 +00001095 if (alloc->context.isValid() && *alloc->context.get() != addr_t(args[eRsContext]))
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001096 log->Printf("%s - Allocation used by multiple contexts", __FUNCTION__);
Aidan Doddse09c44b2016-01-14 15:39:28 +00001097 }
Aidan Doddsf4786782016-02-11 15:16:37 +00001098 alloc->context = addr_t(args[eRsContext]);
Aidan Doddse09c44b2016-01-14 15:39:28 +00001099 }
1100 }
1101
1102 // make sure we track this script object
Aidan Doddsf4786782016-02-11 15:16:37 +00001103 if (lldb_private::RenderScriptRuntime::ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true))
Aidan Doddse09c44b2016-01-14 15:39:28 +00001104 {
1105 if (log)
1106 {
Aidan Doddsf4786782016-02-11 15:16:37 +00001107 if (script->context.isValid() && *script->context.get() != addr_t(args[eRsContext]))
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001108 log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
Aidan Doddse09c44b2016-01-14 15:39:28 +00001109 }
Aidan Doddsf4786782016-02-11 15:16:37 +00001110 script->context = addr_t(args[eRsContext]);
Aidan Doddse09c44b2016-01-14 15:39:28 +00001111 }
1112}
1113
1114void
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001115RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook_info, ExecutionContext &context)
Colin Riley4640cde2015-06-01 18:23:41 +00001116{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001117 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Aidan Dodds35e7b1a2016-01-06 15:43:52 +00001118
Aidan Doddsf4786782016-02-11 15:16:37 +00001119 enum
1120 {
1121 eRsContext,
1122 eRsScript,
1123 eRsId,
1124 eRsData,
1125 eRsLength,
1126 };
Colin Riley4640cde2015-06-01 18:23:41 +00001127
Saleem Abdulrasool1ee07252016-02-15 21:50:28 +00001128 std::array<ArgItem, 5> args{{
Aidan Doddsf4786782016-02-11 15:16:37 +00001129 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1130 ArgItem{ArgItem::ePointer, 0}, // eRsScript
1131 ArgItem{ArgItem::eInt32, 0}, // eRsId
1132 ArgItem{ArgItem::ePointer, 0}, // eRsData
1133 ArgItem{ArgItem::eInt32, 0}, // eRsLength
Saleem Abdulrasool1ee07252016-02-15 21:50:28 +00001134 }};
Colin Riley4640cde2015-06-01 18:23:41 +00001135
Aidan Doddsf4786782016-02-11 15:16:37 +00001136 bool success = GetArgs(context, &args[0], args.size());
Aidan Dodds82780282015-09-18 16:49:39 +00001137 if (!success)
1138 {
1139 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001140 log->Printf("%s - error reading the function parameters.", __FUNCTION__);
Aidan Dodds82780282015-09-18 16:49:39 +00001141 return;
1142 }
Aidan Dodds35e7b1a2016-01-06 15:43:52 +00001143
Aidan Dodds82780282015-09-18 16:49:39 +00001144 if (log)
Colin Riley4640cde2015-06-01 18:23:41 +00001145 {
Aidan Doddsf4786782016-02-11 15:16:37 +00001146 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64 ":%" PRIu64 "bytes.", __FUNCTION__,
1147 uint64_t(args[eRsContext]), uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1148 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
Colin Riley4640cde2015-06-01 18:23:41 +00001149
Aidan Doddsf4786782016-02-11 15:16:37 +00001150 addr_t script_addr = addr_t(args[eRsScript]);
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001151 if (m_scriptMappings.find(script_addr) != m_scriptMappings.end())
Colin Riley4640cde2015-06-01 18:23:41 +00001152 {
1153 auto rsm = m_scriptMappings[script_addr];
Aidan Doddsf4786782016-02-11 15:16:37 +00001154 if (uint64_t(args[eRsId]) < rsm->m_globals.size())
Colin Riley4640cde2015-06-01 18:23:41 +00001155 {
Aidan Doddsf4786782016-02-11 15:16:37 +00001156 auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1157 log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__, rsg.m_name.AsCString(),
1158 rsm->m_module->GetFileSpec().GetFilename().AsCString());
Colin Riley4640cde2015-06-01 18:23:41 +00001159 }
1160 }
1161 }
1162}
1163
Aidan Dodds35e7b1a2016-01-06 15:43:52 +00001164void
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001165RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook_info, ExecutionContext &context)
Colin Riley4640cde2015-06-01 18:23:41 +00001166{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001167 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Aidan Dodds35e7b1a2016-01-06 15:43:52 +00001168
Aidan Doddsf4786782016-02-11 15:16:37 +00001169 enum
1170 {
1171 eRsContext,
1172 eRsAlloc,
1173 eRsForceZero
1174 };
Colin Riley4640cde2015-06-01 18:23:41 +00001175
Saleem Abdulrasool1ee07252016-02-15 21:50:28 +00001176 std::array<ArgItem, 3> args{{
Aidan Doddsf4786782016-02-11 15:16:37 +00001177 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1178 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1179 ArgItem{ArgItem::eBool, 0}, // eRsForceZero
Saleem Abdulrasool1ee07252016-02-15 21:50:28 +00001180 }};
Colin Riley4640cde2015-06-01 18:23:41 +00001181
Aidan Doddsf4786782016-02-11 15:16:37 +00001182 bool success = GetArgs(context, &args[0], args.size());
Aidan Dodds82780282015-09-18 16:49:39 +00001183 if (!success) // error case
1184 {
1185 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001186 log->Printf("%s - error while reading the function parameters", __FUNCTION__);
Aidan Dodds82780282015-09-18 16:49:39 +00001187 return; // abort
1188 }
1189
1190 if (log)
Aidan Doddsf4786782016-02-11 15:16:37 +00001191 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .", __FUNCTION__, uint64_t(args[eRsContext]),
1192 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
Ewan Crawford78f339d2015-09-21 10:53:18 +00001193
Aidan Doddsf4786782016-02-11 15:16:37 +00001194 AllocationDetails *alloc = LookUpAllocation(uint64_t(args[eRsAlloc]), true);
Ewan Crawford78f339d2015-09-21 10:53:18 +00001195 if (alloc)
Aidan Doddsf4786782016-02-11 15:16:37 +00001196 alloc->context = uint64_t(args[eRsContext]);
Colin Riley4640cde2015-06-01 18:23:41 +00001197}
1198
Ewan Crawforde69df382015-12-09 16:01:58 +00001199void
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001200RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook_info, ExecutionContext &context)
Ewan Crawforde69df382015-12-09 16:01:58 +00001201{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001202 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawforde69df382015-12-09 16:01:58 +00001203
Aidan Doddsf4786782016-02-11 15:16:37 +00001204 enum
1205 {
1206 eRsContext,
1207 eRsAlloc,
1208 };
Ewan Crawforde69df382015-12-09 16:01:58 +00001209
Saleem Abdulrasool1ee07252016-02-15 21:50:28 +00001210 std::array<ArgItem, 2> args{{
Aidan Doddsf4786782016-02-11 15:16:37 +00001211 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1212 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
Saleem Abdulrasool1ee07252016-02-15 21:50:28 +00001213 }};
Aidan Doddsf4786782016-02-11 15:16:37 +00001214
1215 bool success = GetArgs(context, &args[0], args.size());
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001216 if (!success)
Ewan Crawforde69df382015-12-09 16:01:58 +00001217 {
1218 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001219 log->Printf("%s - error while reading the function parameters.", __FUNCTION__);
1220 return;
Ewan Crawforde69df382015-12-09 16:01:58 +00001221 }
1222
1223 if (log)
Aidan Doddsf4786782016-02-11 15:16:37 +00001224 log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__, uint64_t(args[eRsContext]),
1225 uint64_t(args[eRsAlloc]));
Ewan Crawforde69df382015-12-09 16:01:58 +00001226
1227 for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter)
1228 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001229 auto &allocation_ap = *iter; // get the unique pointer
Aidan Doddsf4786782016-02-11 15:16:37 +00001230 if (allocation_ap->address.isValid() && *allocation_ap->address.get() == addr_t(args[eRsAlloc]))
Ewan Crawforde69df382015-12-09 16:01:58 +00001231 {
1232 m_allocations.erase(iter);
1233 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001234 log->Printf("%s - deleted allocation entry.", __FUNCTION__);
Ewan Crawforde69df382015-12-09 16:01:58 +00001235 return;
1236 }
1237 }
1238
1239 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001240 log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
Ewan Crawforde69df382015-12-09 16:01:58 +00001241}
1242
Aidan Dodds35e7b1a2016-01-06 15:43:52 +00001243void
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001244RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook_info, ExecutionContext &context)
Colin Riley4640cde2015-06-01 18:23:41 +00001245{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001246 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Colin Riley4640cde2015-06-01 18:23:41 +00001247
Colin Riley4640cde2015-06-01 18:23:41 +00001248 Error error;
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001249 Process *process = context.GetProcessPtr();
Colin Riley4640cde2015-06-01 18:23:41 +00001250
Aidan Doddsf4786782016-02-11 15:16:37 +00001251 enum
1252 {
1253 eRsContext,
1254 eRsScript,
1255 eRsResNamePtr,
1256 eRsCachedDirPtr
1257 };
Colin Riley4640cde2015-06-01 18:23:41 +00001258
Saleem Abdulrasool1ee07252016-02-15 21:50:28 +00001259 std::array<ArgItem, 4> args{{ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
1260 ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
Aidan Doddsf4786782016-02-11 15:16:37 +00001261 bool success = GetArgs(context, &args[0], args.size());
Aidan Dodds82780282015-09-18 16:49:39 +00001262 if (!success)
1263 {
1264 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001265 log->Printf("%s - error while reading the function parameters.", __FUNCTION__);
Aidan Dodds82780282015-09-18 16:49:39 +00001266 return;
1267 }
1268
Aidan Doddsf4786782016-02-11 15:16:37 +00001269 std::string resname;
1270 process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), resname, error);
Colin Riley4640cde2015-06-01 18:23:41 +00001271 if (error.Fail())
1272 {
Aidan Dodds82780282015-09-18 16:49:39 +00001273 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001274 log->Printf("%s - error reading resname: %s.", __FUNCTION__, error.AsCString());
Colin Riley4640cde2015-06-01 18:23:41 +00001275 }
1276
Aidan Doddsf4786782016-02-11 15:16:37 +00001277 std::string cachedir;
1278 process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cachedir, error);
Colin Riley4640cde2015-06-01 18:23:41 +00001279 if (error.Fail())
1280 {
Aidan Dodds82780282015-09-18 16:49:39 +00001281 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001282 log->Printf("%s - error reading cachedir: %s.", __FUNCTION__, error.AsCString());
Colin Riley4640cde2015-06-01 18:23:41 +00001283 }
Aidan Dodds35e7b1a2016-01-06 15:43:52 +00001284
Colin Riley4640cde2015-06-01 18:23:41 +00001285 if (log)
Aidan Doddsf4786782016-02-11 15:16:37 +00001286 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .", __FUNCTION__, uint64_t(args[eRsContext]),
1287 uint64_t(args[eRsScript]), resname.c_str(), cachedir.c_str());
Colin Riley4640cde2015-06-01 18:23:41 +00001288
1289 if (resname.size() > 0)
1290 {
1291 StreamString strm;
1292 strm.Printf("librs.%s.so", resname.c_str());
1293
Aidan Doddsf4786782016-02-11 15:16:37 +00001294 ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
Ewan Crawford78f339d2015-09-21 10:53:18 +00001295 if (script)
1296 {
1297 script->type = ScriptDetails::eScriptC;
1298 script->cacheDir = cachedir;
1299 script->resName = resname;
1300 script->scriptDyLib = strm.GetData();
Aidan Doddsf4786782016-02-11 15:16:37 +00001301 script->context = addr_t(args[eRsContext]);
Ewan Crawford78f339d2015-09-21 10:53:18 +00001302 }
Colin Riley4640cde2015-06-01 18:23:41 +00001303
1304 if (log)
Aidan Doddsf4786782016-02-11 15:16:37 +00001305 log->Printf("%s - '%s' tagged with context 0x%" PRIx64 " and script 0x%" PRIx64 ".", __FUNCTION__,
1306 strm.GetData(), uint64_t(args[eRsContext]), uint64_t(args[eRsScript]));
Aidan Dodds35e7b1a2016-01-06 15:43:52 +00001307 }
Colin Riley4640cde2015-06-01 18:23:41 +00001308 else if (log)
1309 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001310 log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
Colin Riley4640cde2015-06-01 18:23:41 +00001311 }
Colin Riley4640cde2015-06-01 18:23:41 +00001312}
1313
Colin Riley4640cde2015-06-01 18:23:41 +00001314void
1315RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind)
1316{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001317 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Colin Riley4640cde2015-06-01 18:23:41 +00001318
1319 if (!module)
1320 {
1321 return;
1322 }
1323
Aidan Dodds82780282015-09-18 16:49:39 +00001324 Target &target = GetProcess()->GetTarget();
1325 llvm::Triple::ArchType targetArchType = target.GetArchitecture().GetMachine();
1326
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001327 if (targetArchType != llvm::Triple::ArchType::x86 &&
1328 targetArchType != llvm::Triple::ArchType::arm &&
1329 targetArchType != llvm::Triple::ArchType::aarch64 &&
1330 targetArchType != llvm::Triple::ArchType::mipsel &&
1331 targetArchType != llvm::Triple::ArchType::mips64el &&
1332 targetArchType != llvm::Triple::ArchType::x86_64)
Colin Riley4640cde2015-06-01 18:23:41 +00001333 {
1334 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001335 log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
Colin Riley4640cde2015-06-01 18:23:41 +00001336 return;
1337 }
1338
Aidan Dodds82780282015-09-18 16:49:39 +00001339 uint32_t archByteSize = target.GetArchitecture().GetAddressByteSize();
Colin Riley4640cde2015-06-01 18:23:41 +00001340
1341 for (size_t idx = 0; idx < s_runtimeHookCount; idx++)
1342 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001343 const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1344 if (hook_defn->kind != kind)
1345 {
Colin Riley4640cde2015-06-01 18:23:41 +00001346 continue;
1347 }
1348
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001349 const char *symbol_name = (archByteSize == 4) ? hook_defn->symbol_name_m32 : hook_defn->symbol_name_m64;
Aidan Dodds82780282015-09-18 16:49:39 +00001350
1351 const Symbol *sym = module->FindFirstSymbolWithNameAndType(ConstString(symbol_name), eSymbolTypeCode);
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001352 if (!sym)
1353 {
1354 if (log)
1355 {
1356 log->Printf("%s - symbol '%s' related to the function %s not found",
1357 __FUNCTION__, symbol_name, hook_defn->name);
Aidan Dodds82780282015-09-18 16:49:39 +00001358 }
1359 continue;
1360 }
Colin Riley4640cde2015-06-01 18:23:41 +00001361
Greg Clayton358cf1e2015-06-25 21:46:34 +00001362 addr_t addr = sym->GetLoadAddress(&target);
Colin Riley4640cde2015-06-01 18:23:41 +00001363 if (addr == LLDB_INVALID_ADDRESS)
1364 {
Aidan Dodds82780282015-09-18 16:49:39 +00001365 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001366 log->Printf("%s - unable to resolve the address of hook function '%s' with symbol '%s'.",
1367 __FUNCTION__, hook_defn->name, symbol_name);
Colin Riley4640cde2015-06-01 18:23:41 +00001368 continue;
1369 }
Aidan Dodds82780282015-09-18 16:49:39 +00001370 else
1371 {
1372 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001373 log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1374 __FUNCTION__, hook_defn->name, addr);
Aidan Dodds82780282015-09-18 16:49:39 +00001375 }
Colin Riley4640cde2015-06-01 18:23:41 +00001376
1377 RuntimeHookSP hook(new RuntimeHook());
1378 hook->address = addr;
1379 hook->defn = hook_defn;
1380 hook->bp_sp = target.CreateBreakpoint(addr, true, false);
1381 hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
1382 m_runtimeHooks[addr] = hook;
1383 if (log)
1384 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001385 log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64 " at 0x%" PRIx64 ".",
1386 __FUNCTION__, hook_defn->name, module->GetFileSpec().GetFilename().AsCString(),
1387 (uint64_t)hook_defn->version, (uint64_t)addr);
Colin Riley4640cde2015-06-01 18:23:41 +00001388 }
1389 }
1390}
1391
1392void
1393RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp)
1394{
1395 if (!rsmodule_sp)
1396 return;
1397
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001398 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Colin Riley4640cde2015-06-01 18:23:41 +00001399
1400 const ModuleSP module = rsmodule_sp->m_module;
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001401 const FileSpec &file = module->GetPlatformFileSpec();
Ewan Crawford78f339d2015-09-21 10:53:18 +00001402
1403 // Iterate over all of the scripts that we currently know of.
1404 // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001405 for (const auto &rs_script : m_scripts)
Colin Riley4640cde2015-06-01 18:23:41 +00001406 {
Ewan Crawford78f339d2015-09-21 10:53:18 +00001407 // Extract the expected .so file path for this script.
1408 std::string dylib;
1409 if (!rs_script->scriptDyLib.get(dylib))
1410 continue;
1411
1412 // Only proceed if the module that has loaded corresponds to this script.
1413 if (file.GetFilename() != ConstString(dylib.c_str()))
1414 continue;
1415
1416 // Obtain the script address which we use as a key.
1417 lldb::addr_t script;
1418 if (!rs_script->script.get(script))
1419 continue;
1420
1421 // If we have a script mapping for the current script.
1422 if (m_scriptMappings.find(script) != m_scriptMappings.end())
Colin Riley4640cde2015-06-01 18:23:41 +00001423 {
Ewan Crawford78f339d2015-09-21 10:53:18 +00001424 // if the module we have stored is different to the one we just received.
1425 if (m_scriptMappings[script] != rsmodule_sp)
Colin Riley4640cde2015-06-01 18:23:41 +00001426 {
Colin Riley4640cde2015-06-01 18:23:41 +00001427 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001428 log->Printf("%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.", __FUNCTION__,
1429 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
Colin Riley4640cde2015-06-01 18:23:41 +00001430 }
1431 }
Ewan Crawford78f339d2015-09-21 10:53:18 +00001432 // We don't have a script mapping for the current script.
1433 else
1434 {
1435 // Obtain the script resource name.
1436 std::string resName;
1437 if (rs_script->resName.get(resName))
1438 // Set the modules resource name.
1439 rsmodule_sp->m_resname = resName;
1440 // Add Script/Module pair to map.
1441 m_scriptMappings[script] = rsmodule_sp;
1442 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001443 log->Printf("%s - script %" PRIx64 " associated with rsmodule '%s'.", __FUNCTION__,
1444 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
Ewan Crawford78f339d2015-09-21 10:53:18 +00001445 }
Colin Riley4640cde2015-06-01 18:23:41 +00001446 }
Colin Riley4640cde2015-06-01 18:23:41 +00001447}
1448
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001449// Uses the Target API to evaluate the expression passed as a parameter to the function
1450// The result of that expression is returned an unsigned 64 bit int, via the result* paramter.
1451// Function returns true on success, and false on failure
1452bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001453RenderScriptRuntime::EvalRSExpression(const char *expression, StackFrame *frame_ptr, uint64_t *result)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001454{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001455 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001456 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001457 log->Printf("%s(%s)", __FUNCTION__, expression);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001458
1459 ValueObjectSP expr_result;
1460 // Perform the actual expression evaluation
1461 GetProcess()->GetTarget().EvaluateExpression(expression, frame_ptr, expr_result);
1462
1463 if (!expr_result)
1464 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001465 if (log)
1466 log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
1467 return false;
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001468 }
1469
1470 // The result of the expression is invalid
1471 if (!expr_result->GetError().Success())
1472 {
1473 Error err = expr_result->GetError();
1474 if (err.GetError() == UserExpression::kNoResult) // Expression returned void, so this is actually a success
1475 {
1476 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001477 log->Printf("%s - expression returned void.", __FUNCTION__);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001478
1479 result = nullptr;
1480 return true;
1481 }
1482
1483 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001484 log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1485 err.AsCString());
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001486 return false;
1487 }
1488
1489 bool success = false;
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001490 *result = expr_result->GetValueAsUnsigned(0, &success); // We only read the result as an uint32_t.
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001491
1492 if (!success)
1493 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001494 if (log)
1495 log->Printf("%s - couldn't convert expression result to uint32_t", __FUNCTION__);
1496 return false;
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001497 }
1498
1499 return true;
1500}
1501
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001502namespace
1503{
Ewan Crawford836d9652016-01-18 09:16:02 +00001504// Used to index expression format strings
1505enum ExpressionStrings
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001506{
Ewan Crawford836d9652016-01-18 09:16:02 +00001507 eExprGetOffsetPtr = 0,
1508 eExprAllocGetType,
1509 eExprTypeDimX,
1510 eExprTypeDimY,
1511 eExprTypeDimZ,
1512 eExprTypeElemPtr,
1513 eExprElementType,
1514 eExprElementKind,
1515 eExprElementVec,
1516 eExprElementFieldCount,
1517 eExprSubelementsId,
1518 eExprSubelementsName,
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001519 eExprSubelementsArrSize,
1520
1521 _eExprLast // keep at the end, implicit size of the array runtimeExpressions
Ewan Crawford836d9652016-01-18 09:16:02 +00001522};
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001523
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001524// max length of an expanded expression
1525const int jit_max_expr_size = 512;
1526
1527// Retrieve the string to JIT for the given expression
1528const char*
1529JITTemplate(ExpressionStrings e)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001530{
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001531 // Format strings containing the expressions we may need to evaluate.
1532 static std::array<const char*, _eExprLast> runtimeExpressions = {{
1533 // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1534 "(int*)_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace(0x%lx, %u, %u, %u, 0, 0)",
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001535
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001536 // Type* rsaAllocationGetType(Context*, Allocation*)
1537 "(void*)rsaAllocationGetType(0x%lx, 0x%lx)",
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001538
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001539 // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
1540 // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ;
1541 // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
1542 // Need to specify 32 or 64 bit for uint_t since this differs between devices
1543 "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[0]", // X dim
1544 "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[1]", // Y dim
1545 "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[2]", // Z dim
1546 "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[5]", // Element ptr
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001547
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001548 // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1549 // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData
1550 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[0]", // Type
1551 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[1]", // Kind
1552 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[3]", // Vector Size
1553 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[4]", // Field Count
Ewan Crawford8b244e22015-11-30 10:29:49 +00001554
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001555 // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t *ids, const char **names,
1556 // size_t *arraySizes, uint32_t dataSize)
1557 // Needed for Allocations of structs to gather details about fields/Subelements
1558 "void *ids[%u]; const char *names[%u]; size_t arr_size[%u];"
1559 "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); ids[%u]", // Element* of field
Ewan Crawford836d9652016-01-18 09:16:02 +00001560
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001561 "void *ids[%u]; const char *names[%u]; size_t arr_size[%u];"
1562 "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); names[%u]", // Name of field
Ewan Crawford836d9652016-01-18 09:16:02 +00001563
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001564 "void *ids[%u]; const char *names[%u]; size_t arr_size[%u];"
1565 "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); arr_size[%u]" // Array size of field
1566 }};
1567
1568 return runtimeExpressions[e];
1569}
1570} // end of the anonymous namespace
1571
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001572
1573// JITs the RS runtime for the internal data pointer of an allocation.
1574// Is passed x,y,z coordinates for the pointer to a specific element.
1575// Then sets the data_ptr member in Allocation with the result.
1576// Returns true on success, false otherwise
1577bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001578RenderScriptRuntime::JITDataPointer(AllocationDetails *allocation, StackFrame *frame_ptr, uint32_t x,
1579 uint32_t y, uint32_t z)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001580{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001581 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001582
1583 if (!allocation->address.isValid())
1584 {
1585 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001586 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001587 return false;
1588 }
1589
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001590 const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1591 char buffer[jit_max_expr_size];
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001592
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001593 int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), x, y, z);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001594 if (chars_written < 0)
1595 {
1596 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001597 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001598 return false;
1599 }
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001600 else if (chars_written >= jit_max_expr_size)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001601 {
1602 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001603 log->Printf("%s - expression too long.", __FUNCTION__);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001604 return false;
1605 }
1606
1607 uint64_t result = 0;
1608 if (!EvalRSExpression(buffer, frame_ptr, &result))
1609 return false;
1610
1611 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1612 allocation->data_ptr = mem_ptr;
1613
1614 return true;
1615}
1616
1617// JITs the RS runtime for the internal pointer to the RS Type of an allocation
1618// Then sets the type_ptr member in Allocation with the result.
1619// Returns true on success, false otherwise
1620bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001621RenderScriptRuntime::JITTypePointer(AllocationDetails *allocation, StackFrame *frame_ptr)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001622{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001623 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001624
1625 if (!allocation->address.isValid() || !allocation->context.isValid())
1626 {
1627 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001628 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001629 return false;
1630 }
1631
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001632 const char *expr_cstr = JITTemplate(eExprAllocGetType);
1633 char buffer[jit_max_expr_size];
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001634
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001635 int chars_written =
1636 snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->context.get(), *allocation->address.get());
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001637 if (chars_written < 0)
1638 {
1639 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001640 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001641 return false;
1642 }
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001643 else if (chars_written >= jit_max_expr_size)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001644 {
1645 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001646 log->Printf("%s - expression too long.", __FUNCTION__);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001647 return false;
1648 }
1649
1650 uint64_t result = 0;
1651 if (!EvalRSExpression(buffer, frame_ptr, &result))
1652 return false;
1653
1654 addr_t type_ptr = static_cast<lldb::addr_t>(result);
1655 allocation->type_ptr = type_ptr;
1656
1657 return true;
1658}
1659
1660// JITs the RS runtime for information about the dimensions and type of an allocation
1661// Then sets dimension and element_ptr members in Allocation with the result.
1662// Returns true on success, false otherwise
1663bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001664RenderScriptRuntime::JITTypePacked(AllocationDetails *allocation, StackFrame *frame_ptr)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001665{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001666 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001667
1668 if (!allocation->type_ptr.isValid() || !allocation->context.isValid())
1669 {
1670 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001671 log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001672 return false;
1673 }
1674
1675 // Expression is different depending on if device is 32 or 64 bit
1676 uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001677 const uint32_t bits = archByteSize == 4 ? 32 : 64;
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001678
1679 // We want 4 elements from packed data
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001680 const uint32_t num_exprs = 4;
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001681 assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) && "Invalid number of expressions");
1682
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001683 char buffer[num_exprs][jit_max_expr_size];
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001684 uint64_t results[num_exprs];
1685
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001686 for (uint32_t i = 0; i < num_exprs; ++i)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001687 {
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001688 const char *expr_cstr = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
1689 int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, bits, *allocation->context.get(),
1690 *allocation->type_ptr.get());
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001691 if (chars_written < 0)
1692 {
1693 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001694 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001695 return false;
1696 }
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001697 else if (chars_written >= jit_max_expr_size)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001698 {
1699 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001700 log->Printf("%s - expression too long.", __FUNCTION__);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001701 return false;
1702 }
1703
1704 // Perform expression evaluation
1705 if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
1706 return false;
1707 }
1708
1709 // Assign results to allocation members
1710 AllocationDetails::Dimension dims;
1711 dims.dim_1 = static_cast<uint32_t>(results[0]);
1712 dims.dim_2 = static_cast<uint32_t>(results[1]);
1713 dims.dim_3 = static_cast<uint32_t>(results[2]);
1714 allocation->dimension = dims;
1715
1716 addr_t elem_ptr = static_cast<lldb::addr_t>(results[3]);
Ewan Crawford8b244e22015-11-30 10:29:49 +00001717 allocation->element.element_ptr = elem_ptr;
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001718
1719 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001720 log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") Element*: 0x%" PRIx64 ".", __FUNCTION__,
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001721 dims.dim_1, dims.dim_2, dims.dim_3, elem_ptr);
1722
1723 return true;
1724}
1725
1726// JITs the RS runtime for information about the Element of an allocation
Ewan Crawford8b244e22015-11-30 10:29:49 +00001727// Then sets type, type_vec_size, field_count and type_kind members in Element with the result.
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001728// Returns true on success, false otherwise
1729bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001730RenderScriptRuntime::JITElementPacked(Element &elem, const lldb::addr_t context, StackFrame *frame_ptr)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001731{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001732 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001733
Ewan Crawford8b244e22015-11-30 10:29:49 +00001734 if (!elem.element_ptr.isValid())
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001735 {
1736 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001737 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001738 return false;
1739 }
1740
Ewan Crawford8b244e22015-11-30 10:29:49 +00001741 // We want 4 elements from packed data
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001742 const uint32_t num_exprs = 4;
Ewan Crawford8b244e22015-11-30 10:29:49 +00001743 assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) && "Invalid number of expressions");
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001744
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001745 char buffer[num_exprs][jit_max_expr_size];
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001746 uint64_t results[num_exprs];
1747
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001748 for (uint32_t i = 0; i < num_exprs; i++)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001749 {
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001750 const char *expr_cstr = JITTemplate(ExpressionStrings(eExprElementType + i));
1751 int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, context, *elem.element_ptr.get());
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001752 if (chars_written < 0)
1753 {
1754 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001755 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001756 return false;
1757 }
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001758 else if (chars_written >= jit_max_expr_size)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001759 {
1760 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001761 log->Printf("%s - expression too long.", __FUNCTION__);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001762 return false;
1763 }
1764
1765 // Perform expression evaluation
1766 if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
1767 return false;
1768 }
1769
1770 // Assign results to allocation members
Ewan Crawford8b244e22015-11-30 10:29:49 +00001771 elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
1772 elem.type_kind = static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
1773 elem.type_vec_size = static_cast<uint32_t>(results[2]);
1774 elem.field_count = static_cast<uint32_t>(results[3]);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001775
1776 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001777 log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32 ", vector size %" PRIu32 ", field count %" PRIu32,
1778 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(), *elem.type_vec_size.get(), *elem.field_count.get());
Ewan Crawford8b244e22015-11-30 10:29:49 +00001779
1780 // If this Element has subelements then JIT rsaElementGetSubElements() for details about its fields
1781 if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
1782 return false;
1783
1784 return true;
1785}
1786
1787// JITs the RS runtime for information about the subelements/fields of a struct allocation
1788// This is necessary for infering the struct type so we can pretty print the allocation's contents.
1789// Returns true on success, false otherwise
1790bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001791RenderScriptRuntime::JITSubelements(Element &elem, const lldb::addr_t context, StackFrame *frame_ptr)
Ewan Crawford8b244e22015-11-30 10:29:49 +00001792{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001793 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawford8b244e22015-11-30 10:29:49 +00001794
1795 if (!elem.element_ptr.isValid() || !elem.field_count.isValid())
1796 {
1797 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001798 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
Ewan Crawford8b244e22015-11-30 10:29:49 +00001799 return false;
1800 }
1801
1802 const short num_exprs = 3;
1803 assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) && "Invalid number of expressions");
1804
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001805 char expr_buffer[jit_max_expr_size];
Ewan Crawford8b244e22015-11-30 10:29:49 +00001806 uint64_t results;
1807
1808 // Iterate over struct fields.
1809 const uint32_t field_count = *elem.field_count.get();
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001810 for (uint32_t field_index = 0; field_index < field_count; ++field_index)
Ewan Crawford8b244e22015-11-30 10:29:49 +00001811 {
1812 Element child;
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001813 for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index)
Ewan Crawford8b244e22015-11-30 10:29:49 +00001814 {
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001815 const char *expr_cstr = JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
1816 int chars_written = snprintf(expr_buffer, jit_max_expr_size, expr_cstr,
Ewan Crawford8b244e22015-11-30 10:29:49 +00001817 field_count, field_count, field_count,
1818 context, *elem.element_ptr.get(), field_count, field_index);
1819 if (chars_written < 0)
1820 {
1821 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001822 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
Ewan Crawford8b244e22015-11-30 10:29:49 +00001823 return false;
1824 }
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001825 else if (chars_written >= jit_max_expr_size)
Ewan Crawford8b244e22015-11-30 10:29:49 +00001826 {
1827 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001828 log->Printf("%s - expression too long.", __FUNCTION__);
Ewan Crawford8b244e22015-11-30 10:29:49 +00001829 return false;
1830 }
1831
1832 // Perform expression evaluation
1833 if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
1834 return false;
1835
1836 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001837 log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
Ewan Crawford8b244e22015-11-30 10:29:49 +00001838
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001839 switch (expr_index)
Ewan Crawford8b244e22015-11-30 10:29:49 +00001840 {
1841 case 0: // Element* of child
1842 child.element_ptr = static_cast<addr_t>(results);
1843 break;
1844 case 1: // Name of child
1845 {
1846 lldb::addr_t address = static_cast<addr_t>(results);
1847 Error err;
1848 std::string name;
1849 GetProcess()->ReadCStringFromMemory(address, name, err);
1850 if (!err.Fail())
1851 child.type_name = ConstString(name);
1852 else
1853 {
1854 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001855 log->Printf("%s - warning: Couldn't read field name.", __FUNCTION__);
Ewan Crawford8b244e22015-11-30 10:29:49 +00001856 }
1857 break;
1858 }
1859 case 2: // Array size of child
1860 child.array_size = static_cast<uint32_t>(results);
1861 break;
1862 }
1863 }
1864
1865 // We need to recursively JIT each Element field of the struct since
1866 // structs can be nested inside structs.
1867 if (!JITElementPacked(child, context, frame_ptr))
1868 return false;
1869 elem.children.push_back(child);
1870 }
1871
1872 // Try to infer the name of the struct type so we can pretty print the allocation contents.
1873 FindStructTypeName(elem, frame_ptr);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001874
1875 return true;
1876}
1877
Ewan Crawforda0f08672015-10-16 08:28:47 +00001878// JITs the RS runtime for the address of the last element in the allocation.
1879// The `elem_size` paramter represents the size of a single element, including padding.
1880// Which is needed as an offset from the last element pointer.
1881// Using this offset minus the starting address we can calculate the size of the allocation.
1882// Returns true on success, false otherwise
1883bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001884RenderScriptRuntime::JITAllocationSize(AllocationDetails *allocation, StackFrame *frame_ptr)
Ewan Crawforda0f08672015-10-16 08:28:47 +00001885{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001886 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawforda0f08672015-10-16 08:28:47 +00001887
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001888 if (!allocation->address.isValid() || !allocation->dimension.isValid() || !allocation->data_ptr.isValid() ||
1889 !allocation->element.datum_size.isValid())
Ewan Crawforda0f08672015-10-16 08:28:47 +00001890 {
1891 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001892 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
Ewan Crawforda0f08672015-10-16 08:28:47 +00001893 return false;
1894 }
1895
Ewan Crawforda0f08672015-10-16 08:28:47 +00001896 // Find dimensions
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001897 uint32_t dim_x = allocation->dimension.get()->dim_1;
1898 uint32_t dim_y = allocation->dimension.get()->dim_2;
1899 uint32_t dim_z = allocation->dimension.get()->dim_3;
Ewan Crawforda0f08672015-10-16 08:28:47 +00001900
Ewan Crawford8b244e22015-11-30 10:29:49 +00001901 // Our plan of jitting the last element address doesn't seem to work for struct Allocations
1902 // Instead try to infer the size ourselves without any inter element padding.
1903 if (allocation->element.children.size() > 0)
1904 {
1905 if (dim_x == 0) dim_x = 1;
1906 if (dim_y == 0) dim_y = 1;
1907 if (dim_z == 0) dim_z = 1;
1908
1909 allocation->size = dim_x * dim_y * dim_z * *allocation->element.datum_size.get();
1910
1911 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001912 log->Printf("%s - infered size of struct allocation %" PRIu32 ".", __FUNCTION__,
1913 *allocation->size.get());
Ewan Crawford8b244e22015-11-30 10:29:49 +00001914 return true;
1915 }
1916
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001917 const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1918 char buffer[jit_max_expr_size];
Ewan Crawford8b244e22015-11-30 10:29:49 +00001919
Ewan Crawforda0f08672015-10-16 08:28:47 +00001920 // Calculate last element
1921 dim_x = dim_x == 0 ? 0 : dim_x - 1;
1922 dim_y = dim_y == 0 ? 0 : dim_y - 1;
1923 dim_z = dim_z == 0 ? 0 : dim_z - 1;
1924
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001925 int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), dim_x, dim_y, dim_z);
Ewan Crawforda0f08672015-10-16 08:28:47 +00001926 if (chars_written < 0)
1927 {
1928 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001929 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
Ewan Crawforda0f08672015-10-16 08:28:47 +00001930 return false;
1931 }
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001932 else if (chars_written >= jit_max_expr_size)
Ewan Crawforda0f08672015-10-16 08:28:47 +00001933 {
1934 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001935 log->Printf("%s - expression too long.", __FUNCTION__);
Ewan Crawforda0f08672015-10-16 08:28:47 +00001936 return false;
1937 }
1938
1939 uint64_t result = 0;
1940 if (!EvalRSExpression(buffer, frame_ptr, &result))
1941 return false;
1942
1943 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1944 // Find pointer to last element and add on size of an element
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001945 allocation->size =
1946 static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()) + *allocation->element.datum_size.get();
Ewan Crawforda0f08672015-10-16 08:28:47 +00001947
1948 return true;
1949}
1950
1951// JITs the RS runtime for information about the stride between rows in the allocation.
1952// This is done to detect padding, since allocated memory is 16-byte aligned.
1953// Returns true on success, false otherwise
1954bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001955RenderScriptRuntime::JITAllocationStride(AllocationDetails *allocation, StackFrame *frame_ptr)
Ewan Crawforda0f08672015-10-16 08:28:47 +00001956{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001957 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawforda0f08672015-10-16 08:28:47 +00001958
1959 if (!allocation->address.isValid() || !allocation->data_ptr.isValid())
1960 {
1961 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001962 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
Ewan Crawforda0f08672015-10-16 08:28:47 +00001963 return false;
1964 }
1965
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001966 const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1967 char buffer[jit_max_expr_size];
Ewan Crawforda0f08672015-10-16 08:28:47 +00001968
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001969 int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), 0, 1, 0);
Ewan Crawforda0f08672015-10-16 08:28:47 +00001970 if (chars_written < 0)
1971 {
1972 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001973 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
Ewan Crawforda0f08672015-10-16 08:28:47 +00001974 return false;
1975 }
Ewan Crawfordea0636b2016-02-10 11:23:27 +00001976 else if (chars_written >= jit_max_expr_size)
Ewan Crawforda0f08672015-10-16 08:28:47 +00001977 {
1978 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001979 log->Printf("%s - expression too long.", __FUNCTION__);
Ewan Crawforda0f08672015-10-16 08:28:47 +00001980 return false;
1981 }
1982
1983 uint64_t result = 0;
1984 if (!EvalRSExpression(buffer, frame_ptr, &result))
1985 return false;
1986
1987 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1988 allocation->stride = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get());
1989
1990 return true;
1991}
1992
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001993// JIT all the current runtime info regarding an allocation
1994bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00001995RenderScriptRuntime::RefreshAllocation(AllocationDetails *allocation, StackFrame *frame_ptr)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00001996{
1997 // GetOffsetPointer()
1998 if (!JITDataPointer(allocation, frame_ptr))
1999 return false;
2000
2001 // rsaAllocationGetType()
2002 if (!JITTypePointer(allocation, frame_ptr))
2003 return false;
2004
2005 // rsaTypeGetNativeData()
2006 if (!JITTypePacked(allocation, frame_ptr))
2007 return false;
2008
2009 // rsaElementGetNativeData()
Ewan Crawford8b244e22015-11-30 10:29:49 +00002010 if (!JITElementPacked(allocation->element, *allocation->context.get(), frame_ptr))
Ewan Crawford15f2bd92015-10-06 08:42:32 +00002011 return false;
2012
Ewan Crawford8b244e22015-11-30 10:29:49 +00002013 // Sets the datum_size member in Element
2014 SetElementSize(allocation->element);
2015
Ewan Crawford55232f02015-10-21 08:50:42 +00002016 // Use GetOffsetPointer() to infer size of the allocation
Ewan Crawford8b244e22015-11-30 10:29:49 +00002017 if (!JITAllocationSize(allocation, frame_ptr))
Ewan Crawford55232f02015-10-21 08:50:42 +00002018 return false;
2019
2020 return true;
2021}
2022
Ewan Crawford8b244e22015-11-30 10:29:49 +00002023// Function attempts to set the type_name member of the paramaterised Element object.
2024// This string should be the name of the struct type the Element represents.
2025// We need this string for pretty printing the Element to users.
2026void
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002027RenderScriptRuntime::FindStructTypeName(Element &elem, StackFrame *frame_ptr)
Ewan Crawford55232f02015-10-21 08:50:42 +00002028{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002029 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawford8b244e22015-11-30 10:29:49 +00002030
2031 if (!elem.type_name.IsEmpty()) // Name already set
2032 return;
2033 else
Adrian McCarthyfe06b5a2015-11-30 22:18:43 +00002034 elem.type_name = Element::GetFallbackStructName(); // Default type name if we don't succeed
Ewan Crawford8b244e22015-11-30 10:29:49 +00002035
2036 // Find all the global variables from the script rs modules
2037 VariableList variable_list;
2038 for (auto module_sp : m_rsmodules)
2039 module_sp->m_module->FindGlobalVariables(RegularExpression("."), true, UINT32_MAX, variable_list);
2040
2041 // Iterate over all the global variables looking for one with a matching type to the Element.
2042 // We make the assumption a match exists since there needs to be a global variable to reflect the
2043 // struct type back into java host code.
2044 for (uint32_t var_index = 0; var_index < variable_list.GetSize(); ++var_index)
2045 {
2046 const VariableSP var_sp(variable_list.GetVariableAtIndex(var_index));
2047 if (!var_sp)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002048 continue;
Ewan Crawford8b244e22015-11-30 10:29:49 +00002049
2050 ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
2051 if (!valobj_sp)
2052 continue;
2053
2054 // Find the number of variable fields.
2055 // If it has no fields, or more fields than our Element, then it can't be the struct we're looking for.
2056 // Don't check for equality since RS can add extra struct members for padding.
2057 size_t num_children = valobj_sp->GetNumChildren();
2058 if (num_children > elem.children.size() || num_children == 0)
2059 continue;
2060
2061 // Iterate over children looking for members with matching field names.
2062 // If all the field names match, this is likely the struct we want.
2063 //
2064 // TODO: This could be made more robust by also checking children data sizes, or array size
2065 bool found = true;
2066 for (size_t child_index = 0; child_index < num_children; ++child_index)
2067 {
2068 ValueObjectSP child = valobj_sp->GetChildAtIndex(child_index, true);
2069 if (!child || (child->GetName() != elem.children[child_index].type_name))
2070 {
2071 found = false;
2072 break;
2073 }
2074 }
2075
2076 // RS can add extra struct members for padding in the format '#rs_padding_[0-9]+'
2077 if (found && num_children < elem.children.size())
2078 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002079 const uint32_t size_diff = elem.children.size() - num_children;
Ewan Crawford8b244e22015-11-30 10:29:49 +00002080 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002081 log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__, size_diff);
Ewan Crawford8b244e22015-11-30 10:29:49 +00002082
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002083 for (uint32_t padding_index = 0; padding_index < size_diff; ++padding_index)
Ewan Crawford8b244e22015-11-30 10:29:49 +00002084 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002085 const ConstString &name = elem.children[num_children + padding_index].type_name;
Ewan Crawford8b244e22015-11-30 10:29:49 +00002086 if (strcmp(name.AsCString(), "#rs_padding") < 0)
2087 found = false;
2088 }
2089 }
2090
2091 // We've found a global var with matching type
2092 if (found)
2093 {
2094 // Dereference since our Element type isn't a pointer.
2095 if (valobj_sp->IsPointerType())
2096 {
2097 Error err;
2098 ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
2099 if (!err.Fail())
2100 valobj_sp = deref_valobj;
2101 }
2102
2103 // Save name of variable in Element.
2104 elem.type_name = valobj_sp->GetTypeName();
2105 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002106 log->Printf("%s - element name set to %s", __FUNCTION__, elem.type_name.AsCString());
Ewan Crawford8b244e22015-11-30 10:29:49 +00002107
2108 return;
2109 }
2110 }
2111}
2112
2113// Function sets the datum_size member of Element. Representing the size of a single instance including padding.
2114// Assumes the relevant allocation information has already been jitted.
2115void
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002116RenderScriptRuntime::SetElementSize(Element &elem)
Ewan Crawford8b244e22015-11-30 10:29:49 +00002117{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002118 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawford8b244e22015-11-30 10:29:49 +00002119 const Element::DataType type = *elem.type.get();
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002120 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT && "Invalid allocation type");
Ewan Crawford55232f02015-10-21 08:50:42 +00002121
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002122 const uint32_t vec_size = *elem.type_vec_size.get();
2123 uint32_t data_size = 0;
2124 uint32_t padding = 0;
Ewan Crawford55232f02015-10-21 08:50:42 +00002125
Ewan Crawford8b244e22015-11-30 10:29:49 +00002126 // Element is of a struct type, calculate size recursively.
2127 if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0))
2128 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002129 for (Element &child : elem.children)
Ewan Crawford8b244e22015-11-30 10:29:49 +00002130 {
2131 SetElementSize(child);
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002132 const uint32_t array_size = child.array_size.isValid() ? *child.array_size.get() : 1;
Ewan Crawford8b244e22015-11-30 10:29:49 +00002133 data_size += *child.datum_size.get() * array_size;
2134 }
2135 }
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002136 // These have been packed already
2137 else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2138 type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2139 type == Element::RS_TYPE_UNSIGNED_4_4_4_4)
Ewan Crawford2e920712015-12-17 16:40:05 +00002140 {
2141 data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2142 }
2143 else if (type < Element::RS_TYPE_ELEMENT)
2144 {
Ewan Crawford8b244e22015-11-30 10:29:49 +00002145 data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
Ewan Crawford2e920712015-12-17 16:40:05 +00002146 if (vec_size == 3)
2147 padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2148 }
2149 else
2150 data_size = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
Ewan Crawford8b244e22015-11-30 10:29:49 +00002151
2152 elem.padding = padding;
2153 elem.datum_size = data_size + padding;
2154 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002155 log->Printf("%s - element size set to %" PRIu32, __FUNCTION__, data_size + padding);
Ewan Crawford55232f02015-10-21 08:50:42 +00002156}
2157
2158// Given an allocation, this function copies the allocation contents from device into a buffer on the heap.
2159// Returning a shared pointer to the buffer containing the data.
2160std::shared_ptr<uint8_t>
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002161RenderScriptRuntime::GetAllocationData(AllocationDetails *allocation, StackFrame *frame_ptr)
Ewan Crawford55232f02015-10-21 08:50:42 +00002162{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002163 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawford55232f02015-10-21 08:50:42 +00002164
2165 // JIT all the allocation details
Ewan Crawford8b590622015-12-10 10:20:39 +00002166 if (allocation->shouldRefresh())
Ewan Crawford55232f02015-10-21 08:50:42 +00002167 {
2168 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002169 log->Printf("%s - allocation details not calculated yet, jitting info", __FUNCTION__);
Ewan Crawford55232f02015-10-21 08:50:42 +00002170
2171 if (!RefreshAllocation(allocation, frame_ptr))
2172 {
2173 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002174 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
Ewan Crawford55232f02015-10-21 08:50:42 +00002175 return nullptr;
2176 }
2177 }
2178
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002179 assert(allocation->data_ptr.isValid() && allocation->element.type.isValid() &&
2180 allocation->element.type_vec_size.isValid() && allocation->size.isValid() &&
2181 "Allocation information not available");
Ewan Crawford55232f02015-10-21 08:50:42 +00002182
2183 // Allocate a buffer to copy data into
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002184 const uint32_t size = *allocation->size.get();
Ewan Crawford55232f02015-10-21 08:50:42 +00002185 std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2186 if (!buffer)
2187 {
2188 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002189 log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer", __FUNCTION__, size);
Ewan Crawford55232f02015-10-21 08:50:42 +00002190 return nullptr;
2191 }
2192
2193 // Read the inferior memory
2194 Error error;
2195 lldb::addr_t data_ptr = *allocation->data_ptr.get();
2196 GetProcess()->ReadMemory(data_ptr, buffer.get(), size, error);
2197 if (error.Fail())
2198 {
2199 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002200 log->Printf("%s - '%s' Couldn't read %" PRIu32 " bytes of allocation data from 0x%" PRIx64,
2201 __FUNCTION__, error.AsCString(), size, data_ptr);
Ewan Crawford55232f02015-10-21 08:50:42 +00002202 return nullptr;
2203 }
2204
2205 return buffer;
2206}
2207
2208// Function copies data from a binary file into an allocation.
2209// There is a header at the start of the file, FileHeader, before the data content itself.
2210// Information from this header is used to display warnings to the user about incompatabilities
2211bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002212RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id, const char *filename, StackFrame *frame_ptr)
Ewan Crawford55232f02015-10-21 08:50:42 +00002213{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002214 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawford55232f02015-10-21 08:50:42 +00002215
2216 // Find allocation with the given id
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002217 AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
Ewan Crawford55232f02015-10-21 08:50:42 +00002218 if (!alloc)
2219 return false;
2220
2221 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002222 log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__, *alloc->address.get());
Ewan Crawford55232f02015-10-21 08:50:42 +00002223
2224 // JIT all the allocation details
Ewan Crawford8b590622015-12-10 10:20:39 +00002225 if (alloc->shouldRefresh())
Ewan Crawford55232f02015-10-21 08:50:42 +00002226 {
2227 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002228 log->Printf("%s - allocation details not calculated yet, jitting info.", __FUNCTION__);
Ewan Crawford55232f02015-10-21 08:50:42 +00002229
2230 if (!RefreshAllocation(alloc, frame_ptr))
2231 {
2232 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002233 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
Sylvestre Ledru4cfc9192015-10-26 08:49:04 +00002234 return false;
Ewan Crawford55232f02015-10-21 08:50:42 +00002235 }
2236 }
2237
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002238 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid() &&
2239 alloc->size.isValid() && alloc->element.datum_size.isValid() && "Allocation information not available");
Ewan Crawford55232f02015-10-21 08:50:42 +00002240
2241 // Check we can read from file
2242 FileSpec file(filename, true);
2243 if (!file.Exists())
2244 {
2245 strm.Printf("Error: File %s does not exist", filename);
2246 strm.EOL();
2247 return false;
2248 }
2249
2250 if (!file.Readable())
2251 {
2252 strm.Printf("Error: File %s does not have readable permissions", filename);
2253 strm.EOL();
2254 return false;
2255 }
2256
2257 // Read file into data buffer
2258 DataBufferSP data_sp(file.ReadFileContents());
2259
2260 // Cast start of buffer to FileHeader and use pointer to read metadata
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002261 void *file_buffer = data_sp->GetBytes();
2262 if (file_buffer == nullptr ||
2263 data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) + sizeof(AllocationDetails::ElementHeader)))
Ewan Crawford26e52a72016-01-07 10:19:09 +00002264 {
2265 strm.Printf("Error: File %s does not contain enough data for header", filename);
2266 strm.EOL();
2267 return false;
2268 }
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002269 const AllocationDetails::FileHeader *file_header = static_cast<AllocationDetails::FileHeader *>(file_buffer);
Ewan Crawford55232f02015-10-21 08:50:42 +00002270
Ewan Crawford26e52a72016-01-07 10:19:09 +00002271 // Check file starts with ascii characters "RSAD"
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002272 if (memcmp(file_header->ident, "RSAD", 4))
Ewan Crawford26e52a72016-01-07 10:19:09 +00002273 {
2274 strm.Printf("Error: File doesn't contain identifier for an RS allocation dump. Are you sure this is the correct file?");
2275 strm.EOL();
2276 return false;
2277 }
2278
2279 // Look at the type of the root element in the header
2280 AllocationDetails::ElementHeader root_element_header;
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002281 memcpy(&root_element_header, static_cast<uint8_t *>(file_buffer) + sizeof(AllocationDetails::FileHeader),
Ewan Crawford26e52a72016-01-07 10:19:09 +00002282 sizeof(AllocationDetails::ElementHeader));
Ewan Crawford55232f02015-10-21 08:50:42 +00002283
2284 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002285 log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32, __FUNCTION__,
Ewan Crawford26e52a72016-01-07 10:19:09 +00002286 root_element_header.type, root_element_header.element_size);
Ewan Crawford55232f02015-10-21 08:50:42 +00002287
2288 // Check if the target allocation and file both have the same number of bytes for an Element
Ewan Crawford26e52a72016-01-07 10:19:09 +00002289 if (*alloc->element.datum_size.get() != root_element_header.element_size)
Ewan Crawford55232f02015-10-21 08:50:42 +00002290 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002291 strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32 " bytes, allocation %" PRIu32 " bytes",
Ewan Crawford26e52a72016-01-07 10:19:09 +00002292 root_element_header.element_size, *alloc->element.datum_size.get());
Ewan Crawford55232f02015-10-21 08:50:42 +00002293 strm.EOL();
2294 }
2295
Ewan Crawford26e52a72016-01-07 10:19:09 +00002296 // Check if the target allocation and file both have the same type
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002297 const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
2298 const uint32_t file_type = root_element_header.type;
Ewan Crawford26e52a72016-01-07 10:19:09 +00002299
2300 if (file_type > Element::RS_TYPE_FONT)
2301 {
2302 strm.Printf("Warning: File has unknown allocation type");
2303 strm.EOL();
2304 }
2305 else if (alloc_type != file_type)
Ewan Crawford55232f02015-10-21 08:50:42 +00002306 {
Ewan Crawford2e920712015-12-17 16:40:05 +00002307 // Enum value isn't monotonous, so doesn't always index RsDataTypeToString array
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002308 uint32_t printable_target_type_index = alloc_type;
2309 uint32_t printable_head_type_index = file_type;
Ewan Crawford26e52a72016-01-07 10:19:09 +00002310 if (alloc_type >= Element::RS_TYPE_ELEMENT && alloc_type <= Element::RS_TYPE_FONT)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002311 printable_target_type_index = static_cast<Element::DataType>((alloc_type - Element::RS_TYPE_ELEMENT) +
2312 Element::RS_TYPE_MATRIX_2X2 + 1);
Ewan Crawford2e920712015-12-17 16:40:05 +00002313
Ewan Crawford26e52a72016-01-07 10:19:09 +00002314 if (file_type >= Element::RS_TYPE_ELEMENT && file_type <= Element::RS_TYPE_FONT)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002315 printable_head_type_index = static_cast<Element::DataType>((file_type - Element::RS_TYPE_ELEMENT) +
2316 Element::RS_TYPE_MATRIX_2X2 + 1);
Ewan Crawford2e920712015-12-17 16:40:05 +00002317
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002318 const char *file_type_cstr = AllocationDetails::RsDataTypeToString[printable_head_type_index][0];
2319 const char *target_type_cstr = AllocationDetails::RsDataTypeToString[printable_target_type_index][0];
Ewan Crawford55232f02015-10-21 08:50:42 +00002320
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002321 strm.Printf("Warning: Mismatched Types - file '%s' type, allocation '%s' type", file_type_cstr,
2322 target_type_cstr);
Ewan Crawford55232f02015-10-21 08:50:42 +00002323 strm.EOL();
2324 }
2325
Ewan Crawford26e52a72016-01-07 10:19:09 +00002326 // Advance buffer past header
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002327 file_buffer = static_cast<uint8_t *>(file_buffer) + file_header->hdr_size;
Ewan Crawford26e52a72016-01-07 10:19:09 +00002328
Ewan Crawford55232f02015-10-21 08:50:42 +00002329 // Calculate size of allocation data in file
Ewan Crawford26e52a72016-01-07 10:19:09 +00002330 size_t length = data_sp->GetByteSize() - file_header->hdr_size;
Ewan Crawford55232f02015-10-21 08:50:42 +00002331
2332 // Check if the target allocation and file both have the same total data size.
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002333 const uint32_t alloc_size = *alloc->size.get();
Ewan Crawford55232f02015-10-21 08:50:42 +00002334 if (alloc_size != length)
2335 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002336 strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64 " bytes, allocation 0x%" PRIx32 " bytes",
2337 (uint64_t)length, alloc_size);
Ewan Crawford55232f02015-10-21 08:50:42 +00002338 strm.EOL();
2339 length = alloc_size < length ? alloc_size : length; // Set length to copy to minimum
2340 }
2341
2342 // Copy file data from our buffer into the target allocation.
2343 lldb::addr_t alloc_data = *alloc->data_ptr.get();
2344 Error error;
2345 size_t bytes_written = GetProcess()->WriteMemory(alloc_data, file_buffer, length, error);
2346 if (!error.Success() || bytes_written != length)
2347 {
2348 strm.Printf("Error: Couldn't write data to allocation %s", error.AsCString());
2349 strm.EOL();
2350 return false;
2351 }
2352
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002353 strm.Printf("Contents of file '%s' read into allocation %" PRIu32, filename, alloc->id);
Ewan Crawford55232f02015-10-21 08:50:42 +00002354 strm.EOL();
2355
2356 return true;
2357}
2358
Ewan Crawford26e52a72016-01-07 10:19:09 +00002359// Function takes as parameters a byte buffer, which will eventually be written to file as the element header,
2360// an offset into that buffer, and an Element that will be saved into the buffer at the parametrised offset.
2361// Return value is the new offset after writing the element into the buffer.
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002362// Elements are saved to the file as the ElementHeader struct followed by offsets to the structs of all the element's
2363// children.
Ewan Crawford26e52a72016-01-07 10:19:09 +00002364size_t
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002365RenderScriptRuntime::PopulateElementHeaders(const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2366 const Element &elem)
Ewan Crawford26e52a72016-01-07 10:19:09 +00002367{
2368 // File struct for an element header with all the relevant details copied from elem.
2369 // We assume members are valid already.
2370 AllocationDetails::ElementHeader elem_header;
2371 elem_header.type = *elem.type.get();
2372 elem_header.kind = *elem.type_kind.get();
2373 elem_header.element_size = *elem.datum_size.get();
2374 elem_header.vector_size = *elem.type_vec_size.get();
2375 elem_header.array_size = elem.array_size.isValid() ? *elem.array_size.get() : 0;
2376 const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
2377
2378 // Copy struct into buffer and advance offset
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002379 // We assume that header_buffer has been checked for nullptr before this method is called
Ewan Crawford26e52a72016-01-07 10:19:09 +00002380 memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
2381 offset += elem_header_size;
2382
2383 // Starting offset of child ElementHeader struct
2384 size_t child_offset = offset + ((elem.children.size() + 1) * sizeof(uint32_t));
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002385 for (const RenderScriptRuntime::Element &child : elem.children)
Ewan Crawford26e52a72016-01-07 10:19:09 +00002386 {
2387 // Recursively populate the buffer with the element header structs of children.
2388 // Then save the offsets where they were set after the parent element header.
2389 memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
2390 offset += sizeof(uint32_t);
2391
2392 child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
2393 }
2394
2395 // Zero indicates no more children
2396 memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
2397
2398 return child_offset;
2399}
2400
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002401// Given an Element object this function returns the total size needed in the file header to store the element's
2402// details.
Ewan Crawford26e52a72016-01-07 10:19:09 +00002403// Taking into account the size of the element header struct, plus the offsets to all the element's children.
2404// Function is recursive so that the size of all ancestors is taken into account.
2405size_t
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002406RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem)
Ewan Crawford26e52a72016-01-07 10:19:09 +00002407{
2408 size_t size = (elem.children.size() + 1) * sizeof(uint32_t); // Offsets to children plus zero terminator
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002409 size += sizeof(AllocationDetails::ElementHeader); // Size of header struct with type details
Ewan Crawford26e52a72016-01-07 10:19:09 +00002410
2411 // Calculate recursively for all descendants
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002412 for (const Element &child : elem.children)
Ewan Crawford26e52a72016-01-07 10:19:09 +00002413 size += CalculateElementHeaderSize(child);
2414
2415 return size;
2416}
2417
Ewan Crawford55232f02015-10-21 08:50:42 +00002418// Function copies allocation contents into a binary file.
2419// This file can then be loaded later into a different allocation.
2420// There is a header, FileHeader, before the allocation data containing meta-data.
2421bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002422RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id, const char *filename, StackFrame *frame_ptr)
Ewan Crawford55232f02015-10-21 08:50:42 +00002423{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002424 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawford55232f02015-10-21 08:50:42 +00002425
2426 // Find allocation with the given id
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002427 AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
Ewan Crawford55232f02015-10-21 08:50:42 +00002428 if (!alloc)
2429 return false;
2430
2431 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002432 log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__, *alloc->address.get());
Ewan Crawford55232f02015-10-21 08:50:42 +00002433
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002434 // JIT all the allocation details
Ewan Crawford8b590622015-12-10 10:20:39 +00002435 if (alloc->shouldRefresh())
Ewan Crawford55232f02015-10-21 08:50:42 +00002436 {
2437 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002438 log->Printf("%s - allocation details not calculated yet, jitting info.", __FUNCTION__);
Ewan Crawford55232f02015-10-21 08:50:42 +00002439
2440 if (!RefreshAllocation(alloc, frame_ptr))
2441 {
2442 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002443 log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
Sylvestre Ledru4cfc9192015-10-26 08:49:04 +00002444 return false;
Ewan Crawford55232f02015-10-21 08:50:42 +00002445 }
2446 }
2447
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002448 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid() &&
2449 alloc->element.datum_size.get() && alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2450 "Allocation information not available");
Ewan Crawford55232f02015-10-21 08:50:42 +00002451
2452 // Check we can create writable file
2453 FileSpec file_spec(filename, true);
2454 File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionTruncate);
2455 if (!file)
2456 {
2457 strm.Printf("Error: Failed to open '%s' for writing", filename);
2458 strm.EOL();
2459 return false;
2460 }
2461
2462 // Read allocation into buffer of heap memory
2463 const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2464 if (!buffer)
2465 {
2466 strm.Printf("Error: Couldn't read allocation data into buffer");
2467 strm.EOL();
2468 return false;
2469 }
2470
2471 // Create the file header
2472 AllocationDetails::FileHeader head;
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002473 memcpy(head.ident, "RSAD", 4);
Ewan Crawford2d623282015-10-21 10:27:10 +00002474 head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
2475 head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
2476 head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
Ewan Crawford26e52a72016-01-07 10:19:09 +00002477
2478 const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2479 assert((sizeof(AllocationDetails::FileHeader) + element_header_size) < UINT16_MAX && "Element header too large");
2480 head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) + element_header_size);
Ewan Crawford55232f02015-10-21 08:50:42 +00002481
2482 // Write the file header
2483 size_t num_bytes = sizeof(AllocationDetails::FileHeader);
Ewan Crawford26e52a72016-01-07 10:19:09 +00002484 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002485 log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__, num_bytes);
Ewan Crawford26e52a72016-01-07 10:19:09 +00002486
2487 Error err = file.Write(&head, num_bytes);
2488 if (!err.Success())
2489 {
2490 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
2491 strm.EOL();
2492 return false;
2493 }
2494
2495 // Create the headers describing the element type of the allocation.
2496 std::shared_ptr<uint8_t> element_header_buffer(new uint8_t[element_header_size]);
2497 if (element_header_buffer == nullptr)
2498 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002499 strm.Printf("Internal Error: Couldn't allocate %" PRIu64 " bytes on the heap", element_header_size);
Ewan Crawford26e52a72016-01-07 10:19:09 +00002500 strm.EOL();
2501 return false;
2502 }
2503
2504 PopulateElementHeaders(element_header_buffer, 0, alloc->element);
2505
2506 // Write headers for allocation element type to file
2507 num_bytes = element_header_size;
2508 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002509 log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.", __FUNCTION__, num_bytes);
Ewan Crawford26e52a72016-01-07 10:19:09 +00002510
2511 err = file.Write(element_header_buffer.get(), num_bytes);
Ewan Crawford55232f02015-10-21 08:50:42 +00002512 if (!err.Success())
2513 {
2514 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
2515 strm.EOL();
2516 return false;
2517 }
2518
2519 // Write allocation data to file
2520 num_bytes = static_cast<size_t>(*alloc->size.get());
2521 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002522 log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__, num_bytes);
Ewan Crawford55232f02015-10-21 08:50:42 +00002523
2524 err = file.Write(buffer.get(), num_bytes);
2525 if (!err.Success())
2526 {
2527 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
2528 strm.EOL();
2529 return false;
2530 }
2531
2532 strm.Printf("Allocation written to file '%s'", filename);
2533 strm.EOL();
Ewan Crawford15f2bd92015-10-06 08:42:32 +00002534 return true;
2535}
2536
Colin Riley5ec532a2015-04-09 16:49:25 +00002537bool
2538RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp)
2539{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002540 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Colin Riley4640cde2015-06-01 18:23:41 +00002541
Colin Riley5ec532a2015-04-09 16:49:25 +00002542 if (module_sp)
2543 {
2544 for (const auto &rs_module : m_rsmodules)
2545 {
Colin Riley4640cde2015-06-01 18:23:41 +00002546 if (rs_module->m_module == module_sp)
Ewan Crawford7dc77712015-09-10 10:08:48 +00002547 {
2548 // Check if the user has enabled automatically breaking on
2549 // all RS kernels.
2550 if (m_breakAllKernels)
2551 BreakOnModuleKernels(rs_module);
2552
Colin Riley5ec532a2015-04-09 16:49:25 +00002553 return false;
Ewan Crawford7dc77712015-09-10 10:08:48 +00002554 }
Colin Riley5ec532a2015-04-09 16:49:25 +00002555 }
Colin Rileyef20b082015-04-14 07:39:24 +00002556 bool module_loaded = false;
2557 switch (GetModuleKind(module_sp))
Colin Riley5ec532a2015-04-09 16:49:25 +00002558 {
Colin Rileyef20b082015-04-14 07:39:24 +00002559 case eModuleKindKernelObj:
2560 {
Colin Riley4640cde2015-06-01 18:23:41 +00002561 RSModuleDescriptorSP module_desc;
2562 module_desc.reset(new RSModuleDescriptor(module_sp));
2563 if (module_desc->ParseRSInfo())
Colin Rileyef20b082015-04-14 07:39:24 +00002564 {
2565 m_rsmodules.push_back(module_desc);
2566 module_loaded = true;
2567 }
Colin Riley4640cde2015-06-01 18:23:41 +00002568 if (module_loaded)
2569 {
2570 FixupScriptDetails(module_desc);
2571 }
Colin Rileyef20b082015-04-14 07:39:24 +00002572 break;
2573 }
2574 case eModuleKindDriver:
Colin Riley4640cde2015-06-01 18:23:41 +00002575 {
2576 if (!m_libRSDriver)
2577 {
2578 m_libRSDriver = module_sp;
2579 LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
2580 }
2581 break;
2582 }
Colin Rileyef20b082015-04-14 07:39:24 +00002583 case eModuleKindImpl:
Colin Riley4640cde2015-06-01 18:23:41 +00002584 {
2585 m_libRSCpuRef = module_sp;
2586 break;
2587 }
Colin Rileyef20b082015-04-14 07:39:24 +00002588 case eModuleKindLibRS:
Colin Riley4640cde2015-06-01 18:23:41 +00002589 {
Aidan Dodds35e7b1a2016-01-06 15:43:52 +00002590 if (!m_libRS)
Colin Riley4640cde2015-06-01 18:23:41 +00002591 {
2592 m_libRS = module_sp;
2593 static ConstString gDbgPresentStr("gDebuggerPresent");
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002594 const Symbol *debug_present =
2595 m_libRS->FindFirstSymbolWithNameAndType(gDbgPresentStr, eSymbolTypeData);
Colin Riley4640cde2015-06-01 18:23:41 +00002596 if (debug_present)
2597 {
2598 Error error;
2599 uint32_t flag = 0x00000001U;
2600 Target &target = GetProcess()->GetTarget();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002601 addr_t addr = debug_present->GetLoadAddress(&target);
Colin Riley4640cde2015-06-01 18:23:41 +00002602 GetProcess()->WriteMemory(addr, &flag, sizeof(flag), error);
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002603 if (error.Success())
Colin Riley4640cde2015-06-01 18:23:41 +00002604 {
2605 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002606 log->Printf("%s - debugger present flag set on debugee.", __FUNCTION__);
Colin Riley4640cde2015-06-01 18:23:41 +00002607
2608 m_debuggerPresentFlagged = true;
2609 }
2610 else if (log)
2611 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002612 log->Printf("%s - error writing debugger present flags '%s' ", __FUNCTION__,
2613 error.AsCString());
Colin Riley4640cde2015-06-01 18:23:41 +00002614 }
2615 }
2616 else if (log)
2617 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002618 log->Printf("%s - error writing debugger present flags - symbol not found", __FUNCTION__);
Colin Riley4640cde2015-06-01 18:23:41 +00002619 }
2620 }
2621 break;
2622 }
Colin Rileyef20b082015-04-14 07:39:24 +00002623 default:
2624 break;
Colin Riley5ec532a2015-04-09 16:49:25 +00002625 }
Colin Rileyef20b082015-04-14 07:39:24 +00002626 if (module_loaded)
Aidan Dodds35e7b1a2016-01-06 15:43:52 +00002627 Update();
Colin Rileyef20b082015-04-14 07:39:24 +00002628 return module_loaded;
Colin Riley5ec532a2015-04-09 16:49:25 +00002629 }
2630 return false;
2631}
2632
Colin Rileyef20b082015-04-14 07:39:24 +00002633void
2634RenderScriptRuntime::Update()
2635{
2636 if (m_rsmodules.size() > 0)
2637 {
2638 if (!m_initiated)
2639 {
2640 Initiate();
2641 }
2642 }
2643}
2644
Colin Riley5ec532a2015-04-09 16:49:25 +00002645// The maximum line length of an .rs.info packet
2646#define MAXLINE 500
Aidan Doddsb0be30f2016-02-18 10:59:46 +00002647#define STRINGIFY(x) #x
2648#define MAXLINESTR_(x) "%" STRINGIFY(x) "s"
2649#define MAXLINESTR MAXLINESTR_(MAXLINE)
Colin Riley5ec532a2015-04-09 16:49:25 +00002650
2651// The .rs.info symbol in renderscript modules contains a string which needs to be parsed.
2652// The string is basic and is parsed on a line by line basis.
2653bool
2654RSModuleDescriptor::ParseRSInfo()
2655{
Aidan Doddsb0be30f2016-02-18 10:59:46 +00002656 assert(m_module);
Colin Riley5ec532a2015-04-09 16:49:25 +00002657 const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
Aidan Doddsb0be30f2016-02-18 10:59:46 +00002658 if (!info_sym)
2659 return false;
2660
2661 const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
2662 if (addr == LLDB_INVALID_ADDRESS)
2663 return false;
2664
2665 const addr_t size = info_sym->GetByteSize();
2666 const FileSpec fs = m_module->GetFileSpec();
2667
2668 const DataBufferSP buffer = fs.ReadFileContents(addr, size);
2669 if (!buffer)
2670 return false;
2671
2672 // split rs.info. contents into lines
2673 std::vector<std::string> info_lines;
Colin Riley5ec532a2015-04-09 16:49:25 +00002674 {
Aidan Doddsb0be30f2016-02-18 10:59:46 +00002675 const std::string info((const char *)buffer->GetBytes());
2676 for (size_t tail = 0; tail < info.size();)
Colin Riley5ec532a2015-04-09 16:49:25 +00002677 {
Aidan Doddsb0be30f2016-02-18 10:59:46 +00002678 // find next new line or end of string
2679 size_t head = info.find('\n', tail);
2680 head = (head == std::string::npos) ? info.size() : head;
2681 std::string line = info.substr(tail, head - tail);
2682 // add to line list
2683 info_lines.push_back(line);
2684 tail = head + 1;
Colin Riley5ec532a2015-04-09 16:49:25 +00002685 }
Colin Riley5ec532a2015-04-09 16:49:25 +00002686 }
Aidan Doddsb0be30f2016-02-18 10:59:46 +00002687
Saleem Abdulrasool7ccf1372016-02-23 04:56:31 +00002688 std::array<char, MAXLINE> name{{'\0'}};
2689 std::array<char, MAXLINE> value{{'\0'}};
Aidan Doddsb0be30f2016-02-18 10:59:46 +00002690
2691 // parse all text lines of .rs.info
2692 for (auto line = info_lines.begin(); line != info_lines.end(); ++line)
2693 {
2694 uint32_t numDefns = 0;
2695 if (sscanf(line->c_str(), "exportVarCount: %" PRIu32 "", &numDefns) == 1)
2696 {
2697 while (numDefns--)
2698 m_globals.push_back(RSGlobalDescriptor(this, (++line)->c_str()));
2699 }
2700 else if (sscanf(line->c_str(), "exportForEachCount: %" PRIu32 "", &numDefns) == 1)
2701 {
2702 while (numDefns--)
2703 {
2704 uint32_t slot = 0;
2705 name[0] = '\0';
2706 static const char *fmt_s = "%" PRIu32 " - " MAXLINESTR;
2707 if (sscanf((++line)->c_str(), fmt_s, &slot, name.data()) == 2)
2708 {
2709 if (name[0] != '\0')
2710 m_kernels.push_back(RSKernelDescriptor(this, name.data(), slot));
2711 }
2712 }
2713 }
2714 else if (sscanf(line->c_str(), "pragmaCount: %" PRIu32 "", &numDefns) == 1)
2715 {
2716 while (numDefns--)
2717 {
2718 name[0] = value[0] = '\0';
2719 static const char *fmt_s = MAXLINESTR " - " MAXLINESTR;
2720 if (sscanf((++line)->c_str(), fmt_s, name.data(), value.data()) != 0)
2721 {
2722 if (name[0] != '\0')
2723 m_pragmas[std::string(name.data())] = value.data();
2724 }
2725 }
2726 }
2727 else
2728 {
2729 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2730 if (log)
2731 {
2732 log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__, line->c_str());
2733 }
2734 }
2735 }
2736
2737 // 'root' kernel should always be present
2738 return m_kernels.size() > 0;
Colin Riley5ec532a2015-04-09 16:49:25 +00002739}
2740
Colin Riley5ec532a2015-04-09 16:49:25 +00002741void
Colin Riley4640cde2015-06-01 18:23:41 +00002742RenderScriptRuntime::Status(Stream &strm) const
2743{
2744 if (m_libRS)
2745 {
2746 strm.Printf("Runtime Library discovered.");
2747 strm.EOL();
2748 }
2749 if (m_libRSDriver)
2750 {
2751 strm.Printf("Runtime Driver discovered.");
2752 strm.EOL();
2753 }
2754 if (m_libRSCpuRef)
2755 {
2756 strm.Printf("CPU Reference Implementation discovered.");
2757 strm.EOL();
2758 }
Aidan Dodds35e7b1a2016-01-06 15:43:52 +00002759
Colin Riley4640cde2015-06-01 18:23:41 +00002760 if (m_runtimeHooks.size())
2761 {
2762 strm.Printf("Runtime functions hooked:");
2763 strm.EOL();
2764 for (auto b : m_runtimeHooks)
2765 {
2766 strm.Indent(b.second->defn->name);
2767 strm.EOL();
2768 }
Aidan Dodds35e7b1a2016-01-06 15:43:52 +00002769 }
Colin Riley4640cde2015-06-01 18:23:41 +00002770 else
2771 {
2772 strm.Printf("Runtime is not hooked.");
2773 strm.EOL();
2774 }
2775}
2776
Aidan Dodds35e7b1a2016-01-06 15:43:52 +00002777void
Colin Riley4640cde2015-06-01 18:23:41 +00002778RenderScriptRuntime::DumpContexts(Stream &strm) const
2779{
2780 strm.Printf("Inferred RenderScript Contexts:");
2781 strm.EOL();
2782 strm.IndentMore();
2783
2784 std::map<addr_t, uint64_t> contextReferences;
2785
Ewan Crawford78f339d2015-09-21 10:53:18 +00002786 // Iterate over all of the currently discovered scripts.
2787 // Note: We cant push or pop from m_scripts inside this loop or it may invalidate script.
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002788 for (const auto &script : m_scripts)
Colin Riley4640cde2015-06-01 18:23:41 +00002789 {
Ewan Crawford78f339d2015-09-21 10:53:18 +00002790 if (!script->context.isValid())
2791 continue;
2792 lldb::addr_t context = *script->context;
2793
2794 if (contextReferences.find(context) != contextReferences.end())
Colin Riley4640cde2015-06-01 18:23:41 +00002795 {
Ewan Crawford78f339d2015-09-21 10:53:18 +00002796 contextReferences[context]++;
Colin Riley4640cde2015-06-01 18:23:41 +00002797 }
2798 else
2799 {
Ewan Crawford78f339d2015-09-21 10:53:18 +00002800 contextReferences[context] = 1;
Colin Riley4640cde2015-06-01 18:23:41 +00002801 }
2802 }
2803
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002804 for (const auto &cRef : contextReferences)
Colin Riley4640cde2015-06-01 18:23:41 +00002805 {
2806 strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances", cRef.first, cRef.second);
2807 strm.EOL();
2808 }
2809 strm.IndentLess();
2810}
2811
Aidan Dodds35e7b1a2016-01-06 15:43:52 +00002812void
Colin Riley4640cde2015-06-01 18:23:41 +00002813RenderScriptRuntime::DumpKernels(Stream &strm) const
2814{
2815 strm.Printf("RenderScript Kernels:");
2816 strm.EOL();
2817 strm.IndentMore();
2818 for (const auto &module : m_rsmodules)
2819 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002820 strm.Printf("Resource '%s':", module->m_resname.c_str());
Colin Riley4640cde2015-06-01 18:23:41 +00002821 strm.EOL();
2822 for (const auto &kernel : module->m_kernels)
2823 {
2824 strm.Indent(kernel.m_name.AsCString());
2825 strm.EOL();
2826 }
2827 }
2828 strm.IndentLess();
2829}
2830
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002831RenderScriptRuntime::AllocationDetails *
Ewan Crawforda0f08672015-10-16 08:28:47 +00002832RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id)
2833{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002834 AllocationDetails *alloc = nullptr;
Ewan Crawforda0f08672015-10-16 08:28:47 +00002835
2836 // See if we can find allocation using id as an index;
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002837 if (alloc_id <= m_allocations.size() && alloc_id != 0 && m_allocations[alloc_id - 1]->id == alloc_id)
Ewan Crawforda0f08672015-10-16 08:28:47 +00002838 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002839 alloc = m_allocations[alloc_id - 1].get();
Ewan Crawforda0f08672015-10-16 08:28:47 +00002840 return alloc;
2841 }
2842
2843 // Fallback to searching
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002844 for (const auto &a : m_allocations)
Ewan Crawforda0f08672015-10-16 08:28:47 +00002845 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002846 if (a->id == alloc_id)
2847 {
2848 alloc = a.get();
2849 break;
2850 }
Ewan Crawforda0f08672015-10-16 08:28:47 +00002851 }
2852
2853 if (alloc == nullptr)
2854 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002855 strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32, alloc_id);
Ewan Crawforda0f08672015-10-16 08:28:47 +00002856 strm.EOL();
2857 }
2858
2859 return alloc;
2860}
2861
2862// Prints the contents of an allocation to the output stream, which may be a file
2863bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002864RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr, const uint32_t id)
Ewan Crawforda0f08672015-10-16 08:28:47 +00002865{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002866 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawforda0f08672015-10-16 08:28:47 +00002867
2868 // Check we can find the desired allocation
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002869 AllocationDetails *alloc = FindAllocByID(strm, id);
Ewan Crawforda0f08672015-10-16 08:28:47 +00002870 if (!alloc)
2871 return false; // FindAllocByID() will print error message for us here
2872
2873 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002874 log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__, *alloc->address.get());
Ewan Crawforda0f08672015-10-16 08:28:47 +00002875
2876 // Check we have information about the allocation, if not calculate it
Ewan Crawford8b590622015-12-10 10:20:39 +00002877 if (alloc->shouldRefresh())
Ewan Crawforda0f08672015-10-16 08:28:47 +00002878 {
2879 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002880 log->Printf("%s - allocation details not calculated yet, jitting info.", __FUNCTION__);
Ewan Crawforda0f08672015-10-16 08:28:47 +00002881
2882 // JIT all the allocation information
2883 if (!RefreshAllocation(alloc, frame_ptr))
2884 {
2885 strm.Printf("Error: Couldn't JIT allocation details");
2886 strm.EOL();
2887 return false;
2888 }
2889 }
2890
2891 // Establish format and size of each data element
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002892 const uint32_t vec_size = *alloc->element.type_vec_size.get();
Ewan Crawford8b244e22015-11-30 10:29:49 +00002893 const Element::DataType type = *alloc->element.type.get();
Ewan Crawforda0f08672015-10-16 08:28:47 +00002894
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002895 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT && "Invalid allocation type");
Ewan Crawforda0f08672015-10-16 08:28:47 +00002896
Ewan Crawford2e920712015-12-17 16:40:05 +00002897 lldb::Format format;
2898 if (type >= Element::RS_TYPE_ELEMENT)
2899 format = eFormatHex;
2900 else
2901 format = vec_size == 1 ? static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatSingle])
2902 : static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatVector]);
Ewan Crawforda0f08672015-10-16 08:28:47 +00002903
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002904 const uint32_t data_size = *alloc->element.datum_size.get();
Ewan Crawforda0f08672015-10-16 08:28:47 +00002905
2906 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002907 log->Printf("%s - element size %" PRIu32 " bytes, including padding", __FUNCTION__, data_size);
Ewan Crawforda0f08672015-10-16 08:28:47 +00002908
Ewan Crawford55232f02015-10-21 08:50:42 +00002909 // Allocate a buffer to copy data into
2910 std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2911 if (!buffer)
2912 {
Ewan Crawford2e920712015-12-17 16:40:05 +00002913 strm.Printf("Error: Couldn't read allocation data");
Ewan Crawford55232f02015-10-21 08:50:42 +00002914 strm.EOL();
2915 return false;
2916 }
2917
Ewan Crawforda0f08672015-10-16 08:28:47 +00002918 // Calculate stride between rows as there may be padding at end of rows since
2919 // allocated memory is 16-byte aligned
2920 if (!alloc->stride.isValid())
2921 {
2922 if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
2923 alloc->stride = 0;
2924 else if (!JITAllocationStride(alloc, frame_ptr))
2925 {
2926 strm.Printf("Error: Couldn't calculate allocation row stride");
2927 strm.EOL();
2928 return false;
2929 }
2930 }
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002931 const uint32_t stride = *alloc->stride.get();
2932 const uint32_t size = *alloc->size.get(); // Size of whole allocation
2933 const uint32_t padding = alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
Ewan Crawforda0f08672015-10-16 08:28:47 +00002934 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002935 log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32 " bytes, padding %" PRIu32,
2936 __FUNCTION__, stride, size, padding);
Ewan Crawforda0f08672015-10-16 08:28:47 +00002937
Ewan Crawforda0f08672015-10-16 08:28:47 +00002938 // Find dimensions used to index loops, so need to be non-zero
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002939 uint32_t dim_x = alloc->dimension.get()->dim_1;
Ewan Crawforda0f08672015-10-16 08:28:47 +00002940 dim_x = dim_x == 0 ? 1 : dim_x;
2941
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002942 uint32_t dim_y = alloc->dimension.get()->dim_2;
Ewan Crawforda0f08672015-10-16 08:28:47 +00002943 dim_y = dim_y == 0 ? 1 : dim_y;
2944
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002945 uint32_t dim_z = alloc->dimension.get()->dim_3;
Ewan Crawforda0f08672015-10-16 08:28:47 +00002946 dim_z = dim_z == 0 ? 1 : dim_z;
2947
Ewan Crawford55232f02015-10-21 08:50:42 +00002948 // Use data extractor to format output
2949 const uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
2950 DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(), archByteSize);
2951
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002952 uint32_t offset = 0; // Offset in buffer to next element to be printed
2953 uint32_t prev_row = 0; // Offset to the start of the previous row
Ewan Crawforda0f08672015-10-16 08:28:47 +00002954
2955 // Iterate over allocation dimensions, printing results to user
2956 strm.Printf("Data (X, Y, Z):");
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002957 for (uint32_t z = 0; z < dim_z; ++z)
Ewan Crawforda0f08672015-10-16 08:28:47 +00002958 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002959 for (uint32_t y = 0; y < dim_y; ++y)
Ewan Crawforda0f08672015-10-16 08:28:47 +00002960 {
2961 // Use stride to index start of next row.
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002962 if (!(y == 0 && z == 0))
Ewan Crawforda0f08672015-10-16 08:28:47 +00002963 offset = prev_row + stride;
2964 prev_row = offset;
2965
2966 // Print each element in the row individually
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002967 for (uint32_t x = 0; x < dim_x; ++x)
Ewan Crawforda0f08672015-10-16 08:28:47 +00002968 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002969 strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
Ewan Crawford8b244e22015-11-30 10:29:49 +00002970 if ((type == Element::RS_TYPE_NONE) && (alloc->element.children.size() > 0) &&
Adrian McCarthyfe06b5a2015-11-30 22:18:43 +00002971 (alloc->element.type_name != Element::GetFallbackStructName()))
Ewan Crawford8b244e22015-11-30 10:29:49 +00002972 {
2973 // Here we are dumping an Element of struct type.
2974 // This is done using expression evaluation with the name of the struct type and pointer to element.
2975
2976 // Don't print the name of the resulting expression, since this will be '$[0-9]+'
2977 DumpValueObjectOptions expr_options;
2978 expr_options.SetHideName(true);
2979
2980 // Setup expression as derefrencing a pointer cast to element address.
Ewan Crawfordea0636b2016-02-10 11:23:27 +00002981 char expr_char_buffer[jit_max_expr_size];
2982 int chars_written = snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002983 alloc->element.type_name.AsCString(), *alloc->data_ptr.get() + offset);
Ewan Crawford8b244e22015-11-30 10:29:49 +00002984
Ewan Crawfordea0636b2016-02-10 11:23:27 +00002985 if (chars_written < 0 || chars_written >= jit_max_expr_size)
Ewan Crawford8b244e22015-11-30 10:29:49 +00002986 {
2987 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00002988 log->Printf("%s - error in snprintf().", __FUNCTION__);
Ewan Crawford8b244e22015-11-30 10:29:49 +00002989 continue;
2990 }
2991
2992 // Evaluate expression
2993 ValueObjectSP expr_result;
2994 GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer, frame_ptr, expr_result);
2995
2996 // Print the results to our stream.
2997 expr_result->Dump(strm, expr_options);
2998 }
2999 else
3000 {
3001 alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0, 0);
3002 }
3003 offset += data_size;
Ewan Crawforda0f08672015-10-16 08:28:47 +00003004 }
3005 }
3006 }
3007 strm.EOL();
3008
Ewan Crawforda0f08672015-10-16 08:28:47 +00003009 return true;
3010}
3011
Ewan Crawford0d2bfcf2016-02-04 09:44:23 +00003012// Function recalculates all our cached information about allocations by jitting the
3013// RS runtime regarding each allocation we know about.
3014// Returns true if all allocations could be recomputed, false otherwise.
3015bool
3016RenderScriptRuntime::RecomputeAllAllocations(Stream &strm, StackFrame *frame_ptr)
3017{
3018 bool success = true;
3019 for (auto &alloc : m_allocations)
3020 {
3021 // JIT current allocation information
3022 if (!RefreshAllocation(alloc.get(), frame_ptr))
3023 {
3024 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32 "\n", alloc->id);
3025 success = false;
3026 }
3027 }
3028
3029 if (success)
3030 strm.Printf("All allocations successfully recomputed");
3031 strm.EOL();
3032
3033 return success;
3034}
3035
Ewan Crawfordb649b002016-01-26 10:41:08 +00003036// Prints information regarding currently loaded allocations.
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003037// These details are gathered by jitting the runtime, which has as latency.
Ewan Crawfordb649b002016-01-26 10:41:08 +00003038// Index parameter specifies a single allocation ID to print, or a zero value to print them all
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003039void
Ewan Crawfordb649b002016-01-26 10:41:08 +00003040RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr, const uint32_t index)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003041{
3042 strm.Printf("RenderScript Allocations:");
3043 strm.EOL();
3044 strm.IndentMore();
3045
3046 for (auto &alloc : m_allocations)
3047 {
Ewan Crawfordb649b002016-01-26 10:41:08 +00003048 // index will only be zero if we want to print all allocations
3049 if (index != 0 && index != alloc->id)
3050 continue;
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003051
3052 // JIT current allocation information
Ewan Crawfordb649b002016-01-26 10:41:08 +00003053 if (alloc->shouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr))
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003054 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003055 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32, alloc->id);
3056 strm.EOL();
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003057 continue;
3058 }
3059
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003060 strm.Printf("%" PRIu32 ":", alloc->id);
3061 strm.EOL();
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003062 strm.IndentMore();
3063
3064 strm.Indent("Context: ");
3065 if (!alloc->context.isValid())
3066 strm.Printf("unknown\n");
3067 else
3068 strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
3069
3070 strm.Indent("Address: ");
3071 if (!alloc->address.isValid())
3072 strm.Printf("unknown\n");
3073 else
3074 strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
3075
3076 strm.Indent("Data pointer: ");
3077 if (!alloc->data_ptr.isValid())
3078 strm.Printf("unknown\n");
3079 else
3080 strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
3081
3082 strm.Indent("Dimensions: ");
3083 if (!alloc->dimension.isValid())
3084 strm.Printf("unknown\n");
3085 else
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003086 strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3087 alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2, alloc->dimension.get()->dim_3);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003088
3089 strm.Indent("Data Type: ");
Ewan Crawford8b244e22015-11-30 10:29:49 +00003090 if (!alloc->element.type.isValid() || !alloc->element.type_vec_size.isValid())
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003091 strm.Printf("unknown\n");
3092 else
3093 {
Ewan Crawford8b244e22015-11-30 10:29:49 +00003094 const int vector_size = *alloc->element.type_vec_size.get();
Ewan Crawford2e920712015-12-17 16:40:05 +00003095 Element::DataType type = *alloc->element.type.get();
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003096
Ewan Crawford8b244e22015-11-30 10:29:49 +00003097 if (!alloc->element.type_name.IsEmpty())
3098 strm.Printf("%s\n", alloc->element.type_name.AsCString());
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003099 else
Ewan Crawford2e920712015-12-17 16:40:05 +00003100 {
3101 // Enum value isn't monotonous, so doesn't always index RsDataTypeToString array
3102 if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003103 type = static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3104 Element::RS_TYPE_MATRIX_2X2 + 1);
Ewan Crawford2e920712015-12-17 16:40:05 +00003105
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003106 if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3107 sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3108 vector_size > 4 || vector_size < 1)
Ewan Crawford2e920712015-12-17 16:40:05 +00003109 strm.Printf("invalid type\n");
3110 else
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003111 strm.Printf("%s\n", AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3112 [vector_size - 1]);
Ewan Crawford2e920712015-12-17 16:40:05 +00003113 }
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003114 }
3115
3116 strm.Indent("Data Kind: ");
Ewan Crawford8b244e22015-11-30 10:29:49 +00003117 if (!alloc->element.type_kind.isValid())
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003118 strm.Printf("unknown\n");
3119 else
3120 {
Ewan Crawford8b244e22015-11-30 10:29:49 +00003121 const Element::DataKind kind = *alloc->element.type_kind.get();
3122 if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003123 strm.Printf("invalid kind\n");
3124 else
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003125 strm.Printf("%s\n", AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00003126 }
3127
3128 strm.EOL();
3129 strm.IndentLess();
3130 }
3131 strm.IndentLess();
3132}
3133
Ewan Crawford7dc77712015-09-10 10:08:48 +00003134// Set breakpoints on every kernel found in RS module
3135void
3136RenderScriptRuntime::BreakOnModuleKernels(const RSModuleDescriptorSP rsmodule_sp)
3137{
3138 for (const auto &kernel : rsmodule_sp->m_kernels)
3139 {
3140 // Don't set breakpoint on 'root' kernel
3141 if (strcmp(kernel.m_name.AsCString(), "root") == 0)
3142 continue;
3143
3144 CreateKernelBreakpoint(kernel.m_name);
3145 }
3146}
3147
3148// Method is internally called by the 'kernel breakpoint all' command to
3149// enable or disable breaking on all kernels.
3150//
3151// When do_break is true we want to enable this functionality.
3152// When do_break is false we want to disable it.
3153void
3154RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target)
3155{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003156 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
Ewan Crawford7dc77712015-09-10 10:08:48 +00003157
3158 InitSearchFilter(target);
3159
3160 // Set breakpoints on all the kernels
3161 if (do_break && !m_breakAllKernels)
3162 {
3163 m_breakAllKernels = true;
3164
3165 for (const auto &module : m_rsmodules)
3166 BreakOnModuleKernels(module);
3167
3168 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003169 log->Printf("%s(True) - breakpoints set on all currently loaded kernels.", __FUNCTION__);
Ewan Crawford7dc77712015-09-10 10:08:48 +00003170 }
3171 else if (!do_break && m_breakAllKernels) // Breakpoints won't be set on any new kernels.
3172 {
3173 m_breakAllKernels = false;
3174
3175 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003176 log->Printf("%s(False) - breakpoints no longer automatically set.", __FUNCTION__);
Ewan Crawford7dc77712015-09-10 10:08:48 +00003177 }
3178}
3179
3180// Given the name of a kernel this function creates a breakpoint using our
3181// own breakpoint resolver, and returns the Breakpoint shared pointer.
3182BreakpointSP
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003183RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name)
Ewan Crawford7dc77712015-09-10 10:08:48 +00003184{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003185 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
Ewan Crawford7dc77712015-09-10 10:08:48 +00003186
3187 if (!m_filtersp)
3188 {
3189 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003190 log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
Ewan Crawford7dc77712015-09-10 10:08:48 +00003191 return nullptr;
3192 }
3193
3194 BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3195 BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(m_filtersp, resolver_sp, false, false, false);
3196
Ewan Crawford54782db2015-09-16 10:02:57 +00003197 // Give RS breakpoints a specific name, so the user can manipulate them as a group.
3198 Error err;
3199 if (!bp->AddName("RenderScriptKernel", err) && log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003200 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__, err.AsCString());
Ewan Crawford54782db2015-09-16 10:02:57 +00003201
Ewan Crawford7dc77712015-09-10 10:08:48 +00003202 return bp;
3203}
3204
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003205// Given an expression for a variable this function tries to calculate the variable's value.
3206// If this is possible it returns true and sets the uint64_t parameter to the variables unsigned value.
3207// Otherwise function returns false.
3208bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003209RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp, const char *var_name, uint64_t &val)
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003210{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003211 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003212 Error error;
3213 VariableSP var_sp;
3214
3215 // Find variable in stack frame
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003216 ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3217 var_name, eNoDynamicValues,
3218 StackFrame::eExpressionPathOptionCheckPtrVsMember | StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3219 var_sp, error));
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003220 if (!error.Success())
3221 {
3222 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003223 log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__, var_name);
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003224 return false;
3225 }
3226
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003227 // Find the uint32_t value for the variable
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003228 bool success = false;
3229 val = value_sp->GetValueAsUnsigned(0, &success);
3230 if (!success)
3231 {
3232 if (log)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003233 log->Printf("%s - error, couldn't parse '%s' as an uint32_t.", __FUNCTION__, var_name);
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003234 return false;
3235 }
3236
3237 return true;
3238}
3239
Ewan Crawford4f8817c2016-01-20 12:03:29 +00003240// Function attempts to find the current coordinate of a kernel invocation by investigating the
3241// values of frame variables in the .expand function. These coordinates are returned via the coord
3242// array reference parameter. Returns true if the coordinates could be found, and false otherwise.
3243bool
3244RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord, Thread *thread_ptr)
3245{
3246 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3247
3248 if (!thread_ptr)
3249 {
3250 if (log)
3251 log->Printf("%s - Error, No thread pointer", __FUNCTION__);
3252
3253 return false;
3254 }
3255
3256 // Walk the call stack looking for a function whose name has the suffix '.expand'
3257 // and contains the variables we're looking for.
3258 for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i)
3259 {
3260 if (!thread_ptr->SetSelectedFrameByIndex(i))
3261 continue;
3262
3263 StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
3264 if (!frame_sp)
3265 continue;
3266
3267 // Find the function name
3268 const SymbolContext sym_ctx = frame_sp->GetSymbolContext(false);
3269 const char *func_name_cstr = sym_ctx.GetFunctionName().AsCString();
3270 if (!func_name_cstr)
3271 continue;
3272
3273 if (log)
3274 log->Printf("%s - Inspecting function '%s'", __FUNCTION__, func_name_cstr);
3275
3276 // Check if function name has .expand suffix
3277 std::string func_name(func_name_cstr);
3278 const int length_difference = func_name.length() - RenderScriptRuntime::s_runtimeExpandSuffix.length();
3279 if (length_difference <= 0)
3280 continue;
3281
3282 const int32_t has_expand_suffix = func_name.compare(length_difference,
3283 RenderScriptRuntime::s_runtimeExpandSuffix.length(),
3284 RenderScriptRuntime::s_runtimeExpandSuffix);
3285
3286 if (has_expand_suffix != 0)
3287 continue;
3288
3289 if (log)
3290 log->Printf("%s - Found .expand function '%s'", __FUNCTION__, func_name_cstr);
3291
3292 // Get values for variables in .expand frame that tell us the current kernel invocation
3293 bool found_coord_variables = true;
3294 assert(RenderScriptRuntime::s_runtimeCoordVars.size() == coord.size());
3295
3296 for (uint32_t i = 0; i < coord.size(); ++i)
3297 {
3298 uint64_t value = 0;
3299 if (!GetFrameVarAsUnsigned(frame_sp, RenderScriptRuntime::s_runtimeCoordVars[i], value))
3300 {
3301 found_coord_variables = false;
3302 break;
3303 }
3304 coord[i] = value;
3305 }
3306
3307 if (found_coord_variables)
3308 return true;
3309 }
3310 return false;
3311}
3312
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003313// Callback when a kernel breakpoint hits and we're looking for a specific coordinate.
3314// Baton parameter contains a pointer to the target coordinate we want to break on.
3315// Function then checks the .expand frame for the current coordinate and breaks to user if it matches.
3316// Parameter 'break_id' is the id of the Breakpoint which made the callback.
3317// Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
3318// a single logical breakpoint can have multiple addresses.
3319bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003320RenderScriptRuntime::KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx, user_id_t break_id,
3321 user_id_t break_loc_id)
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003322{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003323 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003324
3325 assert(baton && "Error: null baton in conditional kernel breakpoint callback");
3326
3327 // Coordinate we want to stop on
Ewan Crawford4f8817c2016-01-20 12:03:29 +00003328 const uint32_t *target_coord = static_cast<const uint32_t *>(baton);
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003329
3330 if (log)
Ewan Crawford4f8817c2016-01-20 12:03:29 +00003331 log->Printf("%s - Break ID %" PRIu64 ", (%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")", __FUNCTION__, break_id,
3332 target_coord[0], target_coord[1], target_coord[2]);
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003333
Ewan Crawford4f8817c2016-01-20 12:03:29 +00003334 // Select current thread
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003335 ExecutionContext context(ctx->exe_ctx_ref);
Ewan Crawford4f8817c2016-01-20 12:03:29 +00003336 Thread *thread_ptr = context.GetThreadPtr();
3337 assert(thread_ptr && "Null thread pointer");
3338
3339 // Find current kernel invocation from .expand frame variables
3340 RSCoordinate current_coord{}; // Zero initialise array
3341 if (!GetKernelCoordinate(current_coord, thread_ptr))
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003342 {
3343 if (log)
Ewan Crawford4f8817c2016-01-20 12:03:29 +00003344 log->Printf("%s - Error, couldn't select .expand stack frame", __FUNCTION__);
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003345 return false;
3346 }
3347
Ewan Crawford4f8817c2016-01-20 12:03:29 +00003348 if (log)
3349 log->Printf("%s - (%" PRIu32 ",%" PRIu32 ",%" PRIu32 ")", __FUNCTION__, current_coord[0], current_coord[1],
3350 current_coord[2]);
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003351
3352 // Check if the current kernel invocation coordinate matches our target coordinate
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003353 if (current_coord[0] == target_coord[0] &&
3354 current_coord[1] == target_coord[1] &&
Ewan Crawford4f8817c2016-01-20 12:03:29 +00003355 current_coord[2] == target_coord[2])
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003356 {
3357 if (log)
Ewan Crawford4f8817c2016-01-20 12:03:29 +00003358 log->Printf("%s, BREAKING (%" PRIu32 ",%" PRIu32 ",%" PRIu32 ")", __FUNCTION__, current_coord[0],
3359 current_coord[1], current_coord[2]);
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003360
3361 BreakpointSP breakpoint_sp = context.GetTargetPtr()->GetBreakpointByID(break_id);
3362 assert(breakpoint_sp != nullptr && "Error: Couldn't find breakpoint matching break id for callback");
3363 breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint should only be hit once.
3364 return true;
3365 }
3366
3367 // No match on coordinate
3368 return false;
3369}
3370
3371// Tries to set a breakpoint on the start of a kernel, resolved using the kernel name.
3372// Argument 'coords', represents a three dimensional coordinate which can be used to specify
3373// a single kernel instance to break on. If this is set then we add a callback to the breakpoint.
Ewan Crawford98156582015-09-04 08:56:52 +00003374void
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003375RenderScriptRuntime::PlaceBreakpointOnKernel(Stream &strm, const char *name, const std::array<int, 3> coords,
3376 Error &error, TargetSP target)
Colin Riley4640cde2015-06-01 18:23:41 +00003377{
Ewan Crawford98156582015-09-04 08:56:52 +00003378 if (!name)
Colin Riley4640cde2015-06-01 18:23:41 +00003379 {
3380 error.SetErrorString("invalid kernel name");
3381 return;
3382 }
3383
Ewan Crawford7dc77712015-09-10 10:08:48 +00003384 InitSearchFilter(target);
Ewan Crawford98156582015-09-04 08:56:52 +00003385
Colin Riley4640cde2015-06-01 18:23:41 +00003386 ConstString kernel_name(name);
Ewan Crawford7dc77712015-09-10 10:08:48 +00003387 BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003388
3389 // We have a conditional breakpoint on a specific coordinate
3390 if (coords[0] != -1)
3391 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003392 strm.Printf("Conditional kernel breakpoint on coordinate %" PRId32 ", %" PRId32 ", %" PRId32,
3393 coords[0], coords[1], coords[2]);
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003394 strm.EOL();
3395
3396 // Allocate memory for the baton, and copy over coordinate
Ewan Crawford4f8817c2016-01-20 12:03:29 +00003397 uint32_t *baton = new uint32_t[coords.size()];
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003398 baton[0] = coords[0]; baton[1] = coords[1]; baton[2] = coords[2];
3399
3400 // Create a callback that will be invoked everytime the breakpoint is hit.
3401 // The baton object passed to the handler is the target coordinate we want to break on.
3402 bp->SetCallback(KernelBreakpointHit, baton, true);
3403
3404 // Store a shared pointer to the baton, so the memory will eventually be cleaned up after destruction
Ewan Crawford4f8817c2016-01-20 12:03:29 +00003405 m_conditional_breaks[bp->GetID()] = std::shared_ptr<uint32_t>(baton);
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003406 }
3407
Ewan Crawford98156582015-09-04 08:56:52 +00003408 if (bp)
3409 bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
Colin Riley4640cde2015-06-01 18:23:41 +00003410}
3411
3412void
Colin Riley5ec532a2015-04-09 16:49:25 +00003413RenderScriptRuntime::DumpModules(Stream &strm) const
3414{
3415 strm.Printf("RenderScript Modules:");
3416 strm.EOL();
3417 strm.IndentMore();
3418 for (const auto &module : m_rsmodules)
3419 {
Colin Riley4640cde2015-06-01 18:23:41 +00003420 module->Dump(strm);
Colin Riley5ec532a2015-04-09 16:49:25 +00003421 }
3422 strm.IndentLess();
3423}
3424
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003425RenderScriptRuntime::ScriptDetails *
Ewan Crawford78f339d2015-09-21 10:53:18 +00003426RenderScriptRuntime::LookUpScript(addr_t address, bool create)
3427{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003428 for (const auto &s : m_scripts)
Ewan Crawford78f339d2015-09-21 10:53:18 +00003429 {
3430 if (s->script.isValid())
3431 if (*s->script == address)
3432 return s.get();
3433 }
3434 if (create)
3435 {
3436 std::unique_ptr<ScriptDetails> s(new ScriptDetails);
3437 s->script = address;
3438 m_scripts.push_back(std::move(s));
Ewan Crawfordd10ca9d2015-09-22 13:36:35 +00003439 return m_scripts.back().get();
Ewan Crawford78f339d2015-09-21 10:53:18 +00003440 }
3441 return nullptr;
3442}
3443
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003444RenderScriptRuntime::AllocationDetails *
Ewan Crawford78f339d2015-09-21 10:53:18 +00003445RenderScriptRuntime::LookUpAllocation(addr_t address, bool create)
3446{
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003447 for (const auto &a : m_allocations)
Ewan Crawford78f339d2015-09-21 10:53:18 +00003448 {
3449 if (a->address.isValid())
3450 if (*a->address == address)
3451 return a.get();
3452 }
3453 if (create)
3454 {
3455 std::unique_ptr<AllocationDetails> a(new AllocationDetails);
3456 a->address = address;
3457 m_allocations.push_back(std::move(a));
Ewan Crawfordd10ca9d2015-09-22 13:36:35 +00003458 return m_allocations.back().get();
Ewan Crawford78f339d2015-09-21 10:53:18 +00003459 }
3460 return nullptr;
3461}
3462
Colin Riley5ec532a2015-04-09 16:49:25 +00003463void
3464RSModuleDescriptor::Dump(Stream &strm) const
3465{
3466 strm.Indent();
3467 m_module->GetFileSpec().Dump(&strm);
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003468 if (m_module->GetNumCompileUnits())
Colin Riley4640cde2015-06-01 18:23:41 +00003469 {
3470 strm.Indent("Debug info loaded.");
3471 }
3472 else
3473 {
3474 strm.Indent("Debug info does not exist.");
3475 }
Colin Riley5ec532a2015-04-09 16:49:25 +00003476 strm.EOL();
3477 strm.IndentMore();
3478 strm.Indent();
Colin Riley189598e2015-04-12 22:05:58 +00003479 strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
Colin Riley5ec532a2015-04-09 16:49:25 +00003480 strm.EOL();
3481 strm.IndentMore();
3482 for (const auto &global : m_globals)
3483 {
3484 global.Dump(strm);
3485 }
3486 strm.IndentLess();
3487 strm.Indent();
Colin Riley189598e2015-04-12 22:05:58 +00003488 strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
Colin Riley5ec532a2015-04-09 16:49:25 +00003489 strm.EOL();
3490 strm.IndentMore();
3491 for (const auto &kernel : m_kernels)
3492 {
3493 kernel.Dump(strm);
3494 }
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003495 strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
Colin Riley4640cde2015-06-01 18:23:41 +00003496 strm.EOL();
3497 strm.IndentMore();
3498 for (const auto &key_val : m_pragmas)
3499 {
3500 strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
3501 strm.EOL();
3502 }
Colin Riley5ec532a2015-04-09 16:49:25 +00003503 strm.IndentLess(4);
3504}
3505
3506void
3507RSGlobalDescriptor::Dump(Stream &strm) const
3508{
3509 strm.Indent(m_name.AsCString());
Colin Riley4640cde2015-06-01 18:23:41 +00003510 VariableList var_list;
3511 m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
3512 if (var_list.GetSize() == 1)
3513 {
3514 auto var = var_list.GetVariableAtIndex(0);
3515 auto type = var->GetType();
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003516 if (type)
Colin Riley4640cde2015-06-01 18:23:41 +00003517 {
3518 strm.Printf(" - ");
3519 type->DumpTypeName(&strm);
3520 }
3521 else
3522 {
3523 strm.Printf(" - Unknown Type");
3524 }
3525 }
3526 else
3527 {
3528 strm.Printf(" - variable identified, but not found in binary");
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003529 const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(m_name, eSymbolTypeData);
Colin Riley4640cde2015-06-01 18:23:41 +00003530 if (s)
3531 {
3532 strm.Printf(" (symbol exists) ");
3533 }
3534 }
3535
Colin Riley5ec532a2015-04-09 16:49:25 +00003536 strm.EOL();
3537}
3538
3539void
3540RSKernelDescriptor::Dump(Stream &strm) const
3541{
3542 strm.Indent(m_name.AsCString());
3543 strm.EOL();
3544}
3545
Colin Riley5ec532a2015-04-09 16:49:25 +00003546class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed
3547{
Eugene Zelenko222b9372015-10-27 00:45:06 +00003548public:
Colin Riley5ec532a2015-04-09 16:49:25 +00003549 CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
3550 : CommandObjectParsed(interpreter, "renderscript module dump",
3551 "Dumps renderscript specific information for all modules.", "renderscript module dump",
Enrico Granatae87764f2015-05-27 05:04:35 +00003552 eCommandRequiresProcess | eCommandProcessMustBeLaunched)
Colin Riley5ec532a2015-04-09 16:49:25 +00003553 {
3554 }
3555
Eugene Zelenko222b9372015-10-27 00:45:06 +00003556 ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
Colin Riley5ec532a2015-04-09 16:49:25 +00003557
3558 bool
Eugene Zelenko222b9372015-10-27 00:45:06 +00003559 DoExecute(Args &command, CommandReturnObject &result) override
Colin Riley5ec532a2015-04-09 16:49:25 +00003560 {
3561 RenderScriptRuntime *runtime =
3562 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
3563 runtime->DumpModules(result.GetOutputStream());
3564 result.SetStatus(eReturnStatusSuccessFinishResult);
3565 return true;
3566 }
3567};
3568
3569class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword
3570{
Eugene Zelenko222b9372015-10-27 00:45:06 +00003571public:
Colin Riley5ec532a2015-04-09 16:49:25 +00003572 CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
3573 : CommandObjectMultiword(interpreter, "renderscript module", "Commands that deal with renderscript modules.",
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003574 nullptr)
Colin Riley5ec532a2015-04-09 16:49:25 +00003575 {
Colin Riley5ec532a2015-04-09 16:49:25 +00003576 LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(interpreter)));
3577 }
3578
Eugene Zelenko222b9372015-10-27 00:45:06 +00003579 ~CommandObjectRenderScriptRuntimeModule() override = default;
Colin Riley5ec532a2015-04-09 16:49:25 +00003580};
3581
Colin Riley4640cde2015-06-01 18:23:41 +00003582class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed
3583{
Eugene Zelenko222b9372015-10-27 00:45:06 +00003584public:
Colin Riley4640cde2015-06-01 18:23:41 +00003585 CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
3586 : CommandObjectParsed(interpreter, "renderscript kernel list",
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003587 "Lists renderscript kernel names and associated script resources.",
3588 "renderscript kernel list", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
Colin Riley4640cde2015-06-01 18:23:41 +00003589 {
3590 }
3591
Eugene Zelenko222b9372015-10-27 00:45:06 +00003592 ~CommandObjectRenderScriptRuntimeKernelList() override = default;
Colin Riley4640cde2015-06-01 18:23:41 +00003593
3594 bool
Eugene Zelenko222b9372015-10-27 00:45:06 +00003595 DoExecute(Args &command, CommandReturnObject &result) override
Colin Riley4640cde2015-06-01 18:23:41 +00003596 {
3597 RenderScriptRuntime *runtime =
3598 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
3599 runtime->DumpKernels(result.GetOutputStream());
3600 result.SetStatus(eReturnStatusSuccessFinishResult);
3601 return true;
3602 }
3603};
3604
Ewan Crawford7dc77712015-09-10 10:08:48 +00003605class CommandObjectRenderScriptRuntimeKernelBreakpointSet : public CommandObjectParsed
Colin Riley4640cde2015-06-01 18:23:41 +00003606{
Eugene Zelenko222b9372015-10-27 00:45:06 +00003607public:
Ewan Crawford7dc77712015-09-10 10:08:48 +00003608 CommandObjectRenderScriptRuntimeKernelBreakpointSet(CommandInterpreter &interpreter)
3609 : CommandObjectParsed(interpreter, "renderscript kernel breakpoint set",
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003610 "Sets a breakpoint on a renderscript kernel.",
3611 "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
3612 eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
3613 m_options(interpreter)
Colin Riley4640cde2015-06-01 18:23:41 +00003614 {
3615 }
3616
Eugene Zelenko222b9372015-10-27 00:45:06 +00003617 ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
3618
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003619 Options *
Eugene Zelenko222b9372015-10-27 00:45:06 +00003620 GetOptions() override
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003621 {
3622 return &m_options;
3623 }
3624
3625 class CommandOptions : public Options
3626 {
Eugene Zelenko222b9372015-10-27 00:45:06 +00003627 public:
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003628 CommandOptions(CommandInterpreter &interpreter) : Options(interpreter) {}
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003629
Eugene Zelenko222b9372015-10-27 00:45:06 +00003630 ~CommandOptions() override = default;
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003631
Eugene Zelenko222b9372015-10-27 00:45:06 +00003632 Error
3633 SetOptionValue(uint32_t option_idx, const char *option_arg) override
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003634 {
3635 Error error;
3636 const int short_option = m_getopt_table[option_idx].val;
3637
3638 switch (short_option)
3639 {
3640 case 'c':
3641 if (!ParseCoordinate(option_arg))
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003642 error.SetErrorStringWithFormat("Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
3643 option_arg);
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003644 break;
3645 default:
3646 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3647 break;
3648 }
3649 return error;
3650 }
3651
3652 // -c takes an argument of the form 'num[,num][,num]'.
3653 // Where 'id_cstr' is this argument with the whitespace trimmed.
3654 // Missing coordinates are defaulted to zero.
3655 bool
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003656 ParseCoordinate(const char *id_cstr)
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003657 {
3658 RegularExpression regex;
3659 RegularExpression::Match regex_match(3);
3660
3661 bool matched = false;
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003662 if (regex.Compile("^([0-9]+),([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003663 matched = true;
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003664 else if (regex.Compile("^([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003665 matched = true;
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003666 else if (regex.Compile("^([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003667 matched = true;
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003668 for (uint32_t i = 0; i < 3; i++)
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003669 {
3670 std::string group;
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003671 if (regex_match.GetMatchAtIndex(id_cstr, i + 1, group))
3672 m_coord[i] = (uint32_t)strtoul(group.c_str(), nullptr, 0);
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003673 else
3674 m_coord[i] = 0;
3675 }
3676 return matched;
3677 }
3678
3679 void
Eugene Zelenko222b9372015-10-27 00:45:06 +00003680 OptionParsingStarting() override
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003681 {
3682 // -1 means the -c option hasn't been set
3683 m_coord[0] = -1;
3684 m_coord[1] = -1;
3685 m_coord[2] = -1;
3686 }
3687
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003688 const OptionDefinition *
Eugene Zelenko222b9372015-10-27 00:45:06 +00003689 GetDefinitions() override
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003690 {
3691 return g_option_table;
3692 }
3693
3694 static OptionDefinition g_option_table[];
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003695 std::array<int, 3> m_coord;
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003696 };
3697
Colin Riley4640cde2015-06-01 18:23:41 +00003698 bool
Eugene Zelenko222b9372015-10-27 00:45:06 +00003699 DoExecute(Args &command, CommandReturnObject &result) override
Colin Riley4640cde2015-06-01 18:23:41 +00003700 {
3701 const size_t argc = command.GetArgumentCount();
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003702 if (argc < 1)
Colin Riley4640cde2015-06-01 18:23:41 +00003703 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003704 result.AppendErrorWithFormat("'%s' takes 1 argument of kernel name, and an optional coordinate.",
3705 m_cmd_name.c_str());
Colin Riley4640cde2015-06-01 18:23:41 +00003706 result.SetStatus(eReturnStatusFailed);
Colin Riley4640cde2015-06-01 18:23:41 +00003707 return false;
3708 }
3709
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003710 RenderScriptRuntime *runtime =
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003711 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003712
3713 Error error;
3714 runtime->PlaceBreakpointOnKernel(result.GetOutputStream(), command.GetArgumentAtIndex(0), m_options.m_coord,
3715 error, m_exe_ctx.GetTargetSP());
3716
3717 if (error.Success())
3718 {
3719 result.AppendMessage("Breakpoint(s) created");
3720 result.SetStatus(eReturnStatusSuccessFinishResult);
3721 return true;
3722 }
Colin Riley4640cde2015-06-01 18:23:41 +00003723 result.SetStatus(eReturnStatusFailed);
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003724 result.AppendErrorWithFormat("Error: %s", error.AsCString());
Colin Riley4640cde2015-06-01 18:23:41 +00003725 return false;
Eugene Zelenko222b9372015-10-27 00:45:06 +00003726 }
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003727
Eugene Zelenko222b9372015-10-27 00:45:06 +00003728private:
3729 CommandOptions m_options;
Colin Riley4640cde2015-06-01 18:23:41 +00003730};
3731
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003732OptionDefinition CommandObjectRenderScriptRuntimeKernelBreakpointSet::CommandOptions::g_option_table[] = {
3733 {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeValue,
3734 "Set a breakpoint on a single invocation of the kernel with specified coordinate.\n"
3735 "Coordinate takes the form 'x[,y][,z] where x,y,z are positive integers representing kernel dimensions. "
3736 "Any unset dimensions will be defaulted to zero."},
3737 {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}};
Ewan Crawford018f5a7e2015-10-26 14:04:37 +00003738
Ewan Crawford7dc77712015-09-10 10:08:48 +00003739class CommandObjectRenderScriptRuntimeKernelBreakpointAll : public CommandObjectParsed
3740{
Eugene Zelenko222b9372015-10-27 00:45:06 +00003741public:
Ewan Crawford7dc77712015-09-10 10:08:48 +00003742 CommandObjectRenderScriptRuntimeKernelBreakpointAll(CommandInterpreter &interpreter)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003743 : CommandObjectParsed(
3744 interpreter, "renderscript kernel breakpoint all",
3745 "Automatically sets a breakpoint on all renderscript kernels that are or will be loaded.\n"
3746 "Disabling option means breakpoints will no longer be set on any kernels loaded in the future, "
3747 "but does not remove currently set breakpoints.",
3748 "renderscript kernel breakpoint all <enable/disable>",
3749 eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
Ewan Crawford7dc77712015-09-10 10:08:48 +00003750 {
3751 }
3752
Eugene Zelenko222b9372015-10-27 00:45:06 +00003753 ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
Ewan Crawford7dc77712015-09-10 10:08:48 +00003754
3755 bool
Eugene Zelenko222b9372015-10-27 00:45:06 +00003756 DoExecute(Args &command, CommandReturnObject &result) override
Ewan Crawford7dc77712015-09-10 10:08:48 +00003757 {
3758 const size_t argc = command.GetArgumentCount();
3759 if (argc != 1)
3760 {
3761 result.AppendErrorWithFormat("'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
3762 result.SetStatus(eReturnStatusFailed);
3763 return false;
3764 }
3765
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003766 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
3767 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
Ewan Crawford7dc77712015-09-10 10:08:48 +00003768
3769 bool do_break = false;
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003770 const char *argument = command.GetArgumentAtIndex(0);
Ewan Crawford7dc77712015-09-10 10:08:48 +00003771 if (strcmp(argument, "enable") == 0)
3772 {
3773 do_break = true;
3774 result.AppendMessage("Breakpoints will be set on all kernels.");
3775 }
3776 else if (strcmp(argument, "disable") == 0)
3777 {
3778 do_break = false;
3779 result.AppendMessage("Breakpoints will not be set on any new kernels.");
3780 }
3781 else
3782 {
3783 result.AppendErrorWithFormat("Argument must be either 'enable' or 'disable'");
3784 result.SetStatus(eReturnStatusFailed);
3785 return false;
3786 }
3787
3788 runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
3789
3790 result.SetStatus(eReturnStatusSuccessFinishResult);
3791 return true;
3792 }
3793};
3794
Ewan Crawford4f8817c2016-01-20 12:03:29 +00003795class CommandObjectRenderScriptRuntimeKernelCoordinate : public CommandObjectParsed
3796{
3797public:
3798 CommandObjectRenderScriptRuntimeKernelCoordinate(CommandInterpreter &interpreter)
3799 : CommandObjectParsed(interpreter, "renderscript kernel coordinate",
3800 "Shows the (x,y,z) coordinate of the current kernel invocation.",
3801 "renderscript kernel coordinate",
3802 eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
3803 {
3804 }
3805
3806 ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
3807
3808 bool
3809 DoExecute(Args &command, CommandReturnObject &result) override
3810 {
3811 RSCoordinate coord{}; // Zero initialize array
3812 bool success = RenderScriptRuntime::GetKernelCoordinate(coord, m_exe_ctx.GetThreadPtr());
3813 Stream &stream = result.GetOutputStream();
3814
3815 if (success)
3816 {
3817 stream.Printf("Coordinate: (%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")", coord[0], coord[1], coord[2]);
3818 stream.EOL();
3819 result.SetStatus(eReturnStatusSuccessFinishResult);
3820 }
3821 else
3822 {
3823 stream.Printf("Error: Coordinate could not be found.");
3824 stream.EOL();
3825 result.SetStatus(eReturnStatusFailed);
3826 }
3827 return true;
3828 }
3829};
3830
Ewan Crawford7dc77712015-09-10 10:08:48 +00003831class CommandObjectRenderScriptRuntimeKernelBreakpoint : public CommandObjectMultiword
3832{
Eugene Zelenko222b9372015-10-27 00:45:06 +00003833public:
Ewan Crawford7dc77712015-09-10 10:08:48 +00003834 CommandObjectRenderScriptRuntimeKernelBreakpoint(CommandInterpreter &interpreter)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003835 : CommandObjectMultiword(interpreter, "renderscript kernel",
3836 "Commands that generate breakpoints on renderscript kernels.", nullptr)
Ewan Crawford7dc77712015-09-10 10:08:48 +00003837 {
3838 LoadSubCommand("set", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(interpreter)));
3839 LoadSubCommand("all", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(interpreter)));
3840 }
3841
Eugene Zelenko222b9372015-10-27 00:45:06 +00003842 ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
Ewan Crawford7dc77712015-09-10 10:08:48 +00003843};
3844
Colin Riley4640cde2015-06-01 18:23:41 +00003845class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword
3846{
Eugene Zelenko222b9372015-10-27 00:45:06 +00003847public:
Colin Riley4640cde2015-06-01 18:23:41 +00003848 CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
3849 : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that deal with renderscript kernels.",
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003850 nullptr)
Colin Riley4640cde2015-06-01 18:23:41 +00003851 {
3852 LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(interpreter)));
Ewan Crawford36175cc2016-01-29 10:11:03 +00003853 LoadSubCommand("coordinate",
3854 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003855 LoadSubCommand("breakpoint",
3856 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
Colin Riley4640cde2015-06-01 18:23:41 +00003857 }
3858
Eugene Zelenko222b9372015-10-27 00:45:06 +00003859 ~CommandObjectRenderScriptRuntimeKernel() override = default;
Colin Riley4640cde2015-06-01 18:23:41 +00003860};
3861
3862class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed
3863{
Eugene Zelenko222b9372015-10-27 00:45:06 +00003864public:
Colin Riley4640cde2015-06-01 18:23:41 +00003865 CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003866 : CommandObjectParsed(interpreter, "renderscript context dump", "Dumps renderscript context information.",
3867 "renderscript context dump", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
Colin Riley4640cde2015-06-01 18:23:41 +00003868 {
3869 }
3870
Eugene Zelenko222b9372015-10-27 00:45:06 +00003871 ~CommandObjectRenderScriptRuntimeContextDump() override = default;
Colin Riley4640cde2015-06-01 18:23:41 +00003872
3873 bool
Eugene Zelenko222b9372015-10-27 00:45:06 +00003874 DoExecute(Args &command, CommandReturnObject &result) override
Colin Riley4640cde2015-06-01 18:23:41 +00003875 {
3876 RenderScriptRuntime *runtime =
3877 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
3878 runtime->DumpContexts(result.GetOutputStream());
3879 result.SetStatus(eReturnStatusSuccessFinishResult);
3880 return true;
3881 }
3882};
3883
3884class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword
3885{
Eugene Zelenko222b9372015-10-27 00:45:06 +00003886public:
Colin Riley4640cde2015-06-01 18:23:41 +00003887 CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
3888 : CommandObjectMultiword(interpreter, "renderscript context", "Commands that deal with renderscript contexts.",
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003889 nullptr)
Colin Riley4640cde2015-06-01 18:23:41 +00003890 {
3891 LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(interpreter)));
3892 }
3893
Eugene Zelenko222b9372015-10-27 00:45:06 +00003894 ~CommandObjectRenderScriptRuntimeContext() override = default;
Colin Riley4640cde2015-06-01 18:23:41 +00003895};
3896
Ewan Crawforda0f08672015-10-16 08:28:47 +00003897class CommandObjectRenderScriptRuntimeAllocationDump : public CommandObjectParsed
3898{
Eugene Zelenko222b9372015-10-27 00:45:06 +00003899public:
Ewan Crawforda0f08672015-10-16 08:28:47 +00003900 CommandObjectRenderScriptRuntimeAllocationDump(CommandInterpreter &interpreter)
3901 : CommandObjectParsed(interpreter, "renderscript allocation dump",
3902 "Displays the contents of a particular allocation", "renderscript allocation dump <ID>",
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003903 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
3904 m_options(interpreter)
Ewan Crawforda0f08672015-10-16 08:28:47 +00003905 {
3906 }
3907
Eugene Zelenko222b9372015-10-27 00:45:06 +00003908 ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
3909
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003910 Options *
Eugene Zelenko222b9372015-10-27 00:45:06 +00003911 GetOptions() override
Ewan Crawforda0f08672015-10-16 08:28:47 +00003912 {
3913 return &m_options;
3914 }
3915
3916 class CommandOptions : public Options
3917 {
Eugene Zelenko222b9372015-10-27 00:45:06 +00003918 public:
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003919 CommandOptions(CommandInterpreter &interpreter) : Options(interpreter) {}
Ewan Crawforda0f08672015-10-16 08:28:47 +00003920
Eugene Zelenko222b9372015-10-27 00:45:06 +00003921 ~CommandOptions() override = default;
Ewan Crawforda0f08672015-10-16 08:28:47 +00003922
Eugene Zelenko222b9372015-10-27 00:45:06 +00003923 Error
3924 SetOptionValue(uint32_t option_idx, const char *option_arg) override
Ewan Crawforda0f08672015-10-16 08:28:47 +00003925 {
3926 Error error;
3927 const int short_option = m_getopt_table[option_idx].val;
3928
3929 switch (short_option)
3930 {
3931 case 'f':
3932 m_outfile.SetFile(option_arg, true);
3933 if (m_outfile.Exists())
3934 {
3935 m_outfile.Clear();
3936 error.SetErrorStringWithFormat("file already exists: '%s'", option_arg);
3937 }
3938 break;
3939 default:
3940 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3941 break;
3942 }
3943 return error;
3944 }
3945
3946 void
Eugene Zelenko222b9372015-10-27 00:45:06 +00003947 OptionParsingStarting() override
Ewan Crawforda0f08672015-10-16 08:28:47 +00003948 {
3949 m_outfile.Clear();
3950 }
3951
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003952 const OptionDefinition *
Eugene Zelenko222b9372015-10-27 00:45:06 +00003953 GetDefinitions() override
Ewan Crawforda0f08672015-10-16 08:28:47 +00003954 {
3955 return g_option_table;
3956 }
3957
3958 static OptionDefinition g_option_table[];
3959 FileSpec m_outfile;
3960 };
3961
Ewan Crawforda0f08672015-10-16 08:28:47 +00003962 bool
Eugene Zelenko222b9372015-10-27 00:45:06 +00003963 DoExecute(Args &command, CommandReturnObject &result) override
Ewan Crawforda0f08672015-10-16 08:28:47 +00003964 {
3965 const size_t argc = command.GetArgumentCount();
3966 if (argc < 1)
3967 {
3968 result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. As well as an optional -f argument",
3969 m_cmd_name.c_str());
3970 result.SetStatus(eReturnStatusFailed);
3971 return false;
3972 }
3973
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003974 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
3975 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
Ewan Crawforda0f08672015-10-16 08:28:47 +00003976
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003977 const char *id_cstr = command.GetArgumentAtIndex(0);
Ewan Crawforda0f08672015-10-16 08:28:47 +00003978 bool convert_complete = false;
3979 const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
3980 if (!convert_complete)
3981 {
3982 result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
3983 result.SetStatus(eReturnStatusFailed);
3984 return false;
3985 }
3986
Aidan Doddsb3f7f692016-01-28 16:39:44 +00003987 Stream *output_strm = nullptr;
Ewan Crawforda0f08672015-10-16 08:28:47 +00003988 StreamFile outfile_stream;
3989 const FileSpec &outfile_spec = m_options.m_outfile; // Dump allocation to file instead
3990 if (outfile_spec)
3991 {
3992 // Open output file
3993 char path[256];
3994 outfile_spec.GetPath(path, sizeof(path));
3995 if (outfile_stream.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate).Success())
3996 {
3997 output_strm = &outfile_stream;
3998 result.GetOutputStream().Printf("Results written to '%s'", path);
3999 result.GetOutputStream().EOL();
4000 }
4001 else
4002 {
4003 result.AppendErrorWithFormat("Couldn't open file '%s'", path);
4004 result.SetStatus(eReturnStatusFailed);
4005 return false;
4006 }
4007 }
4008 else
4009 output_strm = &result.GetOutputStream();
4010
4011 assert(output_strm != nullptr);
4012 bool success = runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4013
4014 if (success)
4015 result.SetStatus(eReturnStatusSuccessFinishResult);
4016 else
4017 result.SetStatus(eReturnStatusFailed);
4018
4019 return true;
4020 }
4021
Eugene Zelenko222b9372015-10-27 00:45:06 +00004022private:
4023 CommandOptions m_options;
Ewan Crawforda0f08672015-10-16 08:28:47 +00004024};
4025
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004026OptionDefinition CommandObjectRenderScriptRuntimeAllocationDump::CommandOptions::g_option_table[] = {
4027 {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename,
4028 "Print results to specified file instead of command line."},
4029 {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}};
Ewan Crawforda0f08672015-10-16 08:28:47 +00004030
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004031class CommandObjectRenderScriptRuntimeAllocationList : public CommandObjectParsed
4032{
Eugene Zelenko222b9372015-10-27 00:45:06 +00004033public:
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004034 CommandObjectRenderScriptRuntimeAllocationList(CommandInterpreter &interpreter)
4035 : CommandObjectParsed(interpreter, "renderscript allocation list",
4036 "List renderscript allocations and their information.", "renderscript allocation list",
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004037 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4038 m_options(interpreter)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004039 {
4040 }
4041
Eugene Zelenko222b9372015-10-27 00:45:06 +00004042 ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4043
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004044 Options *
Eugene Zelenko222b9372015-10-27 00:45:06 +00004045 GetOptions() override
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004046 {
4047 return &m_options;
4048 }
4049
4050 class CommandOptions : public Options
4051 {
Eugene Zelenko222b9372015-10-27 00:45:06 +00004052 public:
Ewan Crawfordb649b002016-01-26 10:41:08 +00004053 CommandOptions(CommandInterpreter &interpreter) : Options(interpreter), m_id(0) {}
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004054
Eugene Zelenko222b9372015-10-27 00:45:06 +00004055 ~CommandOptions() override = default;
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004056
Eugene Zelenko222b9372015-10-27 00:45:06 +00004057 Error
4058 SetOptionValue(uint32_t option_idx, const char *option_arg) override
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004059 {
4060 Error error;
4061 const int short_option = m_getopt_table[option_idx].val;
4062
4063 switch (short_option)
4064 {
Ewan Crawfordb649b002016-01-26 10:41:08 +00004065 case 'i':
4066 bool success;
4067 m_id = StringConvert::ToUInt32(option_arg, 0, 0, &success);
4068 if (!success)
4069 error.SetErrorStringWithFormat("invalid integer value for option '%c'", short_option);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004070 break;
4071 default:
4072 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4073 break;
4074 }
4075 return error;
4076 }
4077
4078 void
Eugene Zelenko222b9372015-10-27 00:45:06 +00004079 OptionParsingStarting() override
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004080 {
Ewan Crawfordb649b002016-01-26 10:41:08 +00004081 m_id = 0;
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004082 }
4083
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004084 const OptionDefinition *
Eugene Zelenko222b9372015-10-27 00:45:06 +00004085 GetDefinitions() override
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004086 {
4087 return g_option_table;
4088 }
4089
4090 static OptionDefinition g_option_table[];
Ewan Crawfordb649b002016-01-26 10:41:08 +00004091 uint32_t m_id;
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004092 };
4093
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004094 bool
Eugene Zelenko222b9372015-10-27 00:45:06 +00004095 DoExecute(Args &command, CommandReturnObject &result) override
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004096 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004097 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4098 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
Ewan Crawfordb649b002016-01-26 10:41:08 +00004099 runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(), m_options.m_id);
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004100 result.SetStatus(eReturnStatusSuccessFinishResult);
4101 return true;
4102 }
4103
Eugene Zelenko222b9372015-10-27 00:45:06 +00004104private:
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004105 CommandOptions m_options;
4106};
4107
Ewan Crawfordb649b002016-01-26 10:41:08 +00004108OptionDefinition CommandObjectRenderScriptRuntimeAllocationList::CommandOptions::g_option_table[] = {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004109 {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeIndex,
Ewan Crawfordb649b002016-01-26 10:41:08 +00004110 "Only show details of a single allocation with specified id."},
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004111 {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}};
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004112
Ewan Crawford55232f02015-10-21 08:50:42 +00004113class CommandObjectRenderScriptRuntimeAllocationLoad : public CommandObjectParsed
4114{
Eugene Zelenko222b9372015-10-27 00:45:06 +00004115public:
Ewan Crawford55232f02015-10-21 08:50:42 +00004116 CommandObjectRenderScriptRuntimeAllocationLoad(CommandInterpreter &interpreter)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004117 : CommandObjectParsed(
4118 interpreter, "renderscript allocation load", "Loads renderscript allocation contents from a file.",
4119 "renderscript allocation load <ID> <filename>", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
Ewan Crawford55232f02015-10-21 08:50:42 +00004120 {
4121 }
4122
Eugene Zelenko222b9372015-10-27 00:45:06 +00004123 ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
Ewan Crawford55232f02015-10-21 08:50:42 +00004124
4125 bool
Eugene Zelenko222b9372015-10-27 00:45:06 +00004126 DoExecute(Args &command, CommandReturnObject &result) override
Ewan Crawford55232f02015-10-21 08:50:42 +00004127 {
4128 const size_t argc = command.GetArgumentCount();
4129 if (argc != 2)
4130 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004131 result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.",
4132 m_cmd_name.c_str());
Ewan Crawford55232f02015-10-21 08:50:42 +00004133 result.SetStatus(eReturnStatusFailed);
4134 return false;
4135 }
4136
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004137 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4138 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
Ewan Crawford55232f02015-10-21 08:50:42 +00004139
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004140 const char *id_cstr = command.GetArgumentAtIndex(0);
Ewan Crawford55232f02015-10-21 08:50:42 +00004141 bool convert_complete = false;
4142 const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
4143 if (!convert_complete)
4144 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004145 result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
4146 result.SetStatus(eReturnStatusFailed);
Ewan Crawford55232f02015-10-21 08:50:42 +00004147 return false;
4148 }
4149
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004150 const char *filename = command.GetArgumentAtIndex(1);
Ewan Crawford55232f02015-10-21 08:50:42 +00004151 bool success = runtime->LoadAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
4152
4153 if (success)
4154 result.SetStatus(eReturnStatusSuccessFinishResult);
4155 else
4156 result.SetStatus(eReturnStatusFailed);
4157
4158 return true;
4159 }
4160};
4161
Ewan Crawford55232f02015-10-21 08:50:42 +00004162class CommandObjectRenderScriptRuntimeAllocationSave : public CommandObjectParsed
4163{
Eugene Zelenko222b9372015-10-27 00:45:06 +00004164public:
Ewan Crawford55232f02015-10-21 08:50:42 +00004165 CommandObjectRenderScriptRuntimeAllocationSave(CommandInterpreter &interpreter)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004166 : CommandObjectParsed(
4167 interpreter, "renderscript allocation save", "Write renderscript allocation contents to a file.",
4168 "renderscript allocation save <ID> <filename>", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
Ewan Crawford55232f02015-10-21 08:50:42 +00004169 {
4170 }
4171
Eugene Zelenko222b9372015-10-27 00:45:06 +00004172 ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
Ewan Crawford55232f02015-10-21 08:50:42 +00004173
4174 bool
Eugene Zelenko222b9372015-10-27 00:45:06 +00004175 DoExecute(Args &command, CommandReturnObject &result) override
Ewan Crawford55232f02015-10-21 08:50:42 +00004176 {
4177 const size_t argc = command.GetArgumentCount();
4178 if (argc != 2)
4179 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004180 result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.",
4181 m_cmd_name.c_str());
Ewan Crawford55232f02015-10-21 08:50:42 +00004182 result.SetStatus(eReturnStatusFailed);
4183 return false;
4184 }
4185
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004186 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4187 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
Ewan Crawford55232f02015-10-21 08:50:42 +00004188
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004189 const char *id_cstr = command.GetArgumentAtIndex(0);
Ewan Crawford55232f02015-10-21 08:50:42 +00004190 bool convert_complete = false;
4191 const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
4192 if (!convert_complete)
4193 {
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004194 result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
4195 result.SetStatus(eReturnStatusFailed);
Ewan Crawford55232f02015-10-21 08:50:42 +00004196 return false;
4197 }
4198
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004199 const char *filename = command.GetArgumentAtIndex(1);
Ewan Crawford55232f02015-10-21 08:50:42 +00004200 bool success = runtime->SaveAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
4201
4202 if (success)
4203 result.SetStatus(eReturnStatusSuccessFinishResult);
4204 else
4205 result.SetStatus(eReturnStatusFailed);
4206
4207 return true;
4208 }
4209};
4210
Ewan Crawford0d2bfcf2016-02-04 09:44:23 +00004211class CommandObjectRenderScriptRuntimeAllocationRefresh : public CommandObjectParsed
4212{
4213public:
4214 CommandObjectRenderScriptRuntimeAllocationRefresh(CommandInterpreter &interpreter)
4215 : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4216 "Recomputes the details of all allocations.", "renderscript allocation refresh",
4217 eCommandRequiresProcess | eCommandProcessMustBeLaunched)
4218 {
4219 }
4220
4221 ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
4222
4223 bool
4224 DoExecute(Args &command, CommandReturnObject &result) override
4225 {
4226 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4227 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
4228
4229 bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr());
4230
4231 if (success)
4232 {
4233 result.SetStatus(eReturnStatusSuccessFinishResult);
4234 return true;
4235 }
4236 else
4237 {
4238 result.SetStatus(eReturnStatusFailed);
4239 return false;
4240 }
4241 }
4242};
4243
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004244class CommandObjectRenderScriptRuntimeAllocation : public CommandObjectMultiword
4245{
Eugene Zelenko222b9372015-10-27 00:45:06 +00004246public:
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004247 CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004248 : CommandObjectMultiword(interpreter, "renderscript allocation",
4249 "Commands that deal with renderscript allocations.", nullptr)
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004250 {
4251 LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
Ewan Crawforda0f08672015-10-16 08:28:47 +00004252 LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
Ewan Crawford55232f02015-10-21 08:50:42 +00004253 LoadSubCommand("save", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4254 LoadSubCommand("load", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
Ewan Crawford0d2bfcf2016-02-04 09:44:23 +00004255 LoadSubCommand("refresh", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(interpreter)));
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004256 }
4257
Eugene Zelenko222b9372015-10-27 00:45:06 +00004258 ~CommandObjectRenderScriptRuntimeAllocation() override = default;
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004259};
4260
Colin Riley4640cde2015-06-01 18:23:41 +00004261class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed
4262{
Eugene Zelenko222b9372015-10-27 00:45:06 +00004263public:
Colin Riley4640cde2015-06-01 18:23:41 +00004264 CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004265 : CommandObjectParsed(interpreter, "renderscript status", "Displays current renderscript runtime status.",
4266 "renderscript status", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
Colin Riley4640cde2015-06-01 18:23:41 +00004267 {
4268 }
4269
Eugene Zelenko222b9372015-10-27 00:45:06 +00004270 ~CommandObjectRenderScriptRuntimeStatus() override = default;
Colin Riley4640cde2015-06-01 18:23:41 +00004271
4272 bool
Eugene Zelenko222b9372015-10-27 00:45:06 +00004273 DoExecute(Args &command, CommandReturnObject &result) override
Colin Riley4640cde2015-06-01 18:23:41 +00004274 {
4275 RenderScriptRuntime *runtime =
4276 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
4277 runtime->Status(result.GetOutputStream());
4278 result.SetStatus(eReturnStatusSuccessFinishResult);
4279 return true;
4280 }
4281};
4282
Colin Riley5ec532a2015-04-09 16:49:25 +00004283class CommandObjectRenderScriptRuntime : public CommandObjectMultiword
4284{
Eugene Zelenko222b9372015-10-27 00:45:06 +00004285public:
Colin Riley5ec532a2015-04-09 16:49:25 +00004286 CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
4287 : CommandObjectMultiword(interpreter, "renderscript", "A set of commands for operating on renderscript.",
4288 "renderscript <subcommand> [<subcommand-options>]")
4289 {
4290 LoadSubCommand("module", CommandObjectSP(new CommandObjectRenderScriptRuntimeModule(interpreter)));
Colin Riley4640cde2015-06-01 18:23:41 +00004291 LoadSubCommand("status", CommandObjectSP(new CommandObjectRenderScriptRuntimeStatus(interpreter)));
4292 LoadSubCommand("kernel", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernel(interpreter)));
4293 LoadSubCommand("context", CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(interpreter)));
Ewan Crawford15f2bd92015-10-06 08:42:32 +00004294 LoadSubCommand("allocation", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
Colin Riley5ec532a2015-04-09 16:49:25 +00004295 }
4296
Eugene Zelenko222b9372015-10-27 00:45:06 +00004297 ~CommandObjectRenderScriptRuntime() override = default;
Colin Riley5ec532a2015-04-09 16:49:25 +00004298};
Colin Rileyef20b082015-04-14 07:39:24 +00004299
4300void
4301RenderScriptRuntime::Initiate()
Colin Riley5ec532a2015-04-09 16:49:25 +00004302{
Colin Rileyef20b082015-04-14 07:39:24 +00004303 assert(!m_initiated);
Colin Riley5ec532a2015-04-09 16:49:25 +00004304}
Colin Rileyef20b082015-04-14 07:39:24 +00004305
4306RenderScriptRuntime::RenderScriptRuntime(Process *process)
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004307 : lldb_private::CPPLanguageRuntime(process),
4308 m_initiated(false),
4309 m_debuggerPresentFlagged(false),
Ewan Crawford7dc77712015-09-10 10:08:48 +00004310 m_breakAllKernels(false)
Colin Rileyef20b082015-04-14 07:39:24 +00004311{
Colin Riley4640cde2015-06-01 18:23:41 +00004312 ModulesDidLoad(process->GetTarget().GetImages());
Colin Rileyef20b082015-04-14 07:39:24 +00004313}
Colin Riley4640cde2015-06-01 18:23:41 +00004314
4315lldb::CommandObjectSP
Aidan Doddsb3f7f692016-01-28 16:39:44 +00004316RenderScriptRuntime::GetCommandObject(lldb_private::CommandInterpreter &interpreter)
Colin Riley4640cde2015-06-01 18:23:41 +00004317{
Enrico Granata0a66e2f2016-02-06 00:43:07 +00004318 return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
Colin Riley4640cde2015-06-01 18:23:41 +00004319}
4320
Ewan Crawford78f339d2015-09-21 10:53:18 +00004321RenderScriptRuntime::~RenderScriptRuntime() = default;