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