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