]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.cpp
Merge llvm-project main llvmorg-15-init-17485-ga3e38b4a206b
[FreeBSD/FreeBSD.git] / contrib / llvm-project / lldb / source / Plugins / LanguageRuntime / RenderScript / RenderScriptRuntime / RenderScriptRuntime.cpp
1 //===-- RenderScriptRuntime.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "RenderScriptRuntime.h"
10 #include "RenderScriptScriptGroup.h"
11
12 #include "lldb/Breakpoint/StoppointCallbackContext.h"
13 #include "lldb/Core/Debugger.h"
14 #include "lldb/Core/DumpDataExtractor.h"
15 #include "lldb/Core/PluginManager.h"
16 #include "lldb/Core/ValueObjectVariable.h"
17 #include "lldb/DataFormatters/DumpValueObjectOptions.h"
18 #include "lldb/Expression/UserExpression.h"
19 #include "lldb/Host/OptionParser.h"
20 #include "lldb/Interpreter/CommandInterpreter.h"
21 #include "lldb/Interpreter/CommandObjectMultiword.h"
22 #include "lldb/Interpreter/CommandReturnObject.h"
23 #include "lldb/Interpreter/Options.h"
24 #include "lldb/Symbol/Function.h"
25 #include "lldb/Symbol/Symbol.h"
26 #include "lldb/Symbol/Type.h"
27 #include "lldb/Symbol/VariableList.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Target/RegisterContext.h"
30 #include "lldb/Target/SectionLoadList.h"
31 #include "lldb/Target/Target.h"
32 #include "lldb/Target/Thread.h"
33 #include "lldb/Utility/Args.h"
34 #include "lldb/Utility/ConstString.h"
35 #include "lldb/Utility/LLDBLog.h"
36 #include "lldb/Utility/Log.h"
37 #include "lldb/Utility/RegisterValue.h"
38 #include "lldb/Utility/RegularExpression.h"
39 #include "lldb/Utility/Status.h"
40
41 #include "llvm/ADT/StringSwitch.h"
42
43 #include <memory>
44
45 using namespace lldb;
46 using namespace lldb_private;
47 using namespace lldb_renderscript;
48
49 LLDB_PLUGIN_DEFINE(RenderScriptRuntime)
50
51 #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")"
52
53 char RenderScriptRuntime::ID = 0;
54
55 namespace {
56
57 // The empirical_type adds a basic level of validation to arbitrary data
58 // allowing us to track if data has been discovered and stored or not. An
59 // empirical_type will be marked as valid only if it has been explicitly
60 // assigned to.
61 template <typename type_t> class empirical_type {
62 public:
63   // Ctor. Contents is invalid when constructed.
64   empirical_type() = default;
65
66   // Return true and copy contents to out if valid, else return false.
67   bool get(type_t &out) const {
68     if (valid)
69       out = data;
70     return valid;
71   }
72
73   // Return a pointer to the contents or nullptr if it was not valid.
74   const type_t *get() const { return valid ? &data : nullptr; }
75
76   // Assign data explicitly.
77   void set(const type_t in) {
78     data = in;
79     valid = true;
80   }
81
82   // Mark contents as invalid.
83   void invalidate() { valid = false; }
84
85   // Returns true if this type contains valid data.
86   bool isValid() const { return valid; }
87
88   // Assignment operator.
89   empirical_type<type_t> &operator=(const type_t in) {
90     set(in);
91     return *this;
92   }
93
94   // Dereference operator returns contents.
95   // Warning: Will assert if not valid so use only when you know data is valid.
96   const type_t &operator*() const {
97     assert(valid);
98     return data;
99   }
100
101 protected:
102   bool valid = false;
103   type_t data;
104 };
105
106 // ArgItem is used by the GetArgs() function when reading function arguments
107 // from the target.
108 struct ArgItem {
109   enum { ePointer, eInt32, eInt64, eLong, eBool } type;
110
111   uint64_t value;
112
113   explicit operator uint64_t() const { return value; }
114 };
115
116 // Context structure to be passed into GetArgsXXX(), argument reading functions
117 // below.
118 struct GetArgsCtx {
119   RegisterContext *reg_ctx;
120   Process *process;
121 };
122
123 bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
124   Log *log = GetLog(LLDBLog::Language);
125
126   Status err;
127
128   // get the current stack pointer
129   uint64_t sp = ctx.reg_ctx->GetSP();
130
131   for (size_t i = 0; i < num_args; ++i) {
132     ArgItem &arg = arg_list[i];
133     // advance up the stack by one argument
134     sp += sizeof(uint32_t);
135     // get the argument type size
136     size_t arg_size = sizeof(uint32_t);
137     // read the argument from memory
138     arg.value = 0;
139     Status err;
140     size_t read =
141         ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
142     if (read != arg_size || !err.Success()) {
143       LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 " '%s'",
144                 __FUNCTION__, uint64_t(i), err.AsCString());
145       return false;
146     }
147   }
148   return true;
149 }
150
151 bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
152   Log *log = GetLog(LLDBLog::Language);
153
154   // number of arguments passed in registers
155   static const uint32_t args_in_reg = 6;
156   // register passing order
157   static const std::array<const char *, args_in_reg> reg_names{
158       {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
159   // argument type to size mapping
160   static const std::array<size_t, 5> arg_size{{
161       8, // ePointer,
162       4, // eInt32,
163       8, // eInt64,
164       8, // eLong,
165       4, // eBool,
166   }};
167
168   Status err;
169
170   // get the current stack pointer
171   uint64_t sp = ctx.reg_ctx->GetSP();
172   // step over the return address
173   sp += sizeof(uint64_t);
174
175   // check the stack alignment was correct (16 byte aligned)
176   if ((sp & 0xf) != 0x0) {
177     LLDB_LOGF(log, "%s - stack misaligned", __FUNCTION__);
178     return false;
179   }
180
181   // find the start of arguments on the stack
182   uint64_t sp_offset = 0;
183   for (uint32_t i = args_in_reg; i < num_args; ++i) {
184     sp_offset += arg_size[arg_list[i].type];
185   }
186   // round up to multiple of 16
187   sp_offset = (sp_offset + 0xf) & 0xf;
188   sp += sp_offset;
189
190   for (size_t i = 0; i < num_args; ++i) {
191     bool success = false;
192     ArgItem &arg = arg_list[i];
193     // arguments passed in registers
194     if (i < args_in_reg) {
195       const RegisterInfo *reg =
196           ctx.reg_ctx->GetRegisterInfoByName(reg_names[i]);
197       RegisterValue reg_val;
198       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
199         arg.value = reg_val.GetAsUInt64(0, &success);
200     }
201     // arguments passed on the stack
202     else {
203       // get the argument type size
204       const size_t size = arg_size[arg_list[i].type];
205       // read the argument from memory
206       arg.value = 0;
207       // note: due to little endian layout reading 4 or 8 bytes will give the
208       // correct value.
209       size_t read = ctx.process->ReadMemory(sp, &arg.value, size, err);
210       success = (err.Success() && read == size);
211       // advance past this argument
212       sp -= size;
213     }
214     // fail if we couldn't read this argument
215     if (!success) {
216       LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
217                 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
218       return false;
219     }
220   }
221   return true;
222 }
223
224 bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
225   // number of arguments passed in registers
226   static const uint32_t args_in_reg = 4;
227
228   Log *log = GetLog(LLDBLog::Language);
229
230   Status err;
231
232   // get the current stack pointer
233   uint64_t sp = ctx.reg_ctx->GetSP();
234
235   for (size_t i = 0; i < num_args; ++i) {
236     bool success = false;
237     ArgItem &arg = arg_list[i];
238     // arguments passed in registers
239     if (i < args_in_reg) {
240       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
241       RegisterValue reg_val;
242       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
243         arg.value = reg_val.GetAsUInt32(0, &success);
244     }
245     // arguments passed on the stack
246     else {
247       // get the argument type size
248       const size_t arg_size = sizeof(uint32_t);
249       // clear all 64bits
250       arg.value = 0;
251       // read this argument from memory
252       size_t bytes_read =
253           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
254       success = (err.Success() && bytes_read == arg_size);
255       // advance the stack pointer
256       sp += sizeof(uint32_t);
257     }
258     // fail if we couldn't read this argument
259     if (!success) {
260       LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
261                 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
262       return false;
263     }
264   }
265   return true;
266 }
267
268 bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
269   // number of arguments passed in registers
270   static const uint32_t args_in_reg = 8;
271
272   Log *log = GetLog(LLDBLog::Language);
273
274   for (size_t i = 0; i < num_args; ++i) {
275     bool success = false;
276     ArgItem &arg = arg_list[i];
277     // arguments passed in registers
278     if (i < args_in_reg) {
279       const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
280       RegisterValue reg_val;
281       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
282         arg.value = reg_val.GetAsUInt64(0, &success);
283     }
284     // arguments passed on the stack
285     else {
286       LLDB_LOGF(log, "%s - reading arguments spilled to stack not implemented",
287                 __FUNCTION__);
288     }
289     // fail if we couldn't read this argument
290     if (!success) {
291       LLDB_LOGF(log, "%s - error reading argument: %" PRIu64, __FUNCTION__,
292                 uint64_t(i));
293       return false;
294     }
295   }
296   return true;
297 }
298
299 bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
300   // number of arguments passed in registers
301   static const uint32_t args_in_reg = 4;
302   // register file offset to first argument
303   static const uint32_t reg_offset = 4;
304
305   Log *log = GetLog(LLDBLog::Language);
306
307   Status err;
308
309   // find offset to arguments on the stack (+16 to skip over a0-a3 shadow
310   // space)
311   uint64_t sp = ctx.reg_ctx->GetSP() + 16;
312
313   for (size_t i = 0; i < num_args; ++i) {
314     bool success = false;
315     ArgItem &arg = arg_list[i];
316     // arguments passed in registers
317     if (i < args_in_reg) {
318       const RegisterInfo *reg =
319           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
320       RegisterValue reg_val;
321       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
322         arg.value = reg_val.GetAsUInt64(0, &success);
323     }
324     // arguments passed on the stack
325     else {
326       const size_t arg_size = sizeof(uint32_t);
327       arg.value = 0;
328       size_t bytes_read =
329           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
330       success = (err.Success() && bytes_read == arg_size);
331       // advance the stack pointer
332       sp += arg_size;
333     }
334     // fail if we couldn't read this argument
335     if (!success) {
336       LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
337                 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
338       return false;
339     }
340   }
341   return true;
342 }
343
344 bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
345   // number of arguments passed in registers
346   static const uint32_t args_in_reg = 8;
347   // register file offset to first argument
348   static const uint32_t reg_offset = 4;
349
350   Log *log = GetLog(LLDBLog::Language);
351
352   Status err;
353
354   // get the current stack pointer
355   uint64_t sp = ctx.reg_ctx->GetSP();
356
357   for (size_t i = 0; i < num_args; ++i) {
358     bool success = false;
359     ArgItem &arg = arg_list[i];
360     // arguments passed in registers
361     if (i < args_in_reg) {
362       const RegisterInfo *reg =
363           ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
364       RegisterValue reg_val;
365       if (ctx.reg_ctx->ReadRegister(reg, reg_val))
366         arg.value = reg_val.GetAsUInt64(0, &success);
367     }
368     // arguments passed on the stack
369     else {
370       // get the argument type size
371       const size_t arg_size = sizeof(uint64_t);
372       // clear all 64bits
373       arg.value = 0;
374       // read this argument from memory
375       size_t bytes_read =
376           ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
377       success = (err.Success() && bytes_read == arg_size);
378       // advance the stack pointer
379       sp += arg_size;
380     }
381     // fail if we couldn't read this argument
382     if (!success) {
383       LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
384                 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
385       return false;
386     }
387   }
388   return true;
389 }
390
391 bool GetArgs(ExecutionContext &exe_ctx, ArgItem *arg_list, size_t num_args) {
392   Log *log = GetLog(LLDBLog::Language);
393
394   // verify that we have a target
395   if (!exe_ctx.GetTargetPtr()) {
396     LLDB_LOGF(log, "%s - invalid target", __FUNCTION__);
397     return false;
398   }
399
400   GetArgsCtx ctx = {exe_ctx.GetRegisterContext(), exe_ctx.GetProcessPtr()};
401   assert(ctx.reg_ctx && ctx.process);
402
403   // dispatch based on architecture
404   switch (exe_ctx.GetTargetPtr()->GetArchitecture().GetMachine()) {
405   case llvm::Triple::ArchType::x86:
406     return GetArgsX86(ctx, arg_list, num_args);
407
408   case llvm::Triple::ArchType::x86_64:
409     return GetArgsX86_64(ctx, arg_list, num_args);
410
411   case llvm::Triple::ArchType::arm:
412     return GetArgsArm(ctx, arg_list, num_args);
413
414   case llvm::Triple::ArchType::aarch64:
415     return GetArgsAarch64(ctx, arg_list, num_args);
416
417   case llvm::Triple::ArchType::mipsel:
418     return GetArgsMipsel(ctx, arg_list, num_args);
419
420   case llvm::Triple::ArchType::mips64el:
421     return GetArgsMips64el(ctx, arg_list, num_args);
422
423   default:
424     // unsupported architecture
425     if (log) {
426       LLDB_LOGF(log, "%s - architecture not supported: '%s'", __FUNCTION__,
427                 exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
428     }
429     return false;
430   }
431 }
432
433 bool IsRenderScriptScriptModule(ModuleSP module) {
434   if (!module)
435     return false;
436   return module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
437                                                 eSymbolTypeData) != nullptr;
438 }
439
440 bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
441   // takes an argument of the form 'num[,num][,num]'. Where 'coord_s' is a
442   // comma separated 1,2 or 3-dimensional coordinate with the whitespace
443   // trimmed. Missing coordinates are defaulted to zero. If parsing of any
444   // elements fails the contents of &coord are undefined and `false` is
445   // returned, `true` otherwise
446
447   llvm::SmallVector<llvm::StringRef, 4> matches;
448
449   if (!RegularExpression("^([0-9]+),([0-9]+),([0-9]+)$")
450            .Execute(coord_s, &matches) &&
451       !RegularExpression("^([0-9]+),([0-9]+)$").Execute(coord_s, &matches) &&
452       !RegularExpression("^([0-9]+)$").Execute(coord_s, &matches))
453     return false;
454
455   auto get_index = [&](size_t idx, uint32_t &i) -> bool {
456     std::string group;
457     errno = 0;
458     if (idx + 1 < matches.size()) {
459       return !llvm::StringRef(matches[idx + 1]).getAsInteger<uint32_t>(10, i);
460     }
461     return true;
462   };
463
464   return get_index(0, coord.x) && get_index(1, coord.y) &&
465          get_index(2, coord.z);
466 }
467
468 bool SkipPrologue(lldb::ModuleSP &module, Address &addr) {
469   Log *log = GetLog(LLDBLog::Language);
470   SymbolContext sc;
471   uint32_t resolved_flags =
472       module->ResolveSymbolContextForAddress(addr, eSymbolContextFunction, sc);
473   if (resolved_flags & eSymbolContextFunction) {
474     if (sc.function) {
475       const uint32_t offset = sc.function->GetPrologueByteSize();
476       ConstString name = sc.GetFunctionName();
477       if (offset)
478         addr.Slide(offset);
479       LLDB_LOGF(log, "%s: Prologue offset for %s is %" PRIu32, __FUNCTION__,
480                 name.AsCString(), offset);
481     }
482     return true;
483   } else
484     return false;
485 }
486 } // anonymous namespace
487
488 // The ScriptDetails class collects data associated with a single script
489 // instance.
490 struct RenderScriptRuntime::ScriptDetails {
491   ~ScriptDetails() = default;
492
493   enum ScriptType { eScript, eScriptC };
494
495   // The derived type of the script.
496   empirical_type<ScriptType> type;
497   // The name of the original source file.
498   empirical_type<std::string> res_name;
499   // Path to script .so file on the device.
500   empirical_type<std::string> shared_lib;
501   // Directory where kernel objects are cached on device.
502   empirical_type<std::string> cache_dir;
503   // Pointer to the context which owns this script.
504   empirical_type<lldb::addr_t> context;
505   // Pointer to the script object itself.
506   empirical_type<lldb::addr_t> script;
507 };
508
509 // This Element class represents the Element object in RS, defining the type
510 // associated with an Allocation.
511 struct RenderScriptRuntime::Element {
512   // Taken from rsDefines.h
513   enum DataKind {
514     RS_KIND_USER,
515     RS_KIND_PIXEL_L = 7,
516     RS_KIND_PIXEL_A,
517     RS_KIND_PIXEL_LA,
518     RS_KIND_PIXEL_RGB,
519     RS_KIND_PIXEL_RGBA,
520     RS_KIND_PIXEL_DEPTH,
521     RS_KIND_PIXEL_YUV,
522     RS_KIND_INVALID = 100
523   };
524
525   // Taken from rsDefines.h
526   enum DataType {
527     RS_TYPE_NONE = 0,
528     RS_TYPE_FLOAT_16,
529     RS_TYPE_FLOAT_32,
530     RS_TYPE_FLOAT_64,
531     RS_TYPE_SIGNED_8,
532     RS_TYPE_SIGNED_16,
533     RS_TYPE_SIGNED_32,
534     RS_TYPE_SIGNED_64,
535     RS_TYPE_UNSIGNED_8,
536     RS_TYPE_UNSIGNED_16,
537     RS_TYPE_UNSIGNED_32,
538     RS_TYPE_UNSIGNED_64,
539     RS_TYPE_BOOLEAN,
540
541     RS_TYPE_UNSIGNED_5_6_5,
542     RS_TYPE_UNSIGNED_5_5_5_1,
543     RS_TYPE_UNSIGNED_4_4_4_4,
544
545     RS_TYPE_MATRIX_4X4,
546     RS_TYPE_MATRIX_3X3,
547     RS_TYPE_MATRIX_2X2,
548
549     RS_TYPE_ELEMENT = 1000,
550     RS_TYPE_TYPE,
551     RS_TYPE_ALLOCATION,
552     RS_TYPE_SAMPLER,
553     RS_TYPE_SCRIPT,
554     RS_TYPE_MESH,
555     RS_TYPE_PROGRAM_FRAGMENT,
556     RS_TYPE_PROGRAM_VERTEX,
557     RS_TYPE_PROGRAM_RASTER,
558     RS_TYPE_PROGRAM_STORE,
559     RS_TYPE_FONT,
560
561     RS_TYPE_INVALID = 10000
562   };
563
564   std::vector<Element> children; // Child Element fields for structs
565   empirical_type<lldb::addr_t>
566       element_ptr; // Pointer to the RS Element of the Type
567   empirical_type<DataType>
568       type; // Type of each data pointer stored by the allocation
569   empirical_type<DataKind>
570       type_kind; // Defines pixel type if Allocation is created from an image
571   empirical_type<uint32_t>
572       type_vec_size; // Vector size of each data point, e.g '4' for uchar4
573   empirical_type<uint32_t> field_count; // Number of Subelements
574   empirical_type<uint32_t> datum_size;  // Size of a single Element with padding
575   empirical_type<uint32_t> padding;     // Number of padding bytes
576   empirical_type<uint32_t>
577       array_size;        // Number of items in array, only needed for structs
578   ConstString type_name; // Name of type, only needed for structs
579
580   static ConstString 
581   GetFallbackStructName(); // Print this as the type name of a struct Element
582                            // If we can't resolve the actual struct name
583
584   bool ShouldRefresh() const {
585     const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
586     const bool valid_type =
587         type.isValid() && type_vec_size.isValid() && type_kind.isValid();
588     return !valid_ptr || !valid_type || !datum_size.isValid();
589   }
590 };
591
592 // This AllocationDetails class collects data associated with a single
593 // allocation instance.
594 struct RenderScriptRuntime::AllocationDetails {
595   struct Dimension {
596     uint32_t dim_1;
597     uint32_t dim_2;
598     uint32_t dim_3;
599     uint32_t cube_map;
600
601     Dimension() {
602       dim_1 = 0;
603       dim_2 = 0;
604       dim_3 = 0;
605       cube_map = 0;
606     }
607   };
608
609   // The FileHeader struct specifies the header we use for writing allocations
610   // to a binary file. Our format begins with the ASCII characters "RSAD",
611   // identifying the file as an allocation dump. Member variables dims and
612   // hdr_size are then written consecutively, immediately followed by an
613   // instance of the ElementHeader struct. Because Elements can contain
614   // subelements, there may be more than one instance of the ElementHeader
615   // struct. With this first instance being the root element, and the other
616   // instances being the root's descendants. To identify which instances are an
617   // ElementHeader's children, each struct is immediately followed by a
618   // sequence of consecutive offsets to the start of its child structs. These
619   // offsets are
620   // 4 bytes in size, and the 0 offset signifies no more children.
621   struct FileHeader {
622     uint8_t ident[4];  // ASCII 'RSAD' identifying the file
623     uint32_t dims[3];  // Dimensions
624     uint16_t hdr_size; // Header size in bytes, including all element headers
625   };
626
627   struct ElementHeader {
628     uint16_t type;         // DataType enum
629     uint32_t kind;         // DataKind enum
630     uint32_t element_size; // Size of a single element, including padding
631     uint16_t vector_size;  // Vector width
632     uint32_t array_size;   // Number of elements in array
633   };
634
635   // Monotonically increasing from 1
636   static uint32_t ID;
637
638   // Maps Allocation DataType enum and vector size to printable strings using
639   // mapping from RenderScript numerical types summary documentation
640   static const char *RsDataTypeToString[][4];
641
642   // Maps Allocation DataKind enum to printable strings
643   static const char *RsDataKindToString[];
644
645   // Maps allocation types to format sizes for printing.
646   static const uint32_t RSTypeToFormat[][3];
647
648   // Give each allocation an ID as a way
649   // for commands to reference it.
650   const uint32_t id;
651
652   // Allocation Element type
653   RenderScriptRuntime::Element element;
654   // Dimensions of the Allocation
655   empirical_type<Dimension> dimension;
656   // Pointer to address of the RS Allocation
657   empirical_type<lldb::addr_t> address;
658   // Pointer to the data held by the Allocation
659   empirical_type<lldb::addr_t> data_ptr;
660   // Pointer to the RS Type of the Allocation
661   empirical_type<lldb::addr_t> type_ptr;
662   // Pointer to the RS Context of the Allocation
663   empirical_type<lldb::addr_t> context;
664   // Size of the allocation
665   empirical_type<uint32_t> size;
666   // Stride between rows of the allocation
667   empirical_type<uint32_t> stride;
668
669   // Give each allocation an id, so we can reference it in user commands.
670   AllocationDetails() : id(ID++) {}
671
672   bool ShouldRefresh() const {
673     bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
674     valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
675     return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
676            element.ShouldRefresh();
677   }
678 };
679
680 ConstString RenderScriptRuntime::Element::GetFallbackStructName() {
681   static const ConstString FallbackStructName("struct");
682   return FallbackStructName;
683 }
684
685 uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
686
687 const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
688     "User",       "Undefined",   "Undefined", "Undefined",
689     "Undefined",  "Undefined",   "Undefined", // Enum jumps from 0 to 7
690     "L Pixel",    "A Pixel",     "LA Pixel",  "RGB Pixel",
691     "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
692
693 const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
694     {"None", "None", "None", "None"},
695     {"half", "half2", "half3", "half4"},
696     {"float", "float2", "float3", "float4"},
697     {"double", "double2", "double3", "double4"},
698     {"char", "char2", "char3", "char4"},
699     {"short", "short2", "short3", "short4"},
700     {"int", "int2", "int3", "int4"},
701     {"long", "long2", "long3", "long4"},
702     {"uchar", "uchar2", "uchar3", "uchar4"},
703     {"ushort", "ushort2", "ushort3", "ushort4"},
704     {"uint", "uint2", "uint3", "uint4"},
705     {"ulong", "ulong2", "ulong3", "ulong4"},
706     {"bool", "bool2", "bool3", "bool4"},
707     {"packed_565", "packed_565", "packed_565", "packed_565"},
708     {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
709     {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
710     {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
711     {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
712     {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
713
714     // Handlers
715     {"RS Element", "RS Element", "RS Element", "RS Element"},
716     {"RS Type", "RS Type", "RS Type", "RS Type"},
717     {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
718     {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
719     {"RS Script", "RS Script", "RS Script", "RS Script"},
720
721     // Deprecated
722     {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
723     {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
724      "RS Program Fragment"},
725     {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
726      "RS Program Vertex"},
727     {"RS Program Raster", "RS Program Raster", "RS Program Raster",
728      "RS Program Raster"},
729     {"RS Program Store", "RS Program Store", "RS Program Store",
730      "RS Program Store"},
731     {"RS Font", "RS Font", "RS Font", "RS Font"}};
732
733 // Used as an index into the RSTypeToFormat array elements
734 enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
735
736 // { format enum of single element, format enum of element vector, size of
737 // element}
738 const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
739     // RS_TYPE_NONE
740     {eFormatHex, eFormatHex, 1},
741     // RS_TYPE_FLOAT_16
742     {eFormatFloat, eFormatVectorOfFloat16, 2},
743     // RS_TYPE_FLOAT_32
744     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
745     // RS_TYPE_FLOAT_64
746     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
747     // RS_TYPE_SIGNED_8
748     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
749     // RS_TYPE_SIGNED_16
750     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
751     // RS_TYPE_SIGNED_32
752     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
753     // RS_TYPE_SIGNED_64
754     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
755     // RS_TYPE_UNSIGNED_8
756     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
757     // RS_TYPE_UNSIGNED_16
758     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
759     // RS_TYPE_UNSIGNED_32
760     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
761     // RS_TYPE_UNSIGNED_64
762     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
763     // RS_TYPE_BOOL
764     {eFormatBoolean, eFormatBoolean, 1},
765     // RS_TYPE_UNSIGNED_5_6_5
766     {eFormatHex, eFormatHex, sizeof(uint16_t)},
767     // RS_TYPE_UNSIGNED_5_5_5_1
768     {eFormatHex, eFormatHex, sizeof(uint16_t)},
769     // RS_TYPE_UNSIGNED_4_4_4_4
770     {eFormatHex, eFormatHex, sizeof(uint16_t)},
771     // RS_TYPE_MATRIX_4X4
772     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
773     // RS_TYPE_MATRIX_3X3
774     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
775     // RS_TYPE_MATRIX_2X2
776     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
777
778 // Static Functions
779 LanguageRuntime *
780 RenderScriptRuntime::CreateInstance(Process *process,
781                                     lldb::LanguageType language) {
782
783   if (language == eLanguageTypeExtRenderScript)
784     return new RenderScriptRuntime(process);
785   else
786     return nullptr;
787 }
788
789 // Callback with a module to search for matching symbols. We first check that
790 // the module contains RS kernels. Then look for a symbol which matches our
791 // kernel name. The breakpoint address is finally set using the address of this
792 // symbol.
793 Searcher::CallbackReturn
794 RSBreakpointResolver::SearchCallback(SearchFilter &filter,
795                                      SymbolContext &context, Address *) {
796   BreakpointSP breakpoint_sp = GetBreakpoint();
797   assert(breakpoint_sp);
798
799   ModuleSP module = context.module_sp;
800
801   if (!module || !IsRenderScriptScriptModule(module))
802     return Searcher::eCallbackReturnContinue;
803
804   // Attempt to set a breakpoint on the kernel name symbol within the module
805   // library. If it's not found, it's likely debug info is unavailable - try to
806   // set a breakpoint on <name>.expand.
807   const Symbol *kernel_sym =
808       module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
809   if (!kernel_sym) {
810     std::string kernel_name_expanded(m_kernel_name.AsCString());
811     kernel_name_expanded.append(".expand");
812     kernel_sym = module->FindFirstSymbolWithNameAndType(
813         ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
814   }
815
816   if (kernel_sym) {
817     Address bp_addr = kernel_sym->GetAddress();
818     if (filter.AddressPasses(bp_addr))
819       breakpoint_sp->AddLocation(bp_addr);
820   }
821
822   return Searcher::eCallbackReturnContinue;
823 }
824
825 Searcher::CallbackReturn
826 RSReduceBreakpointResolver::SearchCallback(lldb_private::SearchFilter &filter,
827                                            lldb_private::SymbolContext &context,
828                                            Address *) {
829   BreakpointSP breakpoint_sp = GetBreakpoint();
830   assert(breakpoint_sp);
831
832   // We need to have access to the list of reductions currently parsed, as
833   // reduce names don't actually exist as symbols in a module. They are only
834   // identifiable by parsing the .rs.info packet, or finding the expand symbol.
835   // We therefore need access to the list of parsed rs modules to properly
836   // resolve reduction names.
837   Log *log = GetLog(LLDBLog::Breakpoints);
838   ModuleSP module = context.module_sp;
839
840   if (!module || !IsRenderScriptScriptModule(module))
841     return Searcher::eCallbackReturnContinue;
842
843   if (!m_rsmodules)
844     return Searcher::eCallbackReturnContinue;
845
846   for (const auto &module_desc : *m_rsmodules) {
847     if (module_desc->m_module != module)
848       continue;
849
850     for (const auto &reduction : module_desc->m_reductions) {
851       if (reduction.m_reduce_name != m_reduce_name)
852         continue;
853
854       std::array<std::pair<ConstString, int>, 5> funcs{
855           {{reduction.m_init_name, eKernelTypeInit},
856            {reduction.m_accum_name, eKernelTypeAccum},
857            {reduction.m_comb_name, eKernelTypeComb},
858            {reduction.m_outc_name, eKernelTypeOutC},
859            {reduction.m_halter_name, eKernelTypeHalter}}};
860
861       for (const auto &kernel : funcs) {
862         // Skip constituent functions that don't match our spec
863         if (!(m_kernel_types & kernel.second))
864           continue;
865
866         const auto kernel_name = kernel.first;
867         const auto symbol = module->FindFirstSymbolWithNameAndType(
868             kernel_name, eSymbolTypeCode);
869         if (!symbol)
870           continue;
871
872         auto address = symbol->GetAddress();
873         if (filter.AddressPasses(address)) {
874           bool new_bp;
875           if (!SkipPrologue(module, address)) {
876             LLDB_LOGF(log, "%s: Error trying to skip prologue", __FUNCTION__);
877           }
878           breakpoint_sp->AddLocation(address, &new_bp);
879           LLDB_LOGF(log, "%s: %s reduction breakpoint on %s in %s",
880                     __FUNCTION__, new_bp ? "new" : "existing",
881                     kernel_name.GetCString(),
882                     address.GetModule()->GetFileSpec().GetCString());
883         }
884       }
885     }
886   }
887   return eCallbackReturnContinue;
888 }
889
890 Searcher::CallbackReturn RSScriptGroupBreakpointResolver::SearchCallback(
891     SearchFilter &filter, SymbolContext &context, Address *addr) {
892
893   BreakpointSP breakpoint_sp = GetBreakpoint();
894   if (!breakpoint_sp)
895     return eCallbackReturnContinue;
896
897   Log *log = GetLog(LLDBLog::Breakpoints);
898   ModuleSP &module = context.module_sp;
899
900   if (!module || !IsRenderScriptScriptModule(module))
901     return Searcher::eCallbackReturnContinue;
902
903   std::vector<std::string> names;
904   Breakpoint& breakpoint = *breakpoint_sp;
905   breakpoint.GetNames(names);
906   if (names.empty())
907     return eCallbackReturnContinue;
908
909   for (auto &name : names) {
910     const RSScriptGroupDescriptorSP sg = FindScriptGroup(ConstString(name));
911     if (!sg) {
912       LLDB_LOGF(log, "%s: could not find script group for %s", __FUNCTION__,
913                 name.c_str());
914       continue;
915     }
916
917     LLDB_LOGF(log, "%s: Found ScriptGroup for %s", __FUNCTION__, name.c_str());
918
919     for (const RSScriptGroupDescriptor::Kernel &k : sg->m_kernels) {
920       if (log) {
921         LLDB_LOGF(log, "%s: Adding breakpoint for %s", __FUNCTION__,
922                   k.m_name.AsCString());
923         LLDB_LOGF(log, "%s: Kernel address 0x%" PRIx64, __FUNCTION__, k.m_addr);
924       }
925
926       const lldb_private::Symbol *sym =
927           module->FindFirstSymbolWithNameAndType(k.m_name, eSymbolTypeCode);
928       if (!sym) {
929         LLDB_LOGF(log, "%s: Unable to find symbol for %s", __FUNCTION__,
930                   k.m_name.AsCString());
931         continue;
932       }
933
934       if (log) {
935         LLDB_LOGF(log, "%s: Found symbol name is %s", __FUNCTION__,
936                   sym->GetName().AsCString());
937       }
938
939       auto address = sym->GetAddress();
940       if (!SkipPrologue(module, address)) {
941         LLDB_LOGF(log, "%s: Error trying to skip prologue", __FUNCTION__);
942       }
943
944       bool new_bp;
945       breakpoint.AddLocation(address, &new_bp);
946
947       LLDB_LOGF(log, "%s: Placed %sbreakpoint on %s", __FUNCTION__,
948                 new_bp ? "new " : "", k.m_name.AsCString());
949
950       // exit after placing the first breakpoint if we do not intend to stop on
951       // all kernels making up this script group
952       if (!m_stop_on_all)
953         break;
954     }
955   }
956
957   return eCallbackReturnContinue;
958 }
959
960 void RenderScriptRuntime::Initialize() {
961   PluginManager::RegisterPlugin(GetPluginNameStatic(),
962                                 "RenderScript language support", CreateInstance,
963                                 GetCommandObject);
964 }
965
966 void RenderScriptRuntime::Terminate() {
967   PluginManager::UnregisterPlugin(CreateInstance);
968 }
969
970 RenderScriptRuntime::ModuleKind
971 RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
972   if (module_sp) {
973     if (IsRenderScriptScriptModule(module_sp))
974       return eModuleKindKernelObj;
975
976     // Is this the main RS runtime library
977     const ConstString rs_lib("libRS.so");
978     if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
979       return eModuleKindLibRS;
980     }
981
982     const ConstString rs_driverlib("libRSDriver.so");
983     if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
984       return eModuleKindDriver;
985     }
986
987     const ConstString rs_cpureflib("libRSCpuRef.so");
988     if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
989       return eModuleKindImpl;
990     }
991   }
992   return eModuleKindIgnored;
993 }
994
995 bool RenderScriptRuntime::IsRenderScriptModule(
996     const lldb::ModuleSP &module_sp) {
997   return GetModuleKind(module_sp) != eModuleKindIgnored;
998 }
999
1000 void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
1001   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1002
1003   size_t num_modules = module_list.GetSize();
1004   for (size_t i = 0; i < num_modules; i++) {
1005     auto mod = module_list.GetModuleAtIndex(i);
1006     if (IsRenderScriptModule(mod)) {
1007       LoadModule(mod);
1008     }
1009   }
1010 }
1011
1012 bool RenderScriptRuntime::GetDynamicTypeAndAddress(
1013     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
1014     TypeAndOrName &class_type_or_name, Address &address,
1015     Value::ValueType &value_type) {
1016   return false;
1017 }
1018
1019 TypeAndOrName
1020 RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
1021                                       ValueObject &static_value) {
1022   return type_and_or_name;
1023 }
1024
1025 bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
1026   return false;
1027 }
1028
1029 lldb::BreakpointResolverSP
1030 RenderScriptRuntime::CreateExceptionResolver(const lldb::BreakpointSP &bp,
1031                                              bool catch_bp, bool throw_bp) {
1032   BreakpointResolverSP resolver_sp;
1033   return resolver_sp;
1034 }
1035
1036 const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
1037     {
1038         // rsdScript
1039         {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
1040                           "NS0_7ScriptCEPKcS7_PKhjj",
1041          "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
1042          "7ScriptCEPKcS7_PKhmj",
1043          0, RenderScriptRuntime::eModuleKindDriver,
1044          &lldb_private::RenderScriptRuntime::CaptureScriptInit},
1045         {"rsdScriptInvokeForEachMulti",
1046          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1047          "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
1048          "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1049          "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
1050          0, RenderScriptRuntime::eModuleKindDriver,
1051          &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
1052         {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
1053                                   "script7ContextEPKNS0_6ScriptEjPvj",
1054          "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
1055          "6ScriptEjPvm",
1056          0, RenderScriptRuntime::eModuleKindDriver,
1057          &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
1058
1059         // rsdAllocation
1060         {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
1061                               "ontextEPNS0_10AllocationEb",
1062          "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
1063          "10AllocationEb",
1064          0, RenderScriptRuntime::eModuleKindDriver,
1065          &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
1066         {"rsdAllocationRead2D",
1067          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1068          "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1069          "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1070          "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1071          0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1072         {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1073                                  "ript7ContextEPNS0_10AllocationE",
1074          "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1075          "10AllocationE",
1076          0, RenderScriptRuntime::eModuleKindDriver,
1077          &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
1078
1079         // renderscript script groups
1080         {"rsdDebugHintScriptGroup2", "_ZN7android12renderscript21debugHintScrip"
1081                                      "tGroup2EPKcjPKPFvPK24RsExpandKernelDriver"
1082                                      "InfojjjEj",
1083          "_ZN7android12renderscript21debugHintScriptGroup2EPKcjPKPFvPK24RsExpan"
1084          "dKernelDriverInfojjjEj",
1085          0, RenderScriptRuntime::eModuleKindImpl,
1086          &lldb_private::RenderScriptRuntime::CaptureDebugHintScriptGroup2}};
1087
1088 const size_t RenderScriptRuntime::s_runtimeHookCount =
1089     sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
1090
1091 bool RenderScriptRuntime::HookCallback(void *baton,
1092                                        StoppointCallbackContext *ctx,
1093                                        lldb::user_id_t break_id,
1094                                        lldb::user_id_t break_loc_id) {
1095   RuntimeHook *hook = (RuntimeHook *)baton;
1096   ExecutionContext exe_ctx(ctx->exe_ctx_ref);
1097
1098   RenderScriptRuntime *lang_rt = llvm::cast<RenderScriptRuntime>(
1099       exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1100           eLanguageTypeExtRenderScript));
1101
1102   lang_rt->HookCallback(hook, exe_ctx);
1103
1104   return false;
1105 }
1106
1107 void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
1108                                        ExecutionContext &exe_ctx) {
1109   Log *log = GetLog(LLDBLog::Language);
1110
1111   LLDB_LOGF(log, "%s - '%s'", __FUNCTION__, hook->defn->name);
1112
1113   if (hook->defn->grabber) {
1114     (this->*(hook->defn->grabber))(hook, exe_ctx);
1115   }
1116 }
1117
1118 void RenderScriptRuntime::CaptureDebugHintScriptGroup2(
1119     RuntimeHook *hook_info, ExecutionContext &context) {
1120   Log *log = GetLog(LLDBLog::Language);
1121
1122   enum {
1123     eGroupName = 0,
1124     eGroupNameSize,
1125     eKernel,
1126     eKernelCount,
1127   };
1128
1129   std::array<ArgItem, 4> args{{
1130       {ArgItem::ePointer, 0}, // const char         *groupName
1131       {ArgItem::eInt32, 0},   // const uint32_t      groupNameSize
1132       {ArgItem::ePointer, 0}, // const ExpandFuncTy *kernel
1133       {ArgItem::eInt32, 0},   // const uint32_t      kernelCount
1134   }};
1135
1136   if (!GetArgs(context, args.data(), args.size())) {
1137     LLDB_LOGF(log, "%s - Error while reading the function parameters",
1138               __FUNCTION__);
1139     return;
1140   } else if (log) {
1141     LLDB_LOGF(log, "%s - groupName    : 0x%" PRIx64, __FUNCTION__,
1142               addr_t(args[eGroupName]));
1143     LLDB_LOGF(log, "%s - groupNameSize: %" PRIu64, __FUNCTION__,
1144               uint64_t(args[eGroupNameSize]));
1145     LLDB_LOGF(log, "%s - kernel       : 0x%" PRIx64, __FUNCTION__,
1146               addr_t(args[eKernel]));
1147     LLDB_LOGF(log, "%s - kernelCount  : %" PRIu64, __FUNCTION__,
1148               uint64_t(args[eKernelCount]));
1149   }
1150
1151   // parse script group name
1152   ConstString group_name;
1153   {
1154     Status err;
1155     const uint64_t len = uint64_t(args[eGroupNameSize]);
1156     std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]);
1157     m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err);
1158     buffer.get()[len] = '\0';
1159     if (!err.Success()) {
1160       LLDB_LOGF(log, "Error reading scriptgroup name from target");
1161       return;
1162     } else {
1163       LLDB_LOGF(log, "Extracted scriptgroup name %s", buffer.get());
1164     }
1165     // write back the script group name
1166     group_name.SetCString(buffer.get());
1167   }
1168
1169   // create or access existing script group
1170   RSScriptGroupDescriptorSP group;
1171   {
1172     // search for existing script group
1173     for (auto sg : m_scriptGroups) {
1174       if (sg->m_name == group_name) {
1175         group = sg;
1176         break;
1177       }
1178     }
1179     if (!group) {
1180       group = std::make_shared<RSScriptGroupDescriptor>();
1181       group->m_name = group_name;
1182       m_scriptGroups.push_back(group);
1183     } else {
1184       // already have this script group
1185       LLDB_LOGF(log, "Attempt to add duplicate script group %s",
1186                 group_name.AsCString());
1187       return;
1188     }
1189   }
1190   assert(group);
1191
1192   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1193   std::vector<addr_t> kernels;
1194   // parse kernel addresses in script group
1195   for (uint64_t i = 0; i < uint64_t(args[eKernelCount]); ++i) {
1196     RSScriptGroupDescriptor::Kernel kernel;
1197     // extract script group kernel addresses from the target
1198     const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size;
1199     uint64_t kernel_addr = 0;
1200     Status err;
1201     size_t read =
1202         m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err);
1203     if (!err.Success() || read != target_ptr_size) {
1204       LLDB_LOGF(log, "Error parsing kernel address %" PRIu64 " in script group",
1205                 i);
1206       return;
1207     }
1208     LLDB_LOGF(log, "Extracted scriptgroup kernel address - 0x%" PRIx64,
1209               kernel_addr);
1210     kernel.m_addr = kernel_addr;
1211
1212     // try to resolve the associated kernel name
1213     if (!ResolveKernelName(kernel.m_addr, kernel.m_name)) {
1214       LLDB_LOGF(log, "Parsed scriptgroup kernel %" PRIu64 " - 0x%" PRIx64, i,
1215                 kernel_addr);
1216       return;
1217     }
1218
1219     // try to find the non '.expand' function
1220     {
1221       const llvm::StringRef expand(".expand");
1222       const llvm::StringRef name_ref = kernel.m_name.GetStringRef();
1223       if (name_ref.endswith(expand)) {
1224         const ConstString base_kernel(name_ref.drop_back(expand.size()));
1225         // verify this function is a valid kernel
1226         if (IsKnownKernel(base_kernel)) {
1227           kernel.m_name = base_kernel;
1228           LLDB_LOGF(log, "%s - found non expand version '%s'", __FUNCTION__,
1229                     base_kernel.GetCString());
1230         }
1231       }
1232     }
1233     // add to a list of script group kernels we know about
1234     group->m_kernels.push_back(kernel);
1235   }
1236
1237   // Resolve any pending scriptgroup breakpoints
1238   {
1239     Target &target = m_process->GetTarget();
1240     const BreakpointList &list = target.GetBreakpointList();
1241     const size_t num_breakpoints = list.GetSize();
1242     LLDB_LOGF(log, "Resolving %zu breakpoints", num_breakpoints);
1243     for (size_t i = 0; i < num_breakpoints; ++i) {
1244       const BreakpointSP bp = list.GetBreakpointAtIndex(i);
1245       if (bp) {
1246         if (bp->MatchesName(group_name.AsCString())) {
1247           LLDB_LOGF(log, "Found breakpoint with name %s",
1248                     group_name.AsCString());
1249           bp->ResolveBreakpoint();
1250         }
1251       }
1252     }
1253   }
1254 }
1255
1256 void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
1257     RuntimeHook *hook, ExecutionContext &exe_ctx) {
1258   Log *log = GetLog(LLDBLog::Language);
1259
1260   enum {
1261     eRsContext = 0,
1262     eRsScript,
1263     eRsSlot,
1264     eRsAIns,
1265     eRsInLen,
1266     eRsAOut,
1267     eRsUsr,
1268     eRsUsrLen,
1269     eRsSc,
1270   };
1271
1272   std::array<ArgItem, 9> args{{
1273       ArgItem{ArgItem::ePointer, 0}, // const Context       *rsc
1274       ArgItem{ArgItem::ePointer, 0}, // Script              *s
1275       ArgItem{ArgItem::eInt32, 0},   // uint32_t             slot
1276       ArgItem{ArgItem::ePointer, 0}, // const Allocation   **aIns
1277       ArgItem{ArgItem::eInt32, 0},   // size_t               inLen
1278       ArgItem{ArgItem::ePointer, 0}, // Allocation          *aout
1279       ArgItem{ArgItem::ePointer, 0}, // const void          *usr
1280       ArgItem{ArgItem::eInt32, 0},   // size_t               usrLen
1281       ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall  *sc
1282   }};
1283
1284   bool success = GetArgs(exe_ctx, &args[0], args.size());
1285   if (!success) {
1286     LLDB_LOGF(log, "%s - Error while reading the function parameters",
1287               __FUNCTION__);
1288     return;
1289   }
1290
1291   const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1292   Status err;
1293   std::vector<uint64_t> allocs;
1294
1295   // traverse allocation list
1296   for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1297     // calculate offest to allocation pointer
1298     const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1299
1300     // Note: due to little endian layout, reading 32bits or 64bits into res
1301     // will give the correct results.
1302     uint64_t result = 0;
1303     size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
1304     if (read != target_ptr_size || !err.Success()) {
1305       LLDB_LOGF(log,
1306                 "%s - Error while reading allocation list argument %" PRIu64,
1307                 __FUNCTION__, i);
1308     } else {
1309       allocs.push_back(result);
1310     }
1311   }
1312
1313   // if there is an output allocation track it
1314   if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
1315     allocs.push_back(alloc_out);
1316   }
1317
1318   // for all allocations we have found
1319   for (const uint64_t alloc_addr : allocs) {
1320     AllocationDetails *alloc = LookUpAllocation(alloc_addr);
1321     if (!alloc)
1322       alloc = CreateAllocation(alloc_addr);
1323
1324     if (alloc) {
1325       // save the allocation address
1326       if (alloc->address.isValid()) {
1327         // check the allocation address we already have matches
1328         assert(*alloc->address.get() == alloc_addr);
1329       } else {
1330         alloc->address = alloc_addr;
1331       }
1332
1333       // save the context
1334       if (log) {
1335         if (alloc->context.isValid() &&
1336             *alloc->context.get() != addr_t(args[eRsContext]))
1337           LLDB_LOGF(log, "%s - Allocation used by multiple contexts",
1338                     __FUNCTION__);
1339       }
1340       alloc->context = addr_t(args[eRsContext]);
1341     }
1342   }
1343
1344   // make sure we track this script object
1345   if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1346           LookUpScript(addr_t(args[eRsScript]), true)) {
1347     if (log) {
1348       if (script->context.isValid() &&
1349           *script->context.get() != addr_t(args[eRsContext]))
1350         LLDB_LOGF(log, "%s - Script used by multiple contexts", __FUNCTION__);
1351     }
1352     script->context = addr_t(args[eRsContext]);
1353   }
1354 }
1355
1356 void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1357                                               ExecutionContext &context) {
1358   Log *log = GetLog(LLDBLog::Language);
1359
1360   enum {
1361     eRsContext,
1362     eRsScript,
1363     eRsId,
1364     eRsData,
1365     eRsLength,
1366   };
1367
1368   std::array<ArgItem, 5> args{{
1369       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1370       ArgItem{ArgItem::ePointer, 0}, // eRsScript
1371       ArgItem{ArgItem::eInt32, 0},   // eRsId
1372       ArgItem{ArgItem::ePointer, 0}, // eRsData
1373       ArgItem{ArgItem::eInt32, 0},   // eRsLength
1374   }};
1375
1376   bool success = GetArgs(context, &args[0], args.size());
1377   if (!success) {
1378     LLDB_LOGF(log, "%s - error reading the function parameters.", __FUNCTION__);
1379     return;
1380   }
1381
1382   if (log) {
1383     LLDB_LOGF(log,
1384               "%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1385               ":%" PRIu64 "bytes.",
1386               __FUNCTION__, uint64_t(args[eRsContext]),
1387               uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1388               uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
1389
1390     addr_t script_addr = addr_t(args[eRsScript]);
1391     if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
1392       auto rsm = m_scriptMappings[script_addr];
1393       if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1394         auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1395         LLDB_LOGF(log, "%s - Setting of '%s' within '%s' inferred",
1396                   __FUNCTION__, rsg.m_name.AsCString(),
1397                   rsm->m_module->GetFileSpec().GetFilename().AsCString());
1398       }
1399     }
1400   }
1401 }
1402
1403 void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
1404                                                 ExecutionContext &exe_ctx) {
1405   Log *log = GetLog(LLDBLog::Language);
1406
1407   enum { eRsContext, eRsAlloc, eRsForceZero };
1408
1409   std::array<ArgItem, 3> args{{
1410       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1411       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1412       ArgItem{ArgItem::eBool, 0},    // eRsForceZero
1413   }};
1414
1415   bool success = GetArgs(exe_ctx, &args[0], args.size());
1416   if (!success) {
1417     LLDB_LOGF(log, "%s - error while reading the function parameters",
1418               __FUNCTION__);
1419     return;
1420   }
1421
1422   LLDB_LOGF(log, "%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1423             __FUNCTION__, uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]),
1424             uint64_t(args[eRsForceZero]));
1425
1426   AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
1427   if (alloc)
1428     alloc->context = uint64_t(args[eRsContext]);
1429 }
1430
1431 void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
1432                                                    ExecutionContext &exe_ctx) {
1433   Log *log = GetLog(LLDBLog::Language);
1434
1435   enum {
1436     eRsContext,
1437     eRsAlloc,
1438   };
1439
1440   std::array<ArgItem, 2> args{{
1441       ArgItem{ArgItem::ePointer, 0}, // eRsContext
1442       ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1443   }};
1444
1445   bool success = GetArgs(exe_ctx, &args[0], args.size());
1446   if (!success) {
1447     LLDB_LOGF(log, "%s - error while reading the function parameters.",
1448               __FUNCTION__);
1449     return;
1450   }
1451
1452   LLDB_LOGF(log, "%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1453             uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1454
1455   for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1456     auto &allocation_up = *iter; // get the unique pointer
1457     if (allocation_up->address.isValid() &&
1458         *allocation_up->address.get() == addr_t(args[eRsAlloc])) {
1459       m_allocations.erase(iter);
1460       LLDB_LOGF(log, "%s - deleted allocation entry.", __FUNCTION__);
1461       return;
1462     }
1463   }
1464
1465   LLDB_LOGF(log, "%s - couldn't find destroyed allocation.", __FUNCTION__);
1466 }
1467
1468 void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
1469                                             ExecutionContext &exe_ctx) {
1470   Log *log = GetLog(LLDBLog::Language);
1471
1472   Status err;
1473   Process *process = exe_ctx.GetProcessPtr();
1474
1475   enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
1476
1477   std::array<ArgItem, 4> args{
1478       {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
1479        ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
1480   bool success = GetArgs(exe_ctx, &args[0], args.size());
1481   if (!success) {
1482     LLDB_LOGF(log, "%s - error while reading the function parameters.",
1483               __FUNCTION__);
1484     return;
1485   }
1486
1487   std::string res_name;
1488   process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
1489   if (err.Fail()) {
1490     LLDB_LOGF(log, "%s - error reading res_name: %s.", __FUNCTION__,
1491               err.AsCString());
1492   }
1493
1494   std::string cache_dir;
1495   process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
1496   if (err.Fail()) {
1497     LLDB_LOGF(log, "%s - error reading cache_dir: %s.", __FUNCTION__,
1498               err.AsCString());
1499   }
1500
1501   LLDB_LOGF(log, "%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1502             __FUNCTION__, uint64_t(args[eRsContext]), uint64_t(args[eRsScript]),
1503             res_name.c_str(), cache_dir.c_str());
1504
1505   if (res_name.size() > 0) {
1506     StreamString strm;
1507     strm.Printf("librs.%s.so", res_name.c_str());
1508
1509     ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1510     if (script) {
1511       script->type = ScriptDetails::eScriptC;
1512       script->cache_dir = cache_dir;
1513       script->res_name = res_name;
1514       script->shared_lib = std::string(strm.GetString());
1515       script->context = addr_t(args[eRsContext]);
1516     }
1517
1518     LLDB_LOGF(log,
1519               "%s - '%s' tagged with context 0x%" PRIx64
1520               " and script 0x%" PRIx64 ".",
1521               __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1522               uint64_t(args[eRsScript]));
1523   } else if (log) {
1524     LLDB_LOGF(log, "%s - resource name invalid, Script not tagged.",
1525               __FUNCTION__);
1526   }
1527 }
1528
1529 void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1530                                            ModuleKind kind) {
1531   Log *log = GetLog(LLDBLog::Language);
1532
1533   if (!module) {
1534     return;
1535   }
1536
1537   Target &target = GetProcess()->GetTarget();
1538   const llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
1539
1540   if (machine != llvm::Triple::ArchType::x86 &&
1541       machine != llvm::Triple::ArchType::arm &&
1542       machine != llvm::Triple::ArchType::aarch64 &&
1543       machine != llvm::Triple::ArchType::mipsel &&
1544       machine != llvm::Triple::ArchType::mips64el &&
1545       machine != llvm::Triple::ArchType::x86_64) {
1546     LLDB_LOGF(log, "%s - unable to hook runtime functions.", __FUNCTION__);
1547     return;
1548   }
1549
1550   const uint32_t target_ptr_size =
1551       target.GetArchitecture().GetAddressByteSize();
1552
1553   std::array<bool, s_runtimeHookCount> hook_placed;
1554   hook_placed.fill(false);
1555
1556   for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
1557     const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1558     if (hook_defn->kind != kind) {
1559       continue;
1560     }
1561
1562     const char *symbol_name = (target_ptr_size == 4)
1563                                   ? hook_defn->symbol_name_m32
1564                                   : hook_defn->symbol_name_m64;
1565
1566     const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1567         ConstString(symbol_name), eSymbolTypeCode);
1568     if (!sym) {
1569       if (log) {
1570         LLDB_LOGF(log, "%s - symbol '%s' related to the function %s not found",
1571                   __FUNCTION__, symbol_name, hook_defn->name);
1572       }
1573       continue;
1574     }
1575
1576     addr_t addr = sym->GetLoadAddress(&target);
1577     if (addr == LLDB_INVALID_ADDRESS) {
1578       LLDB_LOGF(log,
1579                 "%s - unable to resolve the address of hook function '%s' "
1580                 "with symbol '%s'.",
1581                 __FUNCTION__, hook_defn->name, symbol_name);
1582       continue;
1583     } else {
1584       LLDB_LOGF(log, "%s - function %s, address resolved at 0x%" PRIx64,
1585                 __FUNCTION__, hook_defn->name, addr);
1586     }
1587
1588     RuntimeHookSP hook(new RuntimeHook());
1589     hook->address = addr;
1590     hook->defn = hook_defn;
1591     hook->bp_sp = target.CreateBreakpoint(addr, true, false);
1592     hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
1593     m_runtimeHooks[addr] = hook;
1594     if (log) {
1595       LLDB_LOGF(log,
1596                 "%s - successfully hooked '%s' in '%s' version %" PRIu64
1597                 " at 0x%" PRIx64 ".",
1598                 __FUNCTION__, hook_defn->name,
1599                 module->GetFileSpec().GetFilename().AsCString(),
1600                 (uint64_t)hook_defn->version, (uint64_t)addr);
1601     }
1602     hook_placed[idx] = true;
1603   }
1604
1605   // log any unhooked function
1606   if (log) {
1607     for (size_t i = 0; i < hook_placed.size(); ++i) {
1608       if (hook_placed[i])
1609         continue;
1610       const HookDefn &hook_defn = s_runtimeHookDefns[i];
1611       if (hook_defn.kind != kind)
1612         continue;
1613       LLDB_LOGF(log, "%s - function %s was not hooked", __FUNCTION__,
1614                 hook_defn.name);
1615     }
1616   }
1617 }
1618
1619 void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
1620   if (!rsmodule_sp)
1621     return;
1622
1623   Log *log = GetLog(LLDBLog::Language);
1624
1625   const ModuleSP module = rsmodule_sp->m_module;
1626   const FileSpec &file = module->GetPlatformFileSpec();
1627
1628   // Iterate over all of the scripts that we currently know of. Note: We cant
1629   // push or pop to m_scripts here or it may invalidate rs_script.
1630   for (const auto &rs_script : m_scripts) {
1631     // Extract the expected .so file path for this script.
1632     std::string shared_lib;
1633     if (!rs_script->shared_lib.get(shared_lib))
1634       continue;
1635
1636     // Only proceed if the module that has loaded corresponds to this script.
1637     if (file.GetFilename() != ConstString(shared_lib.c_str()))
1638       continue;
1639
1640     // Obtain the script address which we use as a key.
1641     lldb::addr_t script;
1642     if (!rs_script->script.get(script))
1643       continue;
1644
1645     // If we have a script mapping for the current script.
1646     if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
1647       // if the module we have stored is different to the one we just received.
1648       if (m_scriptMappings[script] != rsmodule_sp) {
1649         LLDB_LOGF(
1650             log,
1651             "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1652             __FUNCTION__, (uint64_t)script,
1653             rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1654       }
1655     }
1656     // We don't have a script mapping for the current script.
1657     else {
1658       // Obtain the script resource name.
1659       std::string res_name;
1660       if (rs_script->res_name.get(res_name))
1661         // Set the modules resource name.
1662         rsmodule_sp->m_resname = res_name;
1663       // Add Script/Module pair to map.
1664       m_scriptMappings[script] = rsmodule_sp;
1665       LLDB_LOGF(log, "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1666                 __FUNCTION__, (uint64_t)script,
1667                 rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1668     }
1669   }
1670 }
1671
1672 // Uses the Target API to evaluate the expression passed as a parameter to the
1673 // function The result of that expression is returned an unsigned 64 bit int,
1674 // via the result* parameter. Function returns true on success, and false on
1675 // failure
1676 bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1677                                            StackFrame *frame_ptr,
1678                                            uint64_t *result) {
1679   Log *log = GetLog(LLDBLog::Language);
1680   LLDB_LOGF(log, "%s(%s)", __FUNCTION__, expr);
1681
1682   ValueObjectSP expr_result;
1683   EvaluateExpressionOptions options;
1684   options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
1685   // Perform the actual expression evaluation
1686   auto &target = GetProcess()->GetTarget();
1687   target.EvaluateExpression(expr, frame_ptr, expr_result, options);
1688
1689   if (!expr_result) {
1690     LLDB_LOGF(log, "%s: couldn't evaluate expression.", __FUNCTION__);
1691     return false;
1692   }
1693
1694   // The result of the expression is invalid
1695   if (!expr_result->GetError().Success()) {
1696     Status err = expr_result->GetError();
1697     // Expression returned is void, so this is actually a success
1698     if (err.GetError() == UserExpression::kNoResult) {
1699       LLDB_LOGF(log, "%s - expression returned void.", __FUNCTION__);
1700
1701       result = nullptr;
1702       return true;
1703     }
1704
1705     LLDB_LOGF(log, "%s - error evaluating expression result: %s", __FUNCTION__,
1706               err.AsCString());
1707     return false;
1708   }
1709
1710   bool success = false;
1711   // We only read the result as an uint32_t.
1712   *result = expr_result->GetValueAsUnsigned(0, &success);
1713
1714   if (!success) {
1715     LLDB_LOGF(log, "%s - couldn't convert expression result to uint32_t",
1716               __FUNCTION__);
1717     return false;
1718   }
1719
1720   return true;
1721 }
1722
1723 namespace {
1724 // Used to index expression format strings
1725 enum ExpressionStrings {
1726   eExprGetOffsetPtr = 0,
1727   eExprAllocGetType,
1728   eExprTypeDimX,
1729   eExprTypeDimY,
1730   eExprTypeDimZ,
1731   eExprTypeElemPtr,
1732   eExprElementType,
1733   eExprElementKind,
1734   eExprElementVec,
1735   eExprElementFieldCount,
1736   eExprSubelementsId,
1737   eExprSubelementsName,
1738   eExprSubelementsArrSize,
1739
1740   _eExprLast // keep at the end, implicit size of the array runtime_expressions
1741 };
1742
1743 // max length of an expanded expression
1744 const int jit_max_expr_size = 512;
1745
1746 // Retrieve the string to JIT for the given expression
1747 #define JIT_TEMPLATE_CONTEXT "void* ctxt = (void*)rsDebugGetContextWrapper(0x%" PRIx64 "); "
1748 const char *JITTemplate(ExpressionStrings e) {
1749   // Format strings containing the expressions we may need to evaluate.
1750   static std::array<const char *, _eExprLast> runtime_expressions = {
1751       {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1752        "(int*)_"
1753        "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1754        "CubemapFace"
1755        "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)", // eExprGetOffsetPtr
1756
1757        // Type* rsaAllocationGetType(Context*, Allocation*)
1758        JIT_TEMPLATE_CONTEXT "(void*)rsaAllocationGetType(ctxt, 0x%" PRIx64 ")", // eExprAllocGetType
1759
1760        // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
1761        // data in the following way mHal.state.dimX; mHal.state.dimY;
1762        // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement;
1763        // into typeData Need to specify 32 or 64 bit for uint_t since this
1764        // differs between devices
1765        JIT_TEMPLATE_CONTEXT
1766        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1767        ", 0x%" PRIx64 ", data, 6); data[0]", // eExprTypeDimX
1768        JIT_TEMPLATE_CONTEXT
1769        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1770        ", 0x%" PRIx64 ", data, 6); data[1]", // eExprTypeDimY
1771        JIT_TEMPLATE_CONTEXT
1772        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1773        ", 0x%" PRIx64 ", data, 6); data[2]", // eExprTypeDimZ
1774        JIT_TEMPLATE_CONTEXT
1775        "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1776        ", 0x%" PRIx64 ", data, 6); data[5]", // eExprTypeElemPtr
1777
1778        // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1779        // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1780        // elemData
1781        JIT_TEMPLATE_CONTEXT
1782        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1783        ", 0x%" PRIx64 ", data, 5); data[0]", // eExprElementType
1784        JIT_TEMPLATE_CONTEXT
1785        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1786        ", 0x%" PRIx64 ", data, 5); data[1]", // eExprElementKind
1787        JIT_TEMPLATE_CONTEXT
1788        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1789        ", 0x%" PRIx64 ", data, 5); data[3]", // eExprElementVec
1790        JIT_TEMPLATE_CONTEXT
1791        "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1792        ", 0x%" PRIx64 ", data, 5); data[4]", // eExprElementFieldCount
1793
1794        // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
1795        // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1796        // Needed for Allocations of structs to gather details about
1797        // fields/Subelements Element* of field
1798        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1799        "]; size_t arr_size[%" PRIu32 "];"
1800        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1801        ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]", // eExprSubelementsId
1802
1803        // Name of field
1804        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1805        "]; size_t arr_size[%" PRIu32 "];"
1806        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1807        ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]", // eExprSubelementsName
1808
1809        // Array size of field
1810        JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1811        "]; size_t arr_size[%" PRIu32 "];"
1812        "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1813        ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}}; // eExprSubelementsArrSize
1814
1815   return runtime_expressions[e];
1816 }
1817 } // end of the anonymous namespace
1818
1819 // JITs the RS runtime for the internal data pointer of an allocation. Is
1820 // passed x,y,z coordinates for the pointer to a specific element. Then sets
1821 // the data_ptr member in Allocation with the result. Returns true on success,
1822 // false otherwise
1823 bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1824                                          StackFrame *frame_ptr, uint32_t x,
1825                                          uint32_t y, uint32_t z) {
1826   Log *log = GetLog(LLDBLog::Language);
1827
1828   if (!alloc->address.isValid()) {
1829     LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
1830     return false;
1831   }
1832
1833   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
1834   char expr_buf[jit_max_expr_size];
1835
1836   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1837                          *alloc->address.get(), x, y, z);
1838   if (written < 0) {
1839     LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
1840     return false;
1841   } else if (written >= jit_max_expr_size) {
1842     LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
1843     return false;
1844   }
1845
1846   uint64_t result = 0;
1847   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1848     return false;
1849
1850   addr_t data_ptr = static_cast<lldb::addr_t>(result);
1851   alloc->data_ptr = data_ptr;
1852
1853   return true;
1854 }
1855
1856 // JITs the RS runtime for the internal pointer to the RS Type of an allocation
1857 // Then sets the type_ptr member in Allocation with the result. Returns true on
1858 // success, false otherwise
1859 bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1860                                          StackFrame *frame_ptr) {
1861   Log *log = GetLog(LLDBLog::Language);
1862
1863   if (!alloc->address.isValid() || !alloc->context.isValid()) {
1864     LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
1865     return false;
1866   }
1867
1868   const char *fmt_str = JITTemplate(eExprAllocGetType);
1869   char expr_buf[jit_max_expr_size];
1870
1871   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1872                          *alloc->context.get(), *alloc->address.get());
1873   if (written < 0) {
1874     LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
1875     return false;
1876   } else if (written >= jit_max_expr_size) {
1877     LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
1878     return false;
1879   }
1880
1881   uint64_t result = 0;
1882   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1883     return false;
1884
1885   addr_t type_ptr = static_cast<lldb::addr_t>(result);
1886   alloc->type_ptr = type_ptr;
1887
1888   return true;
1889 }
1890
1891 // JITs the RS runtime for information about the dimensions and type of an
1892 // allocation Then sets dimension and element_ptr members in Allocation with
1893 // the result. Returns true on success, false otherwise
1894 bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1895                                         StackFrame *frame_ptr) {
1896   Log *log = GetLog(LLDBLog::Language);
1897
1898   if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
1899     LLDB_LOGF(log, "%s - Failed to find allocation details.", __FUNCTION__);
1900     return false;
1901   }
1902
1903   // Expression is different depending on if device is 32 or 64 bit
1904   uint32_t target_ptr_size =
1905       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
1906   const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
1907
1908   // We want 4 elements from packed data
1909   const uint32_t num_exprs = 4;
1910   static_assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1),
1911                 "Invalid number of expressions");
1912
1913   char expr_bufs[num_exprs][jit_max_expr_size];
1914   uint64_t results[num_exprs];
1915
1916   for (uint32_t i = 0; i < num_exprs; ++i) {
1917     const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
1918     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str,
1919                            *alloc->context.get(), bits, *alloc->type_ptr.get());
1920     if (written < 0) {
1921       LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
1922       return false;
1923     } else if (written >= jit_max_expr_size) {
1924       LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
1925       return false;
1926     }
1927
1928     // Perform expression evaluation
1929     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
1930       return false;
1931   }
1932
1933   // Assign results to allocation members
1934   AllocationDetails::Dimension dims;
1935   dims.dim_1 = static_cast<uint32_t>(results[0]);
1936   dims.dim_2 = static_cast<uint32_t>(results[1]);
1937   dims.dim_3 = static_cast<uint32_t>(results[2]);
1938   alloc->dimension = dims;
1939
1940   addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
1941   alloc->element.element_ptr = element_ptr;
1942
1943   LLDB_LOGF(log,
1944             "%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
1945             ") Element*: 0x%" PRIx64 ".",
1946             __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
1947
1948   return true;
1949 }
1950
1951 // JITs the RS runtime for information about the Element of an allocation Then
1952 // sets type, type_vec_size, field_count and type_kind members in Element with
1953 // the result. Returns true on success, false otherwise
1954 bool RenderScriptRuntime::JITElementPacked(Element &elem,
1955                                            const lldb::addr_t context,
1956                                            StackFrame *frame_ptr) {
1957   Log *log = GetLog(LLDBLog::Language);
1958
1959   if (!elem.element_ptr.isValid()) {
1960     LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
1961     return false;
1962   }
1963
1964   // We want 4 elements from packed data
1965   const uint32_t num_exprs = 4;
1966   static_assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1),
1967                 "Invalid number of expressions");
1968
1969   char expr_bufs[num_exprs][jit_max_expr_size];
1970   uint64_t results[num_exprs];
1971
1972   for (uint32_t i = 0; i < num_exprs; i++) {
1973     const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
1974     int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
1975                            *elem.element_ptr.get());
1976     if (written < 0) {
1977       LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
1978       return false;
1979     } else if (written >= jit_max_expr_size) {
1980       LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
1981       return false;
1982     }
1983
1984     // Perform expression evaluation
1985     if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
1986       return false;
1987   }
1988
1989   // Assign results to allocation members
1990   elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
1991   elem.type_kind =
1992       static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
1993   elem.type_vec_size = static_cast<uint32_t>(results[2]);
1994   elem.field_count = static_cast<uint32_t>(results[3]);
1995
1996   LLDB_LOGF(log,
1997             "%s - data type %" PRIu32 ", pixel type %" PRIu32
1998             ", vector size %" PRIu32 ", field count %" PRIu32,
1999             __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
2000             *elem.type_vec_size.get(), *elem.field_count.get());
2001
2002   // If this Element has subelements then JIT rsaElementGetSubElements() for
2003   // details about its fields
2004   return !(*elem.field_count.get() > 0 &&
2005            !JITSubelements(elem, context, frame_ptr));
2006 }
2007
2008 // JITs the RS runtime for information about the subelements/fields of a struct
2009 // allocation This is necessary for infering the struct type so we can pretty
2010 // print the allocation's contents. Returns true on success, false otherwise
2011 bool RenderScriptRuntime::JITSubelements(Element &elem,
2012                                          const lldb::addr_t context,
2013                                          StackFrame *frame_ptr) {
2014   Log *log = GetLog(LLDBLog::Language);
2015
2016   if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
2017     LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
2018     return false;
2019   }
2020
2021   const short num_exprs = 3;
2022   static_assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1),
2023                 "Invalid number of expressions");
2024
2025   char expr_buffer[jit_max_expr_size];
2026   uint64_t results;
2027
2028   // Iterate over struct fields.
2029   const uint32_t field_count = *elem.field_count.get();
2030   for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
2031     Element child;
2032     for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
2033       const char *fmt_str =
2034           JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
2035       int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
2036                              context, field_count, field_count, field_count,
2037                              *elem.element_ptr.get(), field_count, field_index);
2038       if (written < 0) {
2039         LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
2040         return false;
2041       } else if (written >= jit_max_expr_size) {
2042         LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
2043         return false;
2044       }
2045
2046       // Perform expression evaluation
2047       if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
2048         return false;
2049
2050       LLDB_LOGF(log, "%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
2051
2052       switch (expr_index) {
2053       case 0: // Element* of child
2054         child.element_ptr = static_cast<addr_t>(results);
2055         break;
2056       case 1: // Name of child
2057       {
2058         lldb::addr_t address = static_cast<addr_t>(results);
2059         Status err;
2060         std::string name;
2061         GetProcess()->ReadCStringFromMemory(address, name, err);
2062         if (!err.Fail())
2063           child.type_name = ConstString(name);
2064         else {
2065           LLDB_LOGF(log, "%s - warning: Couldn't read field name.",
2066                     __FUNCTION__);
2067         }
2068         break;
2069       }
2070       case 2: // Array size of child
2071         child.array_size = static_cast<uint32_t>(results);
2072         break;
2073       }
2074     }
2075
2076     // We need to recursively JIT each Element field of the struct since
2077     // structs can be nested inside structs.
2078     if (!JITElementPacked(child, context, frame_ptr))
2079       return false;
2080     elem.children.push_back(child);
2081   }
2082
2083   // Try to infer the name of the struct type so we can pretty print the
2084   // allocation contents.
2085   FindStructTypeName(elem, frame_ptr);
2086
2087   return true;
2088 }
2089
2090 // JITs the RS runtime for the address of the last element in the allocation.
2091 // The `elem_size` parameter represents the size of a single element, including
2092 // padding. Which is needed as an offset from the last element pointer. Using
2093 // this offset minus the starting address we can calculate the size of the
2094 // allocation. Returns true on success, false otherwise
2095 bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
2096                                             StackFrame *frame_ptr) {
2097   Log *log = GetLog(LLDBLog::Language);
2098
2099   if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
2100       !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
2101     LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
2102     return false;
2103   }
2104
2105   // Find dimensions
2106   uint32_t dim_x = alloc->dimension.get()->dim_1;
2107   uint32_t dim_y = alloc->dimension.get()->dim_2;
2108   uint32_t dim_z = alloc->dimension.get()->dim_3;
2109
2110   // Our plan of jitting the last element address doesn't seem to work for
2111   // struct Allocations` Instead try to infer the size ourselves without any
2112   // inter element padding.
2113   if (alloc->element.children.size() > 0) {
2114     if (dim_x == 0)
2115       dim_x = 1;
2116     if (dim_y == 0)
2117       dim_y = 1;
2118     if (dim_z == 0)
2119       dim_z = 1;
2120
2121     alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
2122
2123     LLDB_LOGF(log, "%s - inferred size of struct allocation %" PRIu32 ".",
2124               __FUNCTION__, *alloc->size.get());
2125     return true;
2126   }
2127
2128   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2129   char expr_buf[jit_max_expr_size];
2130
2131   // Calculate last element
2132   dim_x = dim_x == 0 ? 0 : dim_x - 1;
2133   dim_y = dim_y == 0 ? 0 : dim_y - 1;
2134   dim_z = dim_z == 0 ? 0 : dim_z - 1;
2135
2136   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2137                          *alloc->address.get(), dim_x, dim_y, dim_z);
2138   if (written < 0) {
2139     LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
2140     return false;
2141   } else if (written >= jit_max_expr_size) {
2142     LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
2143     return false;
2144   }
2145
2146   uint64_t result = 0;
2147   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2148     return false;
2149
2150   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2151   // Find pointer to last element and add on size of an element
2152   alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
2153                 *alloc->element.datum_size.get();
2154
2155   return true;
2156 }
2157
2158 // JITs the RS runtime for information about the stride between rows in the
2159 // allocation. This is done to detect padding, since allocated memory is
2160 // 16-byte aligned. Returns true on success, false otherwise
2161 bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
2162                                               StackFrame *frame_ptr) {
2163   Log *log = GetLog(LLDBLog::Language);
2164
2165   if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
2166     LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
2167     return false;
2168   }
2169
2170   const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2171   char expr_buf[jit_max_expr_size];
2172
2173   int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2174                          *alloc->address.get(), 0, 1, 0);
2175   if (written < 0) {
2176     LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
2177     return false;
2178   } else if (written >= jit_max_expr_size) {
2179     LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
2180     return false;
2181   }
2182
2183   uint64_t result = 0;
2184   if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2185     return false;
2186
2187   addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2188   alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
2189
2190   return true;
2191 }
2192
2193 // JIT all the current runtime info regarding an allocation
2194 bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2195                                             StackFrame *frame_ptr) {
2196   // GetOffsetPointer()
2197   if (!JITDataPointer(alloc, frame_ptr))
2198     return false;
2199
2200   // rsaAllocationGetType()
2201   if (!JITTypePointer(alloc, frame_ptr))
2202     return false;
2203
2204   // rsaTypeGetNativeData()
2205   if (!JITTypePacked(alloc, frame_ptr))
2206     return false;
2207
2208   // rsaElementGetNativeData()
2209   if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
2210     return false;
2211
2212   // Sets the datum_size member in Element
2213   SetElementSize(alloc->element);
2214
2215   // Use GetOffsetPointer() to infer size of the allocation
2216   return JITAllocationSize(alloc, frame_ptr);
2217 }
2218
2219 // Function attempts to set the type_name member of the parameterised Element
2220 // object. This string should be the name of the struct type the Element
2221 // represents. We need this string for pretty printing the Element to users.
2222 void RenderScriptRuntime::FindStructTypeName(Element &elem,
2223                                              StackFrame *frame_ptr) {
2224   Log *log = GetLog(LLDBLog::Language);
2225
2226   if (!elem.type_name.IsEmpty()) // Name already set
2227     return;
2228   else
2229     elem.type_name = Element::GetFallbackStructName(); // Default type name if
2230                                                        // we don't succeed
2231
2232   // Find all the global variables from the script rs modules
2233   VariableList var_list;
2234   for (auto module_sp : m_rsmodules)
2235     module_sp->m_module->FindGlobalVariables(
2236         RegularExpression(llvm::StringRef(".")), UINT32_MAX, var_list);
2237
2238   // Iterate over all the global variables looking for one with a matching type
2239   // to the Element. We make the assumption a match exists since there needs to
2240   // be a global variable to reflect the struct type back into java host code.
2241   for (const VariableSP &var_sp : var_list) {
2242     if (!var_sp)
2243       continue;
2244
2245     ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
2246     if (!valobj_sp)
2247       continue;
2248
2249     // Find the number of variable fields.
2250     // If it has no fields, or more fields than our Element, then it can't be
2251     // the struct we're looking for. Don't check for equality since RS can add
2252     // extra struct members for padding.
2253     size_t num_children = valobj_sp->GetNumChildren();
2254     if (num_children > elem.children.size() || num_children == 0)
2255       continue;
2256
2257     // Iterate over children looking for members with matching field names. If
2258     // all the field names match, this is likely the struct we want.
2259     //   TODO: This could be made more robust by also checking children data
2260     //   sizes, or array size
2261     bool found = true;
2262     for (size_t i = 0; i < num_children; ++i) {
2263       ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
2264       if (!child || (child->GetName() != elem.children[i].type_name)) {
2265         found = false;
2266         break;
2267       }
2268     }
2269
2270     // RS can add extra struct members for padding in the format
2271     // '#rs_padding_[0-9]+'
2272     if (found && num_children < elem.children.size()) {
2273       const uint32_t size_diff = elem.children.size() - num_children;
2274       LLDB_LOGF(log, "%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2275                 size_diff);
2276
2277       for (uint32_t i = 0; i < size_diff; ++i) {
2278         ConstString name = elem.children[num_children + i].type_name;
2279         if (strcmp(name.AsCString(), "#rs_padding") < 0)
2280           found = false;
2281       }
2282     }
2283
2284     // We've found a global variable with matching type
2285     if (found) {
2286       // Dereference since our Element type isn't a pointer.
2287       if (valobj_sp->IsPointerType()) {
2288         Status err;
2289         ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
2290         if (!err.Fail())
2291           valobj_sp = deref_valobj;
2292       }
2293
2294       // Save name of variable in Element.
2295       elem.type_name = valobj_sp->GetTypeName();
2296       LLDB_LOGF(log, "%s - element name set to %s", __FUNCTION__,
2297                 elem.type_name.AsCString());
2298
2299       return;
2300     }
2301   }
2302 }
2303
2304 // Function sets the datum_size member of Element. Representing the size of a
2305 // single instance including padding. Assumes the relevant allocation
2306 // information has already been jitted.
2307 void RenderScriptRuntime::SetElementSize(Element &elem) {
2308   Log *log = GetLog(LLDBLog::Language);
2309   const Element::DataType type = *elem.type.get();
2310   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2311          "Invalid allocation type");
2312
2313   const uint32_t vec_size = *elem.type_vec_size.get();
2314   uint32_t data_size = 0;
2315   uint32_t padding = 0;
2316
2317   // Element is of a struct type, calculate size recursively.
2318   if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2319     for (Element &child : elem.children) {
2320       SetElementSize(child);
2321       const uint32_t array_size =
2322           child.array_size.isValid() ? *child.array_size.get() : 1;
2323       data_size += *child.datum_size.get() * array_size;
2324     }
2325   }
2326   // These have been packed already
2327   else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2328            type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2329            type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
2330     data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2331   } else if (type < Element::RS_TYPE_ELEMENT) {
2332     data_size =
2333         vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
2334     if (vec_size == 3)
2335       padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2336   } else
2337     data_size =
2338         GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
2339
2340   elem.padding = padding;
2341   elem.datum_size = data_size + padding;
2342   LLDB_LOGF(log, "%s - element size set to %" PRIu32, __FUNCTION__,
2343             data_size + padding);
2344 }
2345
2346 // Given an allocation, this function copies the allocation contents from
2347 // device into a buffer on the heap. Returning a shared pointer to the buffer
2348 // containing the data.
2349 std::shared_ptr<uint8_t>
2350 RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2351                                        StackFrame *frame_ptr) {
2352   Log *log = GetLog(LLDBLog::Language);
2353
2354   // JIT all the allocation details
2355   if (alloc->ShouldRefresh()) {
2356     LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info",
2357               __FUNCTION__);
2358
2359     if (!RefreshAllocation(alloc, frame_ptr)) {
2360       LLDB_LOGF(log, "%s - couldn't JIT allocation details", __FUNCTION__);
2361       return nullptr;
2362     }
2363   }
2364
2365   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2366          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2367          "Allocation information not available");
2368
2369   // Allocate a buffer to copy data into
2370   const uint32_t size = *alloc->size.get();
2371   std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2372   if (!buffer) {
2373     LLDB_LOGF(log, "%s - couldn't allocate a %" PRIu32 " byte buffer",
2374               __FUNCTION__, size);
2375     return nullptr;
2376   }
2377
2378   // Read the inferior memory
2379   Status err;
2380   lldb::addr_t data_ptr = *alloc->data_ptr.get();
2381   GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
2382   if (err.Fail()) {
2383     LLDB_LOGF(log,
2384               "%s - '%s' Couldn't read %" PRIu32
2385               " bytes of allocation data from 0x%" PRIx64,
2386               __FUNCTION__, err.AsCString(), size, data_ptr);
2387     return nullptr;
2388   }
2389
2390   return buffer;
2391 }
2392
2393 // Function copies data from a binary file into an allocation. There is a
2394 // header at the start of the file, FileHeader, before the data content itself.
2395 // Information from this header is used to display warnings to the user about
2396 // incompatibilities
2397 bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
2398                                          const char *path,
2399                                          StackFrame *frame_ptr) {
2400   Log *log = GetLog(LLDBLog::Language);
2401
2402   // Find allocation with the given id
2403   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2404   if (!alloc)
2405     return false;
2406
2407   LLDB_LOGF(log, "%s - found allocation 0x%" PRIx64, __FUNCTION__,
2408             *alloc->address.get());
2409
2410   // JIT all the allocation details
2411   if (alloc->ShouldRefresh()) {
2412     LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info.",
2413               __FUNCTION__);
2414
2415     if (!RefreshAllocation(alloc, frame_ptr)) {
2416       LLDB_LOGF(log, "%s - couldn't JIT allocation details", __FUNCTION__);
2417       return false;
2418     }
2419   }
2420
2421   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2422          alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2423          alloc->element.datum_size.isValid() &&
2424          "Allocation information not available");
2425
2426   // Check we can read from file
2427   FileSpec file(path);
2428   FileSystem::Instance().Resolve(file);
2429   if (!FileSystem::Instance().Exists(file)) {
2430     strm.Printf("Error: File %s does not exist", path);
2431     strm.EOL();
2432     return false;
2433   }
2434
2435   if (!FileSystem::Instance().Readable(file)) {
2436     strm.Printf("Error: File %s does not have readable permissions", path);
2437     strm.EOL();
2438     return false;
2439   }
2440
2441   // Read file into data buffer
2442   auto data_sp = FileSystem::Instance().CreateDataBuffer(file.GetPath());
2443
2444   // Cast start of buffer to FileHeader and use pointer to read metadata
2445   const void *file_buf = data_sp->GetBytes();
2446   if (file_buf == nullptr ||
2447       data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2448                                 sizeof(AllocationDetails::ElementHeader))) {
2449     strm.Printf("Error: File %s does not contain enough data for header", path);
2450     strm.EOL();
2451     return false;
2452   }
2453   const AllocationDetails::FileHeader *file_header =
2454       static_cast<const AllocationDetails::FileHeader *>(file_buf);
2455
2456   // Check file starts with ascii characters "RSAD"
2457   if (memcmp(file_header->ident, "RSAD", 4)) {
2458     strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2459                 "dump. Are you sure this is the correct file?");
2460     strm.EOL();
2461     return false;
2462   }
2463
2464   // Look at the type of the root element in the header
2465   AllocationDetails::ElementHeader root_el_hdr;
2466   memcpy(&root_el_hdr,
2467          static_cast<const uint8_t *>(file_buf) +
2468              sizeof(AllocationDetails::FileHeader),
2469          sizeof(AllocationDetails::ElementHeader));
2470
2471   LLDB_LOGF(log, "%s - header type %" PRIu32 ", element size %" PRIu32,
2472             __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
2473
2474   // Check if the target allocation and file both have the same number of bytes
2475   // for an Element
2476   if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2477     strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2478                 " bytes, allocation %" PRIu32 " bytes",
2479                 root_el_hdr.element_size, *alloc->element.datum_size.get());
2480     strm.EOL();
2481   }
2482
2483   // Check if the target allocation and file both have the same type
2484   const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
2485   const uint32_t file_type = root_el_hdr.type;
2486
2487   if (file_type > Element::RS_TYPE_FONT) {
2488     strm.Printf("Warning: File has unknown allocation type");
2489     strm.EOL();
2490   } else if (alloc_type != file_type) {
2491     // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2492     // array
2493     uint32_t target_type_name_idx = alloc_type;
2494     uint32_t head_type_name_idx = file_type;
2495     if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2496         alloc_type <= Element::RS_TYPE_FONT)
2497       target_type_name_idx = static_cast<Element::DataType>(
2498           (alloc_type - Element::RS_TYPE_ELEMENT) +
2499           Element::RS_TYPE_MATRIX_2X2 + 1);
2500
2501     if (file_type >= Element::RS_TYPE_ELEMENT &&
2502         file_type <= Element::RS_TYPE_FONT)
2503       head_type_name_idx = static_cast<Element::DataType>(
2504           (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2505           1);
2506
2507     const char *head_type_name =
2508         AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
2509     const char *target_type_name =
2510         AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
2511
2512     strm.Printf(
2513         "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
2514         head_type_name, target_type_name);
2515     strm.EOL();
2516   }
2517
2518   // Advance buffer past header
2519   file_buf = static_cast<const uint8_t *>(file_buf) + file_header->hdr_size;
2520
2521   // Calculate size of allocation data in file
2522   size_t size = data_sp->GetByteSize() - file_header->hdr_size;
2523
2524   // Check if the target allocation and file both have the same total data
2525   // size.
2526   const uint32_t alloc_size = *alloc->size.get();
2527   if (alloc_size != size) {
2528     strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2529                 " bytes, allocation 0x%" PRIx32 " bytes",
2530                 (uint64_t)size, alloc_size);
2531     strm.EOL();
2532     // Set length to copy to minimum
2533     size = alloc_size < size ? alloc_size : size;
2534   }
2535
2536   // Copy file data from our buffer into the target allocation.
2537   lldb::addr_t alloc_data = *alloc->data_ptr.get();
2538   Status err;
2539   size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
2540   if (!err.Success() || written != size) {
2541     strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
2542     strm.EOL();
2543     return false;
2544   }
2545
2546   strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2547               alloc->id);
2548   strm.EOL();
2549
2550   return true;
2551 }
2552
2553 // Function takes as parameters a byte buffer, which will eventually be written
2554 // to file as the element header, an offset into that buffer, and an Element
2555 // that will be saved into the buffer at the parametrised offset. Return value
2556 // is the new offset after writing the element into the buffer. Elements are
2557 // saved to the file as the ElementHeader struct followed by offsets to the
2558 // structs of all the element's children.
2559 size_t RenderScriptRuntime::PopulateElementHeaders(
2560     const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2561     const Element &elem) {
2562   // File struct for an element header with all the relevant details copied
2563   // from elem. We assume members are valid already.
2564   AllocationDetails::ElementHeader elem_header;
2565   elem_header.type = *elem.type.get();
2566   elem_header.kind = *elem.type_kind.get();
2567   elem_header.element_size = *elem.datum_size.get();
2568   elem_header.vector_size = *elem.type_vec_size.get();
2569   elem_header.array_size =
2570       elem.array_size.isValid() ? *elem.array_size.get() : 0;
2571   const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
2572
2573   // Copy struct into buffer and advance offset We assume that header_buffer
2574   // has been checked for nullptr before this method is called
2575   memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
2576   offset += elem_header_size;
2577
2578   // Starting offset of child ElementHeader struct
2579   size_t child_offset =
2580       offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2581   for (const RenderScriptRuntime::Element &child : elem.children) {
2582     // Recursively populate the buffer with the element header structs of
2583     // children. Then save the offsets where they were set after the parent
2584     // element header.
2585     memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
2586     offset += sizeof(uint32_t);
2587
2588     child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
2589   }
2590
2591   // Zero indicates no more children
2592   memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
2593
2594   return child_offset;
2595 }
2596
2597 // Given an Element object this function returns the total size needed in the
2598 // file header to store the element's details. Taking into account the size of
2599 // the element header struct, plus the offsets to all the element's children.
2600 // Function is recursive so that the size of all ancestors is taken into
2601 // account.
2602 size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
2603   // Offsets to children plus zero terminator
2604   size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
2605   // Size of header struct with type details
2606   size += sizeof(AllocationDetails::ElementHeader);
2607
2608   // Calculate recursively for all descendants
2609   for (const Element &child : elem.children)
2610     size += CalculateElementHeaderSize(child);
2611
2612   return size;
2613 }
2614
2615 // Function copies allocation contents into a binary file. This file can then
2616 // be loaded later into a different allocation. There is a header, FileHeader,
2617 // before the allocation data containing meta-data.
2618 bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
2619                                          const char *path,
2620                                          StackFrame *frame_ptr) {
2621   Log *log = GetLog(LLDBLog::Language);
2622
2623   // Find allocation with the given id
2624   AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2625   if (!alloc)
2626     return false;
2627
2628   LLDB_LOGF(log, "%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2629             *alloc->address.get());
2630
2631   // JIT all the allocation details
2632   if (alloc->ShouldRefresh()) {
2633     LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info.",
2634               __FUNCTION__);
2635
2636     if (!RefreshAllocation(alloc, frame_ptr)) {
2637       LLDB_LOGF(log, "%s - couldn't JIT allocation details.", __FUNCTION__);
2638       return false;
2639     }
2640   }
2641
2642   assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2643          alloc->element.type_vec_size.isValid() &&
2644          alloc->element.datum_size.get() &&
2645          alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2646          "Allocation information not available");
2647
2648   // Check we can create writable file
2649   FileSpec file_spec(path);
2650   FileSystem::Instance().Resolve(file_spec);
2651   auto file = FileSystem::Instance().Open(
2652       file_spec, File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate |
2653                      File::eOpenOptionTruncate);
2654
2655   if (!file) {
2656     std::string error = llvm::toString(file.takeError());
2657     strm.Printf("Error: Failed to open '%s' for writing: %s", path,
2658                 error.c_str());
2659     strm.EOL();
2660     return false;
2661   }
2662
2663   // Read allocation into buffer of heap memory
2664   const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2665   if (!buffer) {
2666     strm.Printf("Error: Couldn't read allocation data into buffer");
2667     strm.EOL();
2668     return false;
2669   }
2670
2671   // Create the file header
2672   AllocationDetails::FileHeader head;
2673   memcpy(head.ident, "RSAD", 4);
2674   head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
2675   head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
2676   head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
2677
2678   const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2679   assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2680              UINT16_MAX &&
2681          "Element header too large");
2682   head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2683                                         element_header_size);
2684
2685   // Write the file header
2686   size_t num_bytes = sizeof(AllocationDetails::FileHeader);
2687   LLDB_LOGF(log, "%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2688             (uint64_t)num_bytes);
2689
2690   Status err = file.get()->Write(&head, num_bytes);
2691   if (!err.Success()) {
2692     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2693     strm.EOL();
2694     return false;
2695   }
2696
2697   // Create the headers describing the element type of the allocation.
2698   std::shared_ptr<uint8_t> element_header_buffer(
2699       new uint8_t[element_header_size]);
2700   if (element_header_buffer == nullptr) {
2701     strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2702                 " bytes on the heap",
2703                 (uint64_t)element_header_size);
2704     strm.EOL();
2705     return false;
2706   }
2707
2708   PopulateElementHeaders(element_header_buffer, 0, alloc->element);
2709
2710   // Write headers for allocation element type to file
2711   num_bytes = element_header_size;
2712   LLDB_LOGF(log, "%s - writing element headers, 0x%" PRIx64 " bytes.",
2713             __FUNCTION__, (uint64_t)num_bytes);
2714
2715   err = file.get()->Write(element_header_buffer.get(), num_bytes);
2716   if (!err.Success()) {
2717     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2718     strm.EOL();
2719     return false;
2720   }
2721
2722   // Write allocation data to file
2723   num_bytes = static_cast<size_t>(*alloc->size.get());
2724   LLDB_LOGF(log, "%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2725             (uint64_t)num_bytes);
2726
2727   err = file.get()->Write(buffer.get(), num_bytes);
2728   if (!err.Success()) {
2729     strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2730     strm.EOL();
2731     return false;
2732   }
2733
2734   strm.Printf("Allocation written to file '%s'", path);
2735   strm.EOL();
2736   return true;
2737 }
2738
2739 bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
2740   Log *log = GetLog(LLDBLog::Language);
2741
2742   if (module_sp) {
2743     for (const auto &rs_module : m_rsmodules) {
2744       if (rs_module->m_module == module_sp) {
2745         // Check if the user has enabled automatically breaking on all RS
2746         // kernels.
2747         if (m_breakAllKernels)
2748           BreakOnModuleKernels(rs_module);
2749
2750         return false;
2751       }
2752     }
2753     bool module_loaded = false;
2754     switch (GetModuleKind(module_sp)) {
2755     case eModuleKindKernelObj: {
2756       RSModuleDescriptorSP module_desc;
2757       module_desc = std::make_shared<RSModuleDescriptor>(module_sp);
2758       if (module_desc->ParseRSInfo()) {
2759         m_rsmodules.push_back(module_desc);
2760         module_desc->WarnIfVersionMismatch(GetProcess()
2761                                                ->GetTarget()
2762                                                .GetDebugger()
2763                                                .GetAsyncOutputStream()
2764                                                .get());
2765         module_loaded = true;
2766       }
2767       if (module_loaded) {
2768         FixupScriptDetails(module_desc);
2769       }
2770       break;
2771     }
2772     case eModuleKindDriver: {
2773       if (!m_libRSDriver) {
2774         m_libRSDriver = module_sp;
2775         LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
2776       }
2777       break;
2778     }
2779     case eModuleKindImpl: {
2780       if (!m_libRSCpuRef) {
2781         m_libRSCpuRef = module_sp;
2782         LoadRuntimeHooks(m_libRSCpuRef, RenderScriptRuntime::eModuleKindImpl);
2783       }
2784       break;
2785     }
2786     case eModuleKindLibRS: {
2787       if (!m_libRS) {
2788         m_libRS = module_sp;
2789         static ConstString gDbgPresentStr("gDebuggerPresent");
2790         const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2791             gDbgPresentStr, eSymbolTypeData);
2792         if (debug_present) {
2793           Status err;
2794           uint32_t flag = 0x00000001U;
2795           Target &target = GetProcess()->GetTarget();
2796           addr_t addr = debug_present->GetLoadAddress(&target);
2797           GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
2798           if (err.Success()) {
2799             LLDB_LOGF(log, "%s - debugger present flag set on debugee.",
2800                       __FUNCTION__);
2801
2802             m_debuggerPresentFlagged = true;
2803           } else if (log) {
2804             LLDB_LOGF(log, "%s - error writing debugger present flags '%s' ",
2805                       __FUNCTION__, err.AsCString());
2806           }
2807         } else if (log) {
2808           LLDB_LOGF(
2809               log,
2810               "%s - error writing debugger present flags - symbol not found",
2811               __FUNCTION__);
2812         }
2813       }
2814       break;
2815     }
2816     default:
2817       break;
2818     }
2819     if (module_loaded)
2820       Update();
2821     return module_loaded;
2822   }
2823   return false;
2824 }
2825
2826 void RenderScriptRuntime::Update() {
2827   if (m_rsmodules.size() > 0) {
2828     if (!m_initiated) {
2829       Initiate();
2830     }
2831   }
2832 }
2833
2834 void RSModuleDescriptor::WarnIfVersionMismatch(lldb_private::Stream *s) const {
2835   if (!s)
2836     return;
2837
2838   if (m_slang_version.empty() || m_bcc_version.empty()) {
2839     s->PutCString("WARNING: Unknown bcc or slang (llvm-rs-cc) version; debug "
2840                   "experience may be unreliable");
2841     s->EOL();
2842   } else if (m_slang_version != m_bcc_version) {
2843     s->Printf("WARNING: The debug info emitted by the slang frontend "
2844               "(llvm-rs-cc) used to build this module (%s) does not match the "
2845               "version of bcc used to generate the debug information (%s). "
2846               "This is an unsupported configuration and may result in a poor "
2847               "debugging experience; proceed with caution",
2848               m_slang_version.c_str(), m_bcc_version.c_str());
2849     s->EOL();
2850   }
2851 }
2852
2853 bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
2854                                           size_t n_lines) {
2855   // Skip the pragma prototype line
2856   ++lines;
2857   for (; n_lines--; ++lines) {
2858     const auto kv_pair = lines->split(" - ");
2859     m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
2860   }
2861   return true;
2862 }
2863
2864 bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
2865                                                 size_t n_lines) {
2866   // The list of reduction kernels in the `.rs.info` symbol is of the form
2867   // "signature - accumulatordatasize - reduction_name - initializer_name -
2868   // accumulator_name - combiner_name - outconverter_name - halter_name" Where
2869   // a function is not explicitly named by the user, or is not generated by the
2870   // compiler, it is named "." so the dash separated list should always be 8
2871   // items long
2872   Log *log = GetLog(LLDBLog::Language);
2873   // Skip the exportReduceCount line
2874   ++lines;
2875   for (; n_lines--; ++lines) {
2876     llvm::SmallVector<llvm::StringRef, 8> spec;
2877     lines->split(spec, " - ");
2878     if (spec.size() != 8) {
2879       if (spec.size() < 8) {
2880         if (log)
2881           log->Error("Error parsing RenderScript reduction spec. wrong number "
2882                      "of fields");
2883         return false;
2884       } else if (log)
2885         log->Warning("Extraneous members in reduction spec: '%s'",
2886                      lines->str().c_str());
2887     }
2888
2889     const auto sig_s = spec[0];
2890     uint32_t sig;
2891     if (sig_s.getAsInteger(10, sig)) {
2892       if (log)
2893         log->Error("Error parsing Renderscript reduction spec: invalid kernel "
2894                    "signature: '%s'",
2895                    sig_s.str().c_str());
2896       return false;
2897     }
2898
2899     const auto accum_data_size_s = spec[1];
2900     uint32_t accum_data_size;
2901     if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
2902       if (log)
2903         log->Error("Error parsing Renderscript reduction spec: invalid "
2904                    "accumulator data size %s",
2905                    accum_data_size_s.str().c_str());
2906       return false;
2907     }
2908
2909     LLDB_LOGF(log, "Found RenderScript reduction '%s'", spec[2].str().c_str());
2910
2911     m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
2912                                                  spec[2], spec[3], spec[4],
2913                                                  spec[5], spec[6], spec[7]));
2914   }
2915   return true;
2916 }
2917
2918 bool RSModuleDescriptor::ParseVersionInfo(llvm::StringRef *lines,
2919                                           size_t n_lines) {
2920   // Skip the versionInfo line
2921   ++lines;
2922   for (; n_lines--; ++lines) {
2923     // We're only interested in bcc and slang versions, and ignore all other
2924     // versionInfo lines
2925     const auto kv_pair = lines->split(" - ");
2926     if (kv_pair.first == "slang")
2927       m_slang_version = kv_pair.second.str();
2928     else if (kv_pair.first == "bcc")
2929       m_bcc_version = kv_pair.second.str();
2930   }
2931   return true;
2932 }
2933
2934 bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
2935                                                  size_t n_lines) {
2936   // Skip the exportForeachCount line
2937   ++lines;
2938   for (; n_lines--; ++lines) {
2939     uint32_t slot;
2940     // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
2941     // pair per line
2942     const auto kv_pair = lines->split(" - ");
2943     if (kv_pair.first.getAsInteger(10, slot))
2944       return false;
2945     m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
2946   }
2947   return true;
2948 }
2949
2950 bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
2951                                              size_t n_lines) {
2952   // Skip the ExportVarCount line
2953   ++lines;
2954   for (; n_lines--; ++lines)
2955     m_globals.push_back(RSGlobalDescriptor(this, *lines));
2956   return true;
2957 }
2958
2959 // The .rs.info symbol in renderscript modules contains a string which needs to
2960 // be parsed. The string is basic and is parsed on a line by line basis.
2961 bool RSModuleDescriptor::ParseRSInfo() {
2962   assert(m_module);
2963   Log *log = GetLog(LLDBLog::Language);
2964   const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
2965       ConstString(".rs.info"), eSymbolTypeData);
2966   if (!info_sym)
2967     return false;
2968
2969   const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
2970   if (addr == LLDB_INVALID_ADDRESS)
2971     return false;
2972
2973   const addr_t size = info_sym->GetByteSize();
2974   const FileSpec fs = m_module->GetFileSpec();
2975
2976   auto buffer =
2977       FileSystem::Instance().CreateDataBuffer(fs.GetPath(), size, addr);
2978   if (!buffer)
2979     return false;
2980
2981   // split rs.info. contents into lines
2982   llvm::SmallVector<llvm::StringRef, 128> info_lines;
2983   {
2984     const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
2985     raw_rs_info.split(info_lines, '\n');
2986     LLDB_LOGF(log, "'.rs.info symbol for '%s':\n%s",
2987               m_module->GetFileSpec().GetCString(), raw_rs_info.str().c_str());
2988   }
2989
2990   enum {
2991     eExportVar,
2992     eExportForEach,
2993     eExportReduce,
2994     ePragma,
2995     eBuildChecksum,
2996     eObjectSlot,
2997     eVersionInfo,
2998   };
2999
3000   const auto rs_info_handler = [](llvm::StringRef name) -> int {
3001     return llvm::StringSwitch<int>(name)
3002         // The number of visible global variables in the script
3003         .Case("exportVarCount", eExportVar)
3004         // The number of RenderScrip `forEach` kernels __attribute__((kernel))
3005         .Case("exportForEachCount", eExportForEach)
3006         // The number of generalreductions: This marked in the script by
3007         // `#pragma reduce()`
3008         .Case("exportReduceCount", eExportReduce)
3009         // Total count of all RenderScript specific `#pragmas` used in the
3010         // script
3011         .Case("pragmaCount", ePragma)
3012         .Case("objectSlotCount", eObjectSlot)
3013         .Case("versionInfo", eVersionInfo)
3014         .Default(-1);
3015   };
3016
3017   // parse all text lines of .rs.info
3018   for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
3019     const auto kv_pair = line->split(": ");
3020     const auto key = kv_pair.first;
3021     const auto val = kv_pair.second.trim();
3022
3023     const auto handler = rs_info_handler(key);
3024     if (handler == -1)
3025       continue;
3026     // getAsInteger returns `true` on an error condition - we're only
3027     // interested in numeric fields at the moment
3028     uint64_t n_lines;
3029     if (val.getAsInteger(10, n_lines)) {
3030       LLDB_LOGV(log, "Failed to parse non-numeric '.rs.info' section {0}",
3031                 line->str());
3032       continue;
3033     }
3034     if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
3035       return false;
3036
3037     bool success = false;
3038     switch (handler) {
3039     case eExportVar:
3040       success = ParseExportVarCount(line, n_lines);
3041       break;
3042     case eExportForEach:
3043       success = ParseExportForeachCount(line, n_lines);
3044       break;
3045     case eExportReduce:
3046       success = ParseExportReduceCount(line, n_lines);
3047       break;
3048     case ePragma:
3049       success = ParsePragmaCount(line, n_lines);
3050       break;
3051     case eVersionInfo:
3052       success = ParseVersionInfo(line, n_lines);
3053       break;
3054     default: {
3055       LLDB_LOGF(log, "%s - skipping .rs.info field '%s'", __FUNCTION__,
3056                 line->str().c_str());
3057       continue;
3058     }
3059     }
3060     if (!success)
3061       return false;
3062     line += n_lines;
3063   }
3064   return info_lines.size() > 0;
3065 }
3066
3067 void RenderScriptRuntime::DumpStatus(Stream &strm) const {
3068   if (m_libRS) {
3069     strm.Printf("Runtime Library discovered.");
3070     strm.EOL();
3071   }
3072   if (m_libRSDriver) {
3073     strm.Printf("Runtime Driver discovered.");
3074     strm.EOL();
3075   }
3076   if (m_libRSCpuRef) {
3077     strm.Printf("CPU Reference Implementation discovered.");
3078     strm.EOL();
3079   }
3080
3081   if (m_runtimeHooks.size()) {
3082     strm.Printf("Runtime functions hooked:");
3083     strm.EOL();
3084     for (auto b : m_runtimeHooks) {
3085       strm.Indent(b.second->defn->name);
3086       strm.EOL();
3087     }
3088   } else {
3089     strm.Printf("Runtime is not hooked.");
3090     strm.EOL();
3091   }
3092 }
3093
3094 void RenderScriptRuntime::DumpContexts(Stream &strm) const {
3095   strm.Printf("Inferred RenderScript Contexts:");
3096   strm.EOL();
3097   strm.IndentMore();
3098
3099   std::map<addr_t, uint64_t> contextReferences;
3100
3101   // Iterate over all of the currently discovered scripts. Note: We cant push
3102   // or pop from m_scripts inside this loop or it may invalidate script.
3103   for (const auto &script : m_scripts) {
3104     if (!script->context.isValid())
3105       continue;
3106     lldb::addr_t context = *script->context;
3107
3108     if (contextReferences.find(context) != contextReferences.end()) {
3109       contextReferences[context]++;
3110     } else {
3111       contextReferences[context] = 1;
3112     }
3113   }
3114
3115   for (const auto &cRef : contextReferences) {
3116     strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
3117                 cRef.first, cRef.second);
3118     strm.EOL();
3119   }
3120   strm.IndentLess();
3121 }
3122
3123 void RenderScriptRuntime::DumpKernels(Stream &strm) const {
3124   strm.Printf("RenderScript Kernels:");
3125   strm.EOL();
3126   strm.IndentMore();
3127   for (const auto &module : m_rsmodules) {
3128     strm.Printf("Resource '%s':", module->m_resname.c_str());
3129     strm.EOL();
3130     for (const auto &kernel : module->m_kernels) {
3131       strm.Indent(kernel.m_name.GetStringRef());
3132       strm.EOL();
3133     }
3134   }
3135   strm.IndentLess();
3136 }
3137
3138 RenderScriptRuntime::AllocationDetails *
3139 RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
3140   AllocationDetails *alloc = nullptr;
3141
3142   // See if we can find allocation using id as an index;
3143   if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
3144       m_allocations[alloc_id - 1]->id == alloc_id) {
3145     alloc = m_allocations[alloc_id - 1].get();
3146     return alloc;
3147   }
3148
3149   // Fallback to searching
3150   for (const auto &a : m_allocations) {
3151     if (a->id == alloc_id) {
3152       alloc = a.get();
3153       break;
3154     }
3155   }
3156
3157   if (alloc == nullptr) {
3158     strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
3159                 alloc_id);
3160     strm.EOL();
3161   }
3162
3163   return alloc;
3164 }
3165
3166 // Prints the contents of an allocation to the output stream, which may be a
3167 // file
3168 bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
3169                                          const uint32_t id) {
3170   Log *log = GetLog(LLDBLog::Language);
3171
3172   // Check we can find the desired allocation
3173   AllocationDetails *alloc = FindAllocByID(strm, id);
3174   if (!alloc)
3175     return false; // FindAllocByID() will print error message for us here
3176
3177   LLDB_LOGF(log, "%s - found allocation 0x%" PRIx64, __FUNCTION__,
3178             *alloc->address.get());
3179
3180   // Check we have information about the allocation, if not calculate it
3181   if (alloc->ShouldRefresh()) {
3182     LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info.",
3183               __FUNCTION__);
3184
3185     // JIT all the allocation information
3186     if (!RefreshAllocation(alloc, frame_ptr)) {
3187       strm.Printf("Error: Couldn't JIT allocation details");
3188       strm.EOL();
3189       return false;
3190     }
3191   }
3192
3193   // Establish format and size of each data element
3194   const uint32_t vec_size = *alloc->element.type_vec_size.get();
3195   const Element::DataType type = *alloc->element.type.get();
3196
3197   assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
3198          "Invalid allocation type");
3199
3200   lldb::Format format;
3201   if (type >= Element::RS_TYPE_ELEMENT)
3202     format = eFormatHex;
3203   else
3204     format = vec_size == 1
3205                  ? static_cast<lldb::Format>(
3206                        AllocationDetails::RSTypeToFormat[type][eFormatSingle])
3207                  : static_cast<lldb::Format>(
3208                        AllocationDetails::RSTypeToFormat[type][eFormatVector]);
3209
3210   const uint32_t data_size = *alloc->element.datum_size.get();
3211
3212   LLDB_LOGF(log, "%s - element size %" PRIu32 " bytes, including padding",
3213             __FUNCTION__, data_size);
3214
3215   // Allocate a buffer to copy data into
3216   std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3217   if (!buffer) {
3218     strm.Printf("Error: Couldn't read allocation data");
3219     strm.EOL();
3220     return false;
3221   }
3222
3223   // Calculate stride between rows as there may be padding at end of rows since
3224   // allocated memory is 16-byte aligned
3225   if (!alloc->stride.isValid()) {
3226     if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
3227       alloc->stride = 0;
3228     else if (!JITAllocationStride(alloc, frame_ptr)) {
3229       strm.Printf("Error: Couldn't calculate allocation row stride");
3230       strm.EOL();
3231       return false;
3232     }
3233   }
3234   const uint32_t stride = *alloc->stride.get();
3235   const uint32_t size = *alloc->size.get(); // Size of whole allocation
3236   const uint32_t padding =
3237       alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3238   LLDB_LOGF(log,
3239             "%s - stride %" PRIu32 " bytes, size %" PRIu32
3240             " bytes, padding %" PRIu32,
3241             __FUNCTION__, stride, size, padding);
3242
3243   // Find dimensions used to index loops, so need to be non-zero
3244   uint32_t dim_x = alloc->dimension.get()->dim_1;
3245   dim_x = dim_x == 0 ? 1 : dim_x;
3246
3247   uint32_t dim_y = alloc->dimension.get()->dim_2;
3248   dim_y = dim_y == 0 ? 1 : dim_y;
3249
3250   uint32_t dim_z = alloc->dimension.get()->dim_3;
3251   dim_z = dim_z == 0 ? 1 : dim_z;
3252
3253   // Use data extractor to format output
3254   const uint32_t target_ptr_size =
3255       GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3256   DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
3257                            target_ptr_size);
3258
3259   uint32_t offset = 0;   // Offset in buffer to next element to be printed
3260   uint32_t prev_row = 0; // Offset to the start of the previous row
3261
3262   // Iterate over allocation dimensions, printing results to user
3263   strm.Printf("Data (X, Y, Z):");
3264   for (uint32_t z = 0; z < dim_z; ++z) {
3265     for (uint32_t y = 0; y < dim_y; ++y) {
3266       // Use stride to index start of next row.
3267       if (!(y == 0 && z == 0))
3268         offset = prev_row + stride;
3269       prev_row = offset;
3270
3271       // Print each element in the row individually
3272       for (uint32_t x = 0; x < dim_x; ++x) {
3273         strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3274         if ((type == Element::RS_TYPE_NONE) &&
3275             (alloc->element.children.size() > 0) &&
3276             (alloc->element.type_name != Element::GetFallbackStructName())) {
3277           // Here we are dumping an Element of struct type. This is done using
3278           // expression evaluation with the name of the struct type and pointer
3279           // to element. Don't print the name of the resulting expression,
3280           // since this will be '$[0-9]+'
3281           DumpValueObjectOptions expr_options;
3282           expr_options.SetHideName(true);
3283
3284           // Setup expression as dereferencing a pointer cast to element
3285           // address.
3286           char expr_char_buffer[jit_max_expr_size];
3287           int written =
3288               snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3289                        alloc->element.type_name.AsCString(),
3290                        *alloc->data_ptr.get() + offset);
3291
3292           if (written < 0 || written >= jit_max_expr_size) {
3293             LLDB_LOGF(log, "%s - error in snprintf().", __FUNCTION__);
3294             continue;
3295           }
3296
3297           // Evaluate expression
3298           ValueObjectSP expr_result;
3299           GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3300                                                        frame_ptr, expr_result);
3301
3302           // Print the results to our stream.
3303           expr_result->Dump(strm, expr_options);
3304         } else {
3305           DumpDataExtractor(alloc_data, &strm, offset, format,
3306                             data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0,
3307                             0);
3308         }
3309         offset += data_size;
3310       }
3311     }
3312   }
3313   strm.EOL();
3314
3315   return true;
3316 }
3317
3318 // Function recalculates all our cached information about allocations by
3319 // jitting the RS runtime regarding each allocation we know about. Returns true
3320 // if all allocations could be recomputed, false otherwise.
3321 bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3322                                                   StackFrame *frame_ptr) {
3323   bool success = true;
3324   for (auto &alloc : m_allocations) {
3325     // JIT current allocation information
3326     if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3327       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3328                   "\n",
3329                   alloc->id);
3330       success = false;
3331     }
3332   }
3333
3334   if (success)
3335     strm.Printf("All allocations successfully recomputed");
3336   strm.EOL();
3337
3338   return success;
3339 }
3340
3341 // Prints information regarding currently loaded allocations. These details are
3342 // gathered by jitting the runtime, which has as latency. Index parameter
3343 // specifies a single allocation ID to print, or a zero value to print them all
3344 void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3345                                           const uint32_t index) {
3346   strm.Printf("RenderScript Allocations:");
3347   strm.EOL();
3348   strm.IndentMore();
3349
3350   for (auto &alloc : m_allocations) {
3351     // index will only be zero if we want to print all allocations
3352     if (index != 0 && index != alloc->id)
3353       continue;
3354
3355     // JIT current allocation information
3356     if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3357       strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3358                   alloc->id);
3359       strm.EOL();
3360       continue;
3361     }
3362
3363     strm.Printf("%" PRIu32 ":", alloc->id);
3364     strm.EOL();
3365     strm.IndentMore();
3366
3367     strm.Indent("Context: ");
3368     if (!alloc->context.isValid())
3369       strm.Printf("unknown\n");
3370     else
3371       strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
3372
3373     strm.Indent("Address: ");
3374     if (!alloc->address.isValid())
3375       strm.Printf("unknown\n");
3376     else
3377       strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
3378
3379     strm.Indent("Data pointer: ");
3380     if (!alloc->data_ptr.isValid())
3381       strm.Printf("unknown\n");
3382     else
3383       strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
3384
3385     strm.Indent("Dimensions: ");
3386     if (!alloc->dimension.isValid())
3387       strm.Printf("unknown\n");
3388     else
3389       strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3390                   alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3391                   alloc->dimension.get()->dim_3);
3392
3393     strm.Indent("Data Type: ");
3394     if (!alloc->element.type.isValid() ||
3395         !alloc->element.type_vec_size.isValid())
3396       strm.Printf("unknown\n");
3397     else {
3398       const int vector_size = *alloc->element.type_vec_size.get();
3399       Element::DataType type = *alloc->element.type.get();
3400
3401       if (!alloc->element.type_name.IsEmpty())
3402         strm.Printf("%s\n", alloc->element.type_name.AsCString());
3403       else {
3404         // Enum value isn't monotonous, so doesn't always index
3405         // RsDataTypeToString array
3406         if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3407           type =
3408               static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3409                                              Element::RS_TYPE_MATRIX_2X2 + 1);
3410
3411         if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3412                      sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3413             vector_size > 4 || vector_size < 1)
3414           strm.Printf("invalid type\n");
3415         else
3416           strm.Printf(
3417               "%s\n",
3418               AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3419                                                    [vector_size - 1]);
3420       }
3421     }
3422
3423     strm.Indent("Data Kind: ");
3424     if (!alloc->element.type_kind.isValid())
3425       strm.Printf("unknown\n");
3426     else {
3427       const Element::DataKind kind = *alloc->element.type_kind.get();
3428       if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
3429         strm.Printf("invalid kind\n");
3430       else
3431         strm.Printf(
3432             "%s\n",
3433             AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
3434     }
3435
3436     strm.EOL();
3437     strm.IndentLess();
3438   }
3439   strm.IndentLess();
3440 }
3441
3442 // Set breakpoints on every kernel found in RS module
3443 void RenderScriptRuntime::BreakOnModuleKernels(
3444     const RSModuleDescriptorSP rsmodule_sp) {
3445   for (const auto &kernel : rsmodule_sp->m_kernels) {
3446     // Don't set breakpoint on 'root' kernel
3447     if (strcmp(kernel.m_name.AsCString(), "root") == 0)
3448       continue;
3449
3450     CreateKernelBreakpoint(kernel.m_name);
3451   }
3452 }
3453
3454 // Method is internally called by the 'kernel breakpoint all' command to enable
3455 // or disable breaking on all kernels. When do_break is true we want to enable
3456 // this functionality. When do_break is false we want to disable it.
3457 void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3458   Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3459
3460   InitSearchFilter(target);
3461
3462   // Set breakpoints on all the kernels
3463   if (do_break && !m_breakAllKernels) {
3464     m_breakAllKernels = true;
3465
3466     for (const auto &module : m_rsmodules)
3467       BreakOnModuleKernels(module);
3468
3469     LLDB_LOGF(log,
3470               "%s(True) - breakpoints set on all currently loaded kernels.",
3471               __FUNCTION__);
3472   } else if (!do_break &&
3473              m_breakAllKernels) // Breakpoints won't be set on any new kernels.
3474   {
3475     m_breakAllKernels = false;
3476
3477     LLDB_LOGF(log, "%s(False) - breakpoints no longer automatically set.",
3478               __FUNCTION__);
3479   }
3480 }
3481
3482 // Given the name of a kernel this function creates a breakpoint using our own
3483 // breakpoint resolver, and returns the Breakpoint shared pointer.
3484 BreakpointSP
3485 RenderScriptRuntime::CreateKernelBreakpoint(ConstString name) {
3486   Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3487
3488   if (!m_filtersp) {
3489     LLDB_LOGF(log, "%s - error, no breakpoint search filter set.",
3490               __FUNCTION__);
3491     return nullptr;
3492   }
3493
3494   BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3495   Target &target = GetProcess()->GetTarget();
3496   BreakpointSP bp = target.CreateBreakpoint(
3497       m_filtersp, resolver_sp, false, false, false);
3498
3499   // Give RS breakpoints a specific name, so the user can manipulate them as a
3500   // group.
3501   Status err;
3502   target.AddNameToBreakpoint(bp, "RenderScriptKernel", err);
3503   if (err.Fail() && log)
3504     LLDB_LOGF(log, "%s - error setting break name, '%s'.", __FUNCTION__,
3505               err.AsCString());
3506
3507   return bp;
3508 }
3509
3510 BreakpointSP
3511 RenderScriptRuntime::CreateReductionBreakpoint(ConstString name,
3512                                                int kernel_types) {
3513   Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3514
3515   if (!m_filtersp) {
3516     LLDB_LOGF(log, "%s - error, no breakpoint search filter set.",
3517               __FUNCTION__);
3518     return nullptr;
3519   }
3520
3521   BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3522       nullptr, name, &m_rsmodules, kernel_types));
3523   Target &target = GetProcess()->GetTarget();
3524   BreakpointSP bp = target.CreateBreakpoint(
3525       m_filtersp, resolver_sp, false, false, false);
3526
3527   // Give RS breakpoints a specific name, so the user can manipulate them as a
3528   // group.
3529   Status err;
3530   target.AddNameToBreakpoint(bp, "RenderScriptReduction", err);
3531   if (err.Fail() && log)
3532     LLDB_LOGF(log, "%s - error setting break name, '%s'.", __FUNCTION__,
3533               err.AsCString());
3534
3535   return bp;
3536 }
3537
3538 // Given an expression for a variable this function tries to calculate the
3539 // variable's value. If this is possible it returns true and sets the uint64_t
3540 // parameter to the variables unsigned value. Otherwise function returns false.
3541 bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3542                                                 const char *var_name,
3543                                                 uint64_t &val) {
3544   Log *log = GetLog(LLDBLog::Language);
3545   Status err;
3546   VariableSP var_sp;
3547
3548   // Find variable in stack frame
3549   ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3550       var_name, eNoDynamicValues,
3551       StackFrame::eExpressionPathOptionCheckPtrVsMember |
3552           StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3553       var_sp, err));
3554   if (!err.Success()) {
3555     LLDB_LOGF(log, "%s - error, couldn't find '%s' in frame", __FUNCTION__,
3556               var_name);
3557     return false;
3558   }
3559
3560   // Find the uint32_t value for the variable
3561   bool success = false;
3562   val = value_sp->GetValueAsUnsigned(0, &success);
3563   if (!success) {
3564     LLDB_LOGF(log, "%s - error, couldn't parse '%s' as an uint32_t.",
3565               __FUNCTION__, var_name);
3566     return false;
3567   }
3568
3569   return true;
3570 }
3571
3572 // Function attempts to find the current coordinate of a kernel invocation by
3573 // investigating the values of frame variables in the .expand function. These
3574 // coordinates are returned via the coord array reference parameter. Returns
3575 // true if the coordinates could be found, and false otherwise.
3576 bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3577                                               Thread *thread_ptr) {
3578   static const char *const x_expr = "rsIndex";
3579   static const char *const y_expr = "p->current.y";
3580   static const char *const z_expr = "p->current.z";
3581
3582   Log *log = GetLog(LLDBLog::Language);
3583
3584   if (!thread_ptr) {
3585     LLDB_LOGF(log, "%s - Error, No thread pointer", __FUNCTION__);
3586
3587     return false;
3588   }
3589
3590   // Walk the call stack looking for a function whose name has the suffix
3591   // '.expand' and contains the variables we're looking for.
3592   for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
3593     if (!thread_ptr->SetSelectedFrameByIndex(i))
3594       continue;
3595
3596     StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
3597     if (!frame_sp)
3598       continue;
3599
3600     // Find the function name
3601     const SymbolContext sym_ctx =
3602         frame_sp->GetSymbolContext(eSymbolContextFunction);
3603     const ConstString func_name = sym_ctx.GetFunctionName();
3604     if (!func_name)
3605       continue;
3606
3607     LLDB_LOGF(log, "%s - Inspecting function '%s'", __FUNCTION__,
3608               func_name.GetCString());
3609
3610     // Check if function name has .expand suffix
3611     if (!func_name.GetStringRef().endswith(".expand"))
3612       continue;
3613
3614     LLDB_LOGF(log, "%s - Found .expand function '%s'", __FUNCTION__,
3615               func_name.GetCString());
3616
3617     // Get values for variables in .expand frame that tell us the current
3618     // kernel invocation
3619     uint64_t x, y, z;
3620     bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
3621                  GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
3622                  GetFrameVarAsUnsigned(frame_sp, z_expr, z);
3623
3624     if (found) {
3625       // The RenderScript runtime uses uint32_t for these vars. If they're not
3626       // within bounds, our frame parsing is garbage
3627       assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
3628       coord.x = (uint32_t)x;
3629       coord.y = (uint32_t)y;
3630       coord.z = (uint32_t)z;
3631       return true;
3632     }
3633   }
3634   return false;
3635 }
3636
3637 // Callback when a kernel breakpoint hits and we're looking for a specific
3638 // coordinate. Baton parameter contains a pointer to the target coordinate we
3639 // want to break on. Function then checks the .expand frame for the current
3640 // coordinate and breaks to user if it matches. Parameter 'break_id' is the id
3641 // of the Breakpoint which made the callback. Parameter 'break_loc_id' is the
3642 // id for the BreakpointLocation which was hit, a single logical breakpoint can
3643 // have multiple addresses.
3644 bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3645                                               StoppointCallbackContext *ctx,
3646                                               user_id_t break_id,
3647                                               user_id_t break_loc_id) {
3648   Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3649
3650   assert(baton &&
3651          "Error: null baton in conditional kernel breakpoint callback");
3652
3653   // Coordinate we want to stop on
3654   RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3655
3656   LLDB_LOGF(log, "%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__,
3657             break_id, target_coord.x, target_coord.y, target_coord.z);
3658
3659   // Select current thread
3660   ExecutionContext context(ctx->exe_ctx_ref);
3661   Thread *thread_ptr = context.GetThreadPtr();
3662   assert(thread_ptr && "Null thread pointer");
3663
3664   // Find current kernel invocation from .expand frame variables
3665   RSCoordinate current_coord{};
3666   if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3667     LLDB_LOGF(log, "%s - Error, couldn't select .expand stack frame",
3668               __FUNCTION__);
3669     return false;
3670   }
3671
3672   LLDB_LOGF(log, "%s - " FMT_COORD, __FUNCTION__, current_coord.x,
3673             current_coord.y, current_coord.z);
3674
3675   // Check if the current kernel invocation coordinate matches our target
3676   // coordinate
3677   if (target_coord == current_coord) {
3678     LLDB_LOGF(log, "%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
3679               current_coord.y, current_coord.z);
3680
3681     BreakpointSP breakpoint_sp =
3682         context.GetTargetPtr()->GetBreakpointByID(break_id);
3683     assert(breakpoint_sp != nullptr &&
3684            "Error: Couldn't find breakpoint matching break id for callback");
3685     breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3686                                       // should only be hit once.
3687     return true;
3688   }
3689
3690   // No match on coordinate
3691   return false;
3692 }
3693
3694 void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
3695                                          const RSCoordinate &coord) {
3696   messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
3697                   coord.x, coord.y, coord.z);
3698   messages.EOL();
3699
3700   // Allocate memory for the baton, and copy over coordinate
3701   RSCoordinate *baton = new RSCoordinate(coord);
3702
3703   // Create a callback that will be invoked every time the breakpoint is hit.
3704   // The baton object passed to the handler is the target coordinate we want to
3705   // break on.
3706   bp->SetCallback(KernelBreakpointHit, baton, true);
3707
3708   // Store a shared pointer to the baton, so the memory will eventually be
3709   // cleaned up after destruction
3710   m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
3711 }
3712
3713 // Tries to set a breakpoint on the start of a kernel, resolved using the
3714 // kernel name. Argument 'coords', represents a three dimensional coordinate
3715 // which can be used to specify a single kernel instance to break on. If this
3716 // is set then we add a callback to the breakpoint.
3717 bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
3718                                                   Stream &messages,
3719                                                   const char *name,
3720                                                   const RSCoordinate *coord) {
3721   if (!name)
3722     return false;
3723
3724   InitSearchFilter(target);
3725
3726   ConstString kernel_name(name);
3727   BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
3728   if (!bp)
3729     return false;
3730
3731   // We have a conditional breakpoint on a specific coordinate
3732   if (coord)
3733     SetConditional(bp, messages, *coord);
3734
3735   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3736
3737   return true;
3738 }
3739
3740 BreakpointSP
3741 RenderScriptRuntime::CreateScriptGroupBreakpoint(ConstString name,
3742                                                  bool stop_on_all) {
3743   Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3744
3745   if (!m_filtersp) {
3746     LLDB_LOGF(log, "%s - error, no breakpoint search filter set.",
3747               __FUNCTION__);
3748     return nullptr;
3749   }
3750
3751   BreakpointResolverSP resolver_sp(new RSScriptGroupBreakpointResolver(
3752       nullptr, name, m_scriptGroups, stop_on_all));
3753   Target &target = GetProcess()->GetTarget();
3754   BreakpointSP bp = target.CreateBreakpoint(
3755       m_filtersp, resolver_sp, false, false, false);
3756   // Give RS breakpoints a specific name, so the user can manipulate them as a
3757   // group.
3758   Status err;
3759   target.AddNameToBreakpoint(bp, name.GetCString(), err);
3760   if (err.Fail() && log)
3761     LLDB_LOGF(log, "%s - error setting break name, '%s'.", __FUNCTION__,
3762               err.AsCString());
3763   // ask the breakpoint to resolve itself
3764   bp->ResolveBreakpoint();
3765   return bp;
3766 }
3767
3768 bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target,
3769                                                        Stream &strm,
3770                                                        ConstString name,
3771                                                        bool multi) {
3772   InitSearchFilter(target);
3773   BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi);
3774   if (bp)
3775     bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
3776   return bool(bp);
3777 }
3778
3779 bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3780                                                      Stream &messages,
3781                                                      const char *reduce_name,
3782                                                      const RSCoordinate *coord,
3783                                                      int kernel_types) {
3784   if (!reduce_name)
3785     return false;
3786
3787   InitSearchFilter(target);
3788   BreakpointSP bp =
3789       CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3790   if (!bp)
3791     return false;
3792
3793   if (coord)
3794     SetConditional(bp, messages, *coord);
3795
3796   bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3797
3798   return true;
3799 }
3800
3801 void RenderScriptRuntime::DumpModules(Stream &strm) const {
3802   strm.Printf("RenderScript Modules:");
3803   strm.EOL();
3804   strm.IndentMore();
3805   for (const auto &module : m_rsmodules) {
3806     module->Dump(strm);
3807   }
3808   strm.IndentLess();
3809 }
3810
3811 RenderScriptRuntime::ScriptDetails *
3812 RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3813   for (const auto &s : m_scripts) {
3814     if (s->script.isValid())
3815       if (*s->script == address)
3816         return s.get();
3817   }
3818   if (create) {
3819     std::unique_ptr<ScriptDetails> s(new ScriptDetails);
3820     s->script = address;
3821     m_scripts.push_back(std::move(s));
3822     return m_scripts.back().get();
3823   }
3824   return nullptr;
3825 }
3826
3827 RenderScriptRuntime::AllocationDetails *
3828 RenderScriptRuntime::LookUpAllocation(addr_t address) {
3829   for (const auto &a : m_allocations) {
3830     if (a->address.isValid())
3831       if (*a->address == address)
3832         return a.get();
3833   }
3834   return nullptr;
3835 }
3836
3837 RenderScriptRuntime::AllocationDetails *
3838 RenderScriptRuntime::CreateAllocation(addr_t address) {
3839   Log *log = GetLog(LLDBLog::Language);
3840
3841   // Remove any previous allocation which contains the same address
3842   auto it = m_allocations.begin();
3843   while (it != m_allocations.end()) {
3844     if (*((*it)->address) == address) {
3845       LLDB_LOGF(log, "%s - Removing allocation id: %d, address: 0x%" PRIx64,
3846                 __FUNCTION__, (*it)->id, address);
3847
3848       it = m_allocations.erase(it);
3849     } else {
3850       it++;
3851     }
3852   }
3853
3854   std::unique_ptr<AllocationDetails> a(new AllocationDetails);
3855   a->address = address;
3856   m_allocations.push_back(std::move(a));
3857   return m_allocations.back().get();
3858 }
3859
3860 bool RenderScriptRuntime::ResolveKernelName(lldb::addr_t kernel_addr,
3861                                             ConstString &name) {
3862   Log *log = GetLog(LLDBLog::Symbols);
3863
3864   Target &target = GetProcess()->GetTarget();
3865   Address resolved;
3866   // RenderScript module
3867   if (!target.GetSectionLoadList().ResolveLoadAddress(kernel_addr, resolved)) {
3868     LLDB_LOGF(log, "%s: unable to resolve 0x%" PRIx64 " to a loaded symbol",
3869               __FUNCTION__, kernel_addr);
3870     return false;
3871   }
3872
3873   Symbol *sym = resolved.CalculateSymbolContextSymbol();
3874   if (!sym)
3875     return false;
3876
3877   name = sym->GetName();
3878   assert(IsRenderScriptModule(resolved.CalculateSymbolContextModule()));
3879   LLDB_LOGF(log, "%s: 0x%" PRIx64 " resolved to the symbol '%s'", __FUNCTION__,
3880             kernel_addr, name.GetCString());
3881   return true;
3882 }
3883
3884 void RSModuleDescriptor::Dump(Stream &strm) const {
3885   int indent = strm.GetIndentLevel();
3886
3887   strm.Indent();
3888   m_module->GetFileSpec().Dump(strm.AsRawOstream());
3889   strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
3890                                              : "Debug info does not exist.");
3891   strm.EOL();
3892   strm.IndentMore();
3893
3894   strm.Indent();
3895   strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
3896   strm.EOL();
3897   strm.IndentMore();
3898   for (const auto &global : m_globals) {
3899     global.Dump(strm);
3900   }
3901   strm.IndentLess();
3902
3903   strm.Indent();
3904   strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
3905   strm.EOL();
3906   strm.IndentMore();
3907   for (const auto &kernel : m_kernels) {
3908     kernel.Dump(strm);
3909   }
3910   strm.IndentLess();
3911
3912   strm.Indent();
3913   strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
3914   strm.EOL();
3915   strm.IndentMore();
3916   for (const auto &key_val : m_pragmas) {
3917     strm.Indent();
3918     strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
3919     strm.EOL();
3920   }
3921   strm.IndentLess();
3922
3923   strm.Indent();
3924   strm.Printf("Reductions: %" PRIu64,
3925               static_cast<uint64_t>(m_reductions.size()));
3926   strm.EOL();
3927   strm.IndentMore();
3928   for (const auto &reduction : m_reductions) {
3929     reduction.Dump(strm);
3930   }
3931
3932   strm.SetIndentLevel(indent);
3933 }
3934
3935 void RSGlobalDescriptor::Dump(Stream &strm) const {
3936   strm.Indent(m_name.GetStringRef());
3937   VariableList var_list;
3938   m_module->m_module->FindGlobalVariables(m_name, CompilerDeclContext(), 1U,
3939                                           var_list);
3940   if (var_list.GetSize() == 1) {
3941     auto var = var_list.GetVariableAtIndex(0);
3942     auto type = var->GetType();
3943     if (type) {
3944       strm.Printf(" - ");
3945       type->DumpTypeName(&strm);
3946     } else {
3947       strm.Printf(" - Unknown Type");
3948     }
3949   } else {
3950     strm.Printf(" - variable identified, but not found in binary");
3951     const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
3952         m_name, eSymbolTypeData);
3953     if (s) {
3954       strm.Printf(" (symbol exists) ");
3955     }
3956   }
3957
3958   strm.EOL();
3959 }
3960
3961 void RSKernelDescriptor::Dump(Stream &strm) const {
3962   strm.Indent(m_name.GetStringRef());
3963   strm.EOL();
3964 }
3965
3966 void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
3967   stream.Indent(m_reduce_name.GetStringRef());
3968   stream.IndentMore();
3969   stream.EOL();
3970   stream.Indent();
3971   stream.Printf("accumulator: %s", m_accum_name.AsCString());
3972   stream.EOL();
3973   stream.Indent();
3974   stream.Printf("initializer: %s", m_init_name.AsCString());
3975   stream.EOL();
3976   stream.Indent();
3977   stream.Printf("combiner: %s", m_comb_name.AsCString());
3978   stream.EOL();
3979   stream.Indent();
3980   stream.Printf("outconverter: %s", m_outc_name.AsCString());
3981   stream.EOL();
3982   // XXX This is currently unspecified by RenderScript, and unused
3983   // stream.Indent();
3984   // stream.Printf("halter: '%s'", m_init_name.AsCString());
3985   // stream.EOL();
3986   stream.IndentLess();
3987 }
3988
3989 class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
3990 public:
3991   CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
3992       : CommandObjectParsed(
3993             interpreter, "renderscript module dump",
3994             "Dumps renderscript specific information for all modules.",
3995             "renderscript module dump",
3996             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
3997
3998   ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
3999
4000   bool DoExecute(Args &command, CommandReturnObject &result) override {
4001     RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4002         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4003             eLanguageTypeExtRenderScript));
4004     runtime->DumpModules(result.GetOutputStream());
4005     result.SetStatus(eReturnStatusSuccessFinishResult);
4006     return true;
4007   }
4008 };
4009
4010 class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
4011 public:
4012   CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
4013       : CommandObjectMultiword(interpreter, "renderscript module",
4014                                "Commands that deal with RenderScript modules.",
4015                                nullptr) {
4016     LoadSubCommand(
4017         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
4018                     interpreter)));
4019   }
4020
4021   ~CommandObjectRenderScriptRuntimeModule() override = default;
4022 };
4023
4024 class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
4025 public:
4026   CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
4027       : CommandObjectParsed(
4028             interpreter, "renderscript kernel list",
4029             "Lists renderscript kernel names and associated script resources.",
4030             "renderscript kernel list",
4031             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4032
4033   ~CommandObjectRenderScriptRuntimeKernelList() override = default;
4034
4035   bool DoExecute(Args &command, CommandReturnObject &result) override {
4036     RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4037         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4038             eLanguageTypeExtRenderScript));
4039     runtime->DumpKernels(result.GetOutputStream());
4040     result.SetStatus(eReturnStatusSuccessFinishResult);
4041     return true;
4042   }
4043 };
4044
4045 static constexpr OptionDefinition g_renderscript_reduction_bp_set_options[] = {
4046     {LLDB_OPT_SET_1, false, "function-role", 't',
4047      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOneLiner,
4048      "Break on a comma separated set of reduction kernel types "
4049      "(accumulator,outcoverter,combiner,initializer"},
4050     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4051      nullptr, {}, 0, eArgTypeValue,
4052      "Set a breakpoint on a single invocation of the kernel with specified "
4053      "coordinate.\n"
4054      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4055      "integers representing kernel dimensions. "
4056      "Any unset dimensions will be defaulted to zero."}};
4057
4058 class CommandObjectRenderScriptRuntimeReductionBreakpointSet
4059     : public CommandObjectParsed {
4060 public:
4061   CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4062       CommandInterpreter &interpreter)
4063       : CommandObjectParsed(
4064             interpreter, "renderscript reduction breakpoint set",
4065             "Set a breakpoint on named RenderScript general reductions",
4066             "renderscript reduction breakpoint set  <kernel_name> [-t "
4067             "<reduction_kernel_type,...>]",
4068             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4069                 eCommandProcessMustBePaused),
4070         m_options() {
4071     CommandArgumentData name_arg{eArgTypeName, eArgRepeatPlain};
4072     m_arguments.push_back({name_arg});
4073   };
4074
4075   class CommandOptions : public Options {
4076   public:
4077     CommandOptions() : Options() {}
4078
4079     ~CommandOptions() override = default;
4080
4081     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4082                           ExecutionContext *exe_ctx) override {
4083       Status err;
4084       StreamString err_str;
4085       const int short_option = m_getopt_table[option_idx].val;
4086       switch (short_option) {
4087       case 't':
4088         if (!ParseReductionTypes(option_arg, err_str))
4089           err.SetErrorStringWithFormat(
4090               "Unable to deduce reduction types for %s: %s",
4091               option_arg.str().c_str(), err_str.GetData());
4092         break;
4093       case 'c': {
4094         auto coord = RSCoordinate{};
4095         if (!ParseCoordinate(option_arg, coord))
4096           err.SetErrorStringWithFormat("unable to parse coordinate for %s",
4097                                        option_arg.str().c_str());
4098         else {
4099           m_have_coord = true;
4100           m_coord = coord;
4101         }
4102         break;
4103       }
4104       default:
4105         err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
4106       }
4107       return err;
4108     }
4109
4110     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4111       m_have_coord = false;
4112     }
4113
4114     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4115       return llvm::makeArrayRef(g_renderscript_reduction_bp_set_options);
4116     }
4117
4118     bool ParseReductionTypes(llvm::StringRef option_val,
4119                              StreamString &err_str) {
4120       m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
4121       const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
4122         return llvm::StringSwitch<int>(name)
4123             .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
4124             .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
4125             .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
4126             .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
4127             .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
4128             // Currently not exposed by the runtime
4129             // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
4130             .Default(0);
4131       };
4132
4133       // Matching a comma separated list of known words is fairly
4134       // straightforward with PCRE, but we're using ERE, so we end up with a
4135       // little ugliness...
4136       RegularExpression match_type_list(
4137           llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
4138
4139       assert(match_type_list.IsValid());
4140
4141       if (!match_type_list.Execute(option_val)) {
4142         err_str.PutCString(
4143             "a comma-separated list of kernel types is required");
4144         return false;
4145       }
4146
4147       // splitting on commas is much easier with llvm::StringRef than regex
4148       llvm::SmallVector<llvm::StringRef, 5> type_names;
4149       llvm::StringRef(option_val).split(type_names, ',');
4150
4151       for (const auto &name : type_names) {
4152         const int type = reduce_name_to_type(name);
4153         if (!type) {
4154           err_str.Printf("unknown kernel type name %s", name.str().c_str());
4155           return false;
4156         }
4157         m_kernel_types |= type;
4158       }
4159
4160       return true;
4161     }
4162
4163     int m_kernel_types = RSReduceBreakpointResolver::eKernelTypeAll;
4164     llvm::StringRef m_reduce_name;
4165     RSCoordinate m_coord;
4166     bool m_have_coord = false;
4167   };
4168
4169   Options *GetOptions() override { return &m_options; }
4170
4171   bool DoExecute(Args &command, CommandReturnObject &result) override {
4172     const size_t argc = command.GetArgumentCount();
4173     if (argc < 1) {
4174       result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
4175                                    "and an optional kernel type list",
4176                                    m_cmd_name.c_str());
4177       return false;
4178     }
4179
4180     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4181         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4182             eLanguageTypeExtRenderScript));
4183
4184     auto &outstream = result.GetOutputStream();
4185     auto name = command.GetArgumentAtIndex(0);
4186     auto &target = m_exe_ctx.GetTargetSP();
4187     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4188     if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
4189                                              m_options.m_kernel_types)) {
4190       result.AppendError("Error: unable to place breakpoint on reduction");
4191       return false;
4192     }
4193     result.AppendMessage("Breakpoint(s) created");
4194     result.SetStatus(eReturnStatusSuccessFinishResult);
4195     return true;
4196   }
4197
4198 private:
4199   CommandOptions m_options;
4200 };
4201
4202 static constexpr OptionDefinition g_renderscript_kernel_bp_set_options[] = {
4203     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4204      nullptr, {}, 0, eArgTypeValue,
4205      "Set a breakpoint on a single invocation of the kernel with specified "
4206      "coordinate.\n"
4207      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4208      "integers representing kernel dimensions. "
4209      "Any unset dimensions will be defaulted to zero."}};
4210
4211 class CommandObjectRenderScriptRuntimeKernelBreakpointSet
4212     : public CommandObjectParsed {
4213 public:
4214   CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4215       CommandInterpreter &interpreter)
4216       : CommandObjectParsed(
4217             interpreter, "renderscript kernel breakpoint set",
4218             "Sets a breakpoint on a renderscript kernel.",
4219             "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
4220             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4221                 eCommandProcessMustBePaused),
4222         m_options() {
4223     CommandArgumentData name_arg{eArgTypeName, eArgRepeatPlain};
4224     m_arguments.push_back({name_arg});
4225   }
4226
4227   ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
4228
4229   Options *GetOptions() override { return &m_options; }
4230
4231   class CommandOptions : public Options {
4232   public:
4233     CommandOptions() : Options() {}
4234
4235     ~CommandOptions() override = default;
4236
4237     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4238                           ExecutionContext *exe_ctx) override {
4239       Status err;
4240       const int short_option = m_getopt_table[option_idx].val;
4241
4242       switch (short_option) {
4243       case 'c': {
4244         auto coord = RSCoordinate{};
4245         if (!ParseCoordinate(option_arg, coord))
4246           err.SetErrorStringWithFormat(
4247               "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
4248               option_arg.str().c_str());
4249         else {
4250           m_have_coord = true;
4251           m_coord = coord;
4252         }
4253         break;
4254       }
4255       default:
4256         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4257         break;
4258       }
4259       return err;
4260     }
4261
4262     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4263       m_have_coord = false;
4264     }
4265
4266     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4267       return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
4268     }
4269
4270     RSCoordinate m_coord;
4271     bool m_have_coord = false;
4272   };
4273
4274   bool DoExecute(Args &command, CommandReturnObject &result) override {
4275     const size_t argc = command.GetArgumentCount();
4276     if (argc < 1) {
4277       result.AppendErrorWithFormat(
4278           "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4279           m_cmd_name.c_str());
4280       return false;
4281     }
4282
4283     RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4284         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4285             eLanguageTypeExtRenderScript));
4286
4287     auto &outstream = result.GetOutputStream();
4288     auto &target = m_exe_ctx.GetTargetSP();
4289     auto name = command.GetArgumentAtIndex(0);
4290     auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4291     if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
4292       result.AppendErrorWithFormat(
4293           "Error: unable to set breakpoint on kernel '%s'", name);
4294       return false;
4295     }
4296
4297     result.AppendMessage("Breakpoint(s) created");
4298     result.SetStatus(eReturnStatusSuccessFinishResult);
4299     return true;
4300   }
4301
4302 private:
4303   CommandOptions m_options;
4304 };
4305
4306 class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4307     : public CommandObjectParsed {
4308 public:
4309   CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4310       CommandInterpreter &interpreter)
4311       : CommandObjectParsed(
4312             interpreter, "renderscript kernel breakpoint all",
4313             "Automatically sets a breakpoint on all renderscript kernels that "
4314             "are or will be loaded.\n"
4315             "Disabling option means breakpoints will no longer be set on any "
4316             "kernels loaded in the future, "
4317             "but does not remove currently set breakpoints.",
4318             "renderscript kernel breakpoint all <enable/disable>",
4319             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4320                 eCommandProcessMustBePaused) {
4321     CommandArgumentData enable_arg{eArgTypeNone, eArgRepeatPlain};
4322     m_arguments.push_back({enable_arg});
4323   }
4324
4325   ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
4326
4327   bool DoExecute(Args &command, CommandReturnObject &result) override {
4328     const size_t argc = command.GetArgumentCount();
4329     if (argc != 1) {
4330       result.AppendErrorWithFormat(
4331           "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
4332       return false;
4333     }
4334
4335     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4336         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4337             eLanguageTypeExtRenderScript));
4338
4339     bool do_break = false;
4340     const char *argument = command.GetArgumentAtIndex(0);
4341     if (strcmp(argument, "enable") == 0) {
4342       do_break = true;
4343       result.AppendMessage("Breakpoints will be set on all kernels.");
4344     } else if (strcmp(argument, "disable") == 0) {
4345       do_break = false;
4346       result.AppendMessage("Breakpoints will not be set on any new kernels.");
4347     } else {
4348       result.AppendErrorWithFormat(
4349           "Argument must be either 'enable' or 'disable'");
4350       return false;
4351     }
4352
4353     runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
4354
4355     result.SetStatus(eReturnStatusSuccessFinishResult);
4356     return true;
4357   }
4358 };
4359
4360 class CommandObjectRenderScriptRuntimeReductionBreakpoint
4361     : public CommandObjectMultiword {
4362 public:
4363   CommandObjectRenderScriptRuntimeReductionBreakpoint(
4364       CommandInterpreter &interpreter)
4365       : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4366                                "Commands that manipulate breakpoints on "
4367                                "renderscript general reductions.",
4368                                nullptr) {
4369     LoadSubCommand(
4370         "set", CommandObjectSP(
4371                    new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4372                        interpreter)));
4373   }
4374
4375   ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4376 };
4377
4378 class CommandObjectRenderScriptRuntimeKernelCoordinate
4379     : public CommandObjectParsed {
4380 public:
4381   CommandObjectRenderScriptRuntimeKernelCoordinate(
4382       CommandInterpreter &interpreter)
4383       : CommandObjectParsed(
4384             interpreter, "renderscript kernel coordinate",
4385             "Shows the (x,y,z) coordinate of the current kernel invocation.",
4386             "renderscript kernel coordinate",
4387             eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4388                 eCommandProcessMustBePaused) {}
4389
4390   ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
4391
4392   bool DoExecute(Args &command, CommandReturnObject &result) override {
4393     RSCoordinate coord{};
4394     bool success = RenderScriptRuntime::GetKernelCoordinate(
4395         coord, m_exe_ctx.GetThreadPtr());
4396     Stream &stream = result.GetOutputStream();
4397
4398     if (success) {
4399       stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
4400       stream.EOL();
4401       result.SetStatus(eReturnStatusSuccessFinishResult);
4402     } else {
4403       stream.Printf("Error: Coordinate could not be found.");
4404       stream.EOL();
4405       result.SetStatus(eReturnStatusFailed);
4406     }
4407     return true;
4408   }
4409 };
4410
4411 class CommandObjectRenderScriptRuntimeKernelBreakpoint
4412     : public CommandObjectMultiword {
4413 public:
4414   CommandObjectRenderScriptRuntimeKernelBreakpoint(
4415       CommandInterpreter &interpreter)
4416       : CommandObjectMultiword(
4417             interpreter, "renderscript kernel",
4418             "Commands that generate breakpoints on renderscript kernels.",
4419             nullptr) {
4420     LoadSubCommand(
4421         "set",
4422         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4423             interpreter)));
4424     LoadSubCommand(
4425         "all",
4426         CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4427             interpreter)));
4428   }
4429
4430   ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
4431 };
4432
4433 class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
4434 public:
4435   CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4436       : CommandObjectMultiword(interpreter, "renderscript kernel",
4437                                "Commands that deal with RenderScript kernels.",
4438                                nullptr) {
4439     LoadSubCommand(
4440         "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4441                     interpreter)));
4442     LoadSubCommand(
4443         "coordinate",
4444         CommandObjectSP(
4445             new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4446     LoadSubCommand(
4447         "breakpoint",
4448         CommandObjectSP(
4449             new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
4450   }
4451
4452   ~CommandObjectRenderScriptRuntimeKernel() override = default;
4453 };
4454
4455 class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
4456 public:
4457   CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4458       : CommandObjectParsed(interpreter, "renderscript context dump",
4459                             "Dumps renderscript context information.",
4460                             "renderscript context dump",
4461                             eCommandRequiresProcess |
4462                                 eCommandProcessMustBeLaunched) {}
4463
4464   ~CommandObjectRenderScriptRuntimeContextDump() override = default;
4465
4466   bool DoExecute(Args &command, CommandReturnObject &result) override {
4467     RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4468         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4469             eLanguageTypeExtRenderScript));
4470     runtime->DumpContexts(result.GetOutputStream());
4471     result.SetStatus(eReturnStatusSuccessFinishResult);
4472     return true;
4473   }
4474 };
4475
4476 static constexpr OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
4477     {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
4478      nullptr, {}, 0, eArgTypeFilename,
4479      "Print results to specified file instead of command line."}};
4480
4481 class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
4482 public:
4483   CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4484       : CommandObjectMultiword(interpreter, "renderscript context",
4485                                "Commands that deal with RenderScript contexts.",
4486                                nullptr) {
4487     LoadSubCommand(
4488         "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4489                     interpreter)));
4490   }
4491
4492   ~CommandObjectRenderScriptRuntimeContext() override = default;
4493 };
4494
4495 class CommandObjectRenderScriptRuntimeAllocationDump
4496     : public CommandObjectParsed {
4497 public:
4498   CommandObjectRenderScriptRuntimeAllocationDump(
4499       CommandInterpreter &interpreter)
4500       : CommandObjectParsed(interpreter, "renderscript allocation dump",
4501                             "Displays the contents of a particular allocation",
4502                             "renderscript allocation dump <ID>",
4503                             eCommandRequiresProcess |
4504                                 eCommandProcessMustBeLaunched),
4505         m_options() {
4506     CommandArgumentData id_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
4507     m_arguments.push_back({id_arg});
4508   }
4509
4510   ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4511
4512   Options *GetOptions() override { return &m_options; }
4513
4514   class CommandOptions : public Options {
4515   public:
4516     CommandOptions() : Options() {}
4517
4518     ~CommandOptions() override = default;
4519
4520     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4521                           ExecutionContext *exe_ctx) override {
4522       Status err;
4523       const int short_option = m_getopt_table[option_idx].val;
4524
4525       switch (short_option) {
4526       case 'f':
4527         m_outfile.SetFile(option_arg, FileSpec::Style::native);
4528         FileSystem::Instance().Resolve(m_outfile);
4529         if (FileSystem::Instance().Exists(m_outfile)) {
4530           m_outfile.Clear();
4531           err.SetErrorStringWithFormat("file already exists: '%s'",
4532                                        option_arg.str().c_str());
4533         }
4534         break;
4535       default:
4536         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4537         break;
4538       }
4539       return err;
4540     }
4541
4542     void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4543       m_outfile.Clear();
4544     }
4545
4546     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4547       return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
4548     }
4549
4550     FileSpec m_outfile;
4551   };
4552
4553   bool DoExecute(Args &command, CommandReturnObject &result) override {
4554     const size_t argc = command.GetArgumentCount();
4555     if (argc < 1) {
4556       result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4557                                    "As well as an optional -f argument",
4558                                    m_cmd_name.c_str());
4559       return false;
4560     }
4561
4562     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4563         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4564             eLanguageTypeExtRenderScript));
4565
4566     const char *id_cstr = command.GetArgumentAtIndex(0);
4567     uint32_t id;
4568     if (!llvm::to_integer(id_cstr, id)) {
4569       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4570                                    id_cstr);
4571       return false;
4572     }
4573
4574     Stream *output_stream_p = nullptr;
4575     std::unique_ptr<Stream> output_stream_storage;
4576
4577     const FileSpec &outfile_spec =
4578         m_options.m_outfile; // Dump allocation to file instead
4579     if (outfile_spec) {
4580       // Open output file
4581       std::string path = outfile_spec.GetPath();
4582       auto file = FileSystem::Instance().Open(outfile_spec,
4583                                               File::eOpenOptionWriteOnly |
4584                                                   File::eOpenOptionCanCreate);
4585       if (file) {
4586         output_stream_storage =
4587             std::make_unique<StreamFile>(std::move(file.get()));
4588         output_stream_p = output_stream_storage.get();
4589         result.GetOutputStream().Printf("Results written to '%s'",
4590                                         path.c_str());
4591         result.GetOutputStream().EOL();
4592       } else {
4593         std::string error = llvm::toString(file.takeError());
4594         result.AppendErrorWithFormat("Couldn't open file '%s': %s",
4595                                      path.c_str(), error.c_str());
4596         return false;
4597       }
4598     } else
4599       output_stream_p = &result.GetOutputStream();
4600
4601     assert(output_stream_p != nullptr);
4602     bool dumped =
4603         runtime->DumpAllocation(*output_stream_p, m_exe_ctx.GetFramePtr(), id);
4604
4605     if (dumped)
4606       result.SetStatus(eReturnStatusSuccessFinishResult);
4607     else
4608       result.SetStatus(eReturnStatusFailed);
4609
4610     return true;
4611   }
4612
4613 private:
4614   CommandOptions m_options;
4615 };
4616
4617 static constexpr OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
4618     {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
4619      {}, 0, eArgTypeIndex,
4620      "Only show details of a single allocation with specified id."}};
4621
4622 class CommandObjectRenderScriptRuntimeAllocationList
4623     : public CommandObjectParsed {
4624 public:
4625   CommandObjectRenderScriptRuntimeAllocationList(
4626       CommandInterpreter &interpreter)
4627       : CommandObjectParsed(
4628             interpreter, "renderscript allocation list",
4629             "List renderscript allocations and their information.",
4630             "renderscript allocation list",
4631             eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4632         m_options() {}
4633
4634   ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4635
4636   Options *GetOptions() override { return &m_options; }
4637
4638   class CommandOptions : public Options {
4639   public:
4640     CommandOptions() : Options() {}
4641
4642     ~CommandOptions() override = default;
4643
4644     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4645                           ExecutionContext *exe_ctx) override {
4646       Status err;
4647       const int short_option = m_getopt_table[option_idx].val;
4648
4649       switch (short_option) {
4650       case 'i':
4651         if (option_arg.getAsInteger(0, m_id))
4652           err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4653                                        short_option);
4654         break;
4655       default:
4656         err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4657         break;
4658       }
4659       return err;
4660     }
4661
4662     void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
4663
4664     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4665       return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
4666     }
4667
4668     uint32_t m_id = 0;
4669   };
4670
4671   bool DoExecute(Args &command, CommandReturnObject &result) override {
4672     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4673         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4674             eLanguageTypeExtRenderScript));
4675     runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4676                              m_options.m_id);
4677     result.SetStatus(eReturnStatusSuccessFinishResult);
4678     return true;
4679   }
4680
4681 private:
4682   CommandOptions m_options;
4683 };
4684
4685 class CommandObjectRenderScriptRuntimeAllocationLoad
4686     : public CommandObjectParsed {
4687 public:
4688   CommandObjectRenderScriptRuntimeAllocationLoad(
4689       CommandInterpreter &interpreter)
4690       : CommandObjectParsed(
4691             interpreter, "renderscript allocation load",
4692             "Loads renderscript allocation contents from a file.",
4693             "renderscript allocation load <ID> <filename>",
4694             eCommandRequiresProcess | eCommandProcessMustBeLaunched) {
4695     CommandArgumentData id_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
4696     CommandArgumentData name_arg{eArgTypeFilename, eArgRepeatPlain};
4697     m_arguments.push_back({id_arg});
4698     m_arguments.push_back({name_arg});
4699   }
4700
4701   ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
4702
4703   bool DoExecute(Args &command, CommandReturnObject &result) override {
4704     const size_t argc = command.GetArgumentCount();
4705     if (argc != 2) {
4706       result.AppendErrorWithFormat(
4707           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4708           m_cmd_name.c_str());
4709       return false;
4710     }
4711
4712     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4713         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4714             eLanguageTypeExtRenderScript));
4715
4716     const char *id_cstr = command.GetArgumentAtIndex(0);
4717     uint32_t id;
4718     if (!llvm::to_integer(id_cstr, id)) {
4719       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4720                                    id_cstr);
4721       return false;
4722     }
4723
4724     const char *path = command.GetArgumentAtIndex(1);
4725     bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
4726                                           m_exe_ctx.GetFramePtr());
4727
4728     if (loaded)
4729       result.SetStatus(eReturnStatusSuccessFinishResult);
4730     else
4731       result.SetStatus(eReturnStatusFailed);
4732
4733     return true;
4734   }
4735 };
4736
4737 class CommandObjectRenderScriptRuntimeAllocationSave
4738     : public CommandObjectParsed {
4739 public:
4740   CommandObjectRenderScriptRuntimeAllocationSave(
4741       CommandInterpreter &interpreter)
4742       : CommandObjectParsed(interpreter, "renderscript allocation save",
4743                             "Write renderscript allocation contents to a file.",
4744                             "renderscript allocation save <ID> <filename>",
4745                             eCommandRequiresProcess |
4746                                 eCommandProcessMustBeLaunched) {
4747     CommandArgumentData id_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
4748     CommandArgumentData name_arg{eArgTypeFilename, eArgRepeatPlain};
4749     m_arguments.push_back({id_arg});
4750     m_arguments.push_back({name_arg});
4751   }
4752
4753   ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
4754
4755   bool DoExecute(Args &command, CommandReturnObject &result) override {
4756     const size_t argc = command.GetArgumentCount();
4757     if (argc != 2) {
4758       result.AppendErrorWithFormat(
4759           "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4760           m_cmd_name.c_str());
4761       return false;
4762     }
4763
4764     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4765         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4766             eLanguageTypeExtRenderScript));
4767
4768     const char *id_cstr = command.GetArgumentAtIndex(0);
4769     uint32_t id;
4770     if (!llvm::to_integer(id_cstr, id)) {
4771       result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4772                                    id_cstr);
4773       return false;
4774     }
4775
4776     const char *path = command.GetArgumentAtIndex(1);
4777     bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
4778                                          m_exe_ctx.GetFramePtr());
4779
4780     if (saved)
4781       result.SetStatus(eReturnStatusSuccessFinishResult);
4782     else
4783       result.SetStatus(eReturnStatusFailed);
4784
4785     return true;
4786   }
4787 };
4788
4789 class CommandObjectRenderScriptRuntimeAllocationRefresh
4790     : public CommandObjectParsed {
4791 public:
4792   CommandObjectRenderScriptRuntimeAllocationRefresh(
4793       CommandInterpreter &interpreter)
4794       : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4795                             "Recomputes the details of all allocations.",
4796                             "renderscript allocation refresh",
4797                             eCommandRequiresProcess |
4798                                 eCommandProcessMustBeLaunched) {}
4799
4800   ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
4801
4802   bool DoExecute(Args &command, CommandReturnObject &result) override {
4803     RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4804         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4805             eLanguageTypeExtRenderScript));
4806
4807     bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4808                                                     m_exe_ctx.GetFramePtr());
4809
4810     if (success) {
4811       result.SetStatus(eReturnStatusSuccessFinishResult);
4812       return true;
4813     } else {
4814       result.SetStatus(eReturnStatusFailed);
4815       return false;
4816     }
4817   }
4818 };
4819
4820 class CommandObjectRenderScriptRuntimeAllocation
4821     : public CommandObjectMultiword {
4822 public:
4823   CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4824       : CommandObjectMultiword(
4825             interpreter, "renderscript allocation",
4826             "Commands that deal with RenderScript allocations.", nullptr) {
4827     LoadSubCommand(
4828         "list",
4829         CommandObjectSP(
4830             new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4831     LoadSubCommand(
4832         "dump",
4833         CommandObjectSP(
4834             new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4835     LoadSubCommand(
4836         "save",
4837         CommandObjectSP(
4838             new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4839     LoadSubCommand(
4840         "load",
4841         CommandObjectSP(
4842             new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4843     LoadSubCommand(
4844         "refresh",
4845         CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4846             interpreter)));
4847   }
4848
4849   ~CommandObjectRenderScriptRuntimeAllocation() override = default;
4850 };
4851
4852 class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
4853 public:
4854   CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4855       : CommandObjectParsed(interpreter, "renderscript status",
4856                             "Displays current RenderScript runtime status.",
4857                             "renderscript status",
4858                             eCommandRequiresProcess |
4859                                 eCommandProcessMustBeLaunched) {}
4860
4861   ~CommandObjectRenderScriptRuntimeStatus() override = default;
4862
4863   bool DoExecute(Args &command, CommandReturnObject &result) override {
4864     RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4865         m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4866             eLanguageTypeExtRenderScript));
4867     runtime->DumpStatus(result.GetOutputStream());
4868     result.SetStatus(eReturnStatusSuccessFinishResult);
4869     return true;
4870   }
4871 };
4872
4873 class CommandObjectRenderScriptRuntimeReduction
4874     : public CommandObjectMultiword {
4875 public:
4876   CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
4877       : CommandObjectMultiword(interpreter, "renderscript reduction",
4878                                "Commands that handle general reduction kernels",
4879                                nullptr) {
4880     LoadSubCommand(
4881         "breakpoint",
4882         CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
4883             interpreter)));
4884   }
4885   ~CommandObjectRenderScriptRuntimeReduction() override = default;
4886 };
4887
4888 class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
4889 public:
4890   CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
4891       : CommandObjectMultiword(
4892             interpreter, "renderscript",
4893             "Commands for operating on the RenderScript runtime.",
4894             "renderscript <subcommand> [<subcommand-options>]") {
4895     LoadSubCommand(
4896         "module", CommandObjectSP(
4897                       new CommandObjectRenderScriptRuntimeModule(interpreter)));
4898     LoadSubCommand(
4899         "status", CommandObjectSP(
4900                       new CommandObjectRenderScriptRuntimeStatus(interpreter)));
4901     LoadSubCommand(
4902         "kernel", CommandObjectSP(
4903                       new CommandObjectRenderScriptRuntimeKernel(interpreter)));
4904     LoadSubCommand("context",
4905                    CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
4906                        interpreter)));
4907     LoadSubCommand(
4908         "allocation",
4909         CommandObjectSP(
4910             new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
4911     LoadSubCommand("scriptgroup",
4912                    NewCommandObjectRenderScriptScriptGroup(interpreter));
4913     LoadSubCommand(
4914         "reduction",
4915         CommandObjectSP(
4916             new CommandObjectRenderScriptRuntimeReduction(interpreter)));
4917   }
4918
4919   ~CommandObjectRenderScriptRuntime() override = default;
4920 };
4921
4922 void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
4923
4924 RenderScriptRuntime::RenderScriptRuntime(Process *process)
4925     : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
4926       m_debuggerPresentFlagged(false), m_breakAllKernels(false),
4927       m_ir_passes(nullptr) {
4928   ModulesDidLoad(process->GetTarget().GetImages());
4929 }
4930
4931 lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
4932     lldb_private::CommandInterpreter &interpreter) {
4933   return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
4934 }
4935
4936 RenderScriptRuntime::~RenderScriptRuntime() = default;