1 //===-- RenderScriptRuntime.h -----------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef liblldb_RenderScriptRuntime_h_
10 #define liblldb_RenderScriptRuntime_h_
11 
12 #include <array>
13 #include <map>
14 #include <memory>
15 #include <string>
16 #include <vector>
17 
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "lldb/Core/Module.h"
21 #include "lldb/Expression/LLVMUserExpression.h"
22 #include "lldb/Target/CPPLanguageRuntime.h"
23 #include "lldb/Target/LanguageRuntime.h"
24 #include "lldb/lldb-private.h"
25 
26 namespace lldb_private {
27 namespace lldb_renderscript {
28 
29 typedef uint32_t RSSlot;
30 class RSModuleDescriptor;
31 struct RSGlobalDescriptor;
32 struct RSKernelDescriptor;
33 struct RSReductionDescriptor;
34 struct RSScriptGroupDescriptor;
35 
36 typedef std::shared_ptr<RSModuleDescriptor> RSModuleDescriptorSP;
37 typedef std::shared_ptr<RSGlobalDescriptor> RSGlobalDescriptorSP;
38 typedef std::shared_ptr<RSKernelDescriptor> RSKernelDescriptorSP;
39 typedef std::shared_ptr<RSScriptGroupDescriptor> RSScriptGroupDescriptorSP;
40 
41 struct RSCoordinate {
42   uint32_t x, y, z;
43 
44   RSCoordinate() : x(), y(), z(){};
45 
46   bool operator==(const lldb_renderscript::RSCoordinate &rhs) {
47     return x == rhs.x && y == rhs.y && z == rhs.z;
48   }
49 };
50 
51 // Breakpoint Resolvers decide where a breakpoint is placed, so having our own
52 // allows us to limit the search scope to RS kernel modules. As well as check
53 // for .expand kernels as a fallback.
54 class RSBreakpointResolver : public BreakpointResolver {
55 public:
56   RSBreakpointResolver(Breakpoint *bp, ConstString name)
57       : BreakpointResolver(bp, BreakpointResolver::NameResolver),
58         m_kernel_name(name) {}
59 
60   void GetDescription(Stream *strm) override {
61     if (strm)
62       strm->Printf("RenderScript kernel breakpoint for '%s'",
63                    m_kernel_name.AsCString());
64   }
65 
66   void Dump(Stream *s) const override {}
67 
68   Searcher::CallbackReturn SearchCallback(SearchFilter &filter,
69                                           SymbolContext &context, Address *addr,
70                                           bool containing) override;
71 
72   lldb::SearchDepth GetDepth() override { return lldb::eSearchDepthModule; }
73 
74   lldb::BreakpointResolverSP
75   CopyForBreakpoint(Breakpoint &breakpoint) override {
76     lldb::BreakpointResolverSP ret_sp(
77         new RSBreakpointResolver(&breakpoint, m_kernel_name));
78     return ret_sp;
79   }
80 
81 protected:
82   ConstString m_kernel_name;
83 };
84 
85 class RSReduceBreakpointResolver : public BreakpointResolver {
86 public:
87   enum ReduceKernelTypeFlags {
88     eKernelTypeAll = ~(0),
89     eKernelTypeNone = 0,
90     eKernelTypeAccum = (1 << 0),
91     eKernelTypeInit = (1 << 1),
92     eKernelTypeComb = (1 << 2),
93     eKernelTypeOutC = (1 << 3),
94     eKernelTypeHalter = (1 << 4)
95   };
96 
97   RSReduceBreakpointResolver(
98       Breakpoint *breakpoint, ConstString reduce_name,
99       std::vector<lldb_renderscript::RSModuleDescriptorSP> *rs_modules,
100       int kernel_types = eKernelTypeAll)
101       : BreakpointResolver(breakpoint, BreakpointResolver::NameResolver),
102         m_reduce_name(reduce_name), m_rsmodules(rs_modules),
103         m_kernel_types(kernel_types) {
104     // The reduce breakpoint resolver handles adding breakpoints for named
105     // reductions.
106     // Breakpoints will be resolved for all constituent kernels in the named
107     // reduction
108   }
109 
110   void GetDescription(Stream *strm) override {
111     if (strm)
112       strm->Printf("RenderScript reduce breakpoint for '%s'",
113                    m_reduce_name.AsCString());
114   }
115 
116   void Dump(Stream *s) const override {}
117 
118   Searcher::CallbackReturn SearchCallback(SearchFilter &filter,
119                                           SymbolContext &context, Address *addr,
120                                           bool containing) override;
121 
122   lldb::SearchDepth GetDepth() override { return lldb::eSearchDepthModule; }
123 
124   lldb::BreakpointResolverSP
125   CopyForBreakpoint(Breakpoint &breakpoint) override {
126     lldb::BreakpointResolverSP ret_sp(new RSReduceBreakpointResolver(
127         &breakpoint, m_reduce_name, m_rsmodules, m_kernel_types));
128     return ret_sp;
129   }
130 
131 private:
132   ConstString m_reduce_name; // The name of the reduction
133   std::vector<lldb_renderscript::RSModuleDescriptorSP> *m_rsmodules;
134   int m_kernel_types;
135 };
136 
137 struct RSKernelDescriptor {
138 public:
139   RSKernelDescriptor(const RSModuleDescriptor *module, llvm::StringRef name,
140                      uint32_t slot)
141       : m_module(module), m_name(name), m_slot(slot) {}
142 
143   void Dump(Stream &strm) const;
144 
145   const RSModuleDescriptor *m_module;
146   ConstString m_name;
147   RSSlot m_slot;
148 };
149 
150 struct RSGlobalDescriptor {
151 public:
152   RSGlobalDescriptor(const RSModuleDescriptor *module, llvm::StringRef name)
153       : m_module(module), m_name(name) {}
154 
155   void Dump(Stream &strm) const;
156 
157   const RSModuleDescriptor *m_module;
158   ConstString m_name;
159 };
160 
161 struct RSReductionDescriptor {
162   RSReductionDescriptor(const RSModuleDescriptor *module, uint32_t sig,
163                         uint32_t accum_data_size, llvm::StringRef name,
164                         llvm::StringRef init_name, llvm::StringRef accum_name,
165                         llvm::StringRef comb_name, llvm::StringRef outc_name,
166                         llvm::StringRef halter_name = ".")
167       : m_module(module), m_reduce_name(name), m_init_name(init_name),
168         m_accum_name(accum_name), m_comb_name(comb_name),
169         m_outc_name(outc_name), m_halter_name(halter_name) {
170     // TODO Check whether the combiner is an autogenerated name, and track
171     // this
172   }
173 
174   void Dump(Stream &strm) const;
175 
176   const RSModuleDescriptor *m_module;
177   ConstString m_reduce_name; // This is the name given to the general reduction
178                              // as a group as passed to pragma
179   // reduce(m_reduce_name). There is no kernel function with this name
180   ConstString m_init_name;  // The name of the initializer name. "." if no
181                             // initializer given
182   ConstString m_accum_name; // The accumulator function name. "." if not given
183   ConstString m_comb_name; // The name of the combiner function. If this was not
184                            // given, a name is generated by the
185                            // compiler. TODO
186   ConstString m_outc_name; // The name of the outconverter
187 
188   ConstString m_halter_name; // The name of the halter function. XXX This is not
189                              // yet specified by the RenderScript
190   // compiler or runtime, and its semantics and existence is still under
191   // discussion by the
192   // RenderScript Contributors
193   RSSlot m_accum_sig; // metatdata signature for this reduction (bitwise mask of
194                       // type information (see
195                       // libbcc/include/bcinfo/MetadataExtractor.h
196   uint32_t m_accum_data_size; // Data size of the accumulator function input
197   bool m_comb_name_generated; // Was the combiner name generated by the compiler
198 };
199 
200 class RSModuleDescriptor {
201   std::string m_slang_version;
202   std::string m_bcc_version;
203 
204   bool ParseVersionInfo(llvm::StringRef *, size_t n_lines);
205 
206   bool ParseExportForeachCount(llvm::StringRef *, size_t n_lines);
207 
208   bool ParseExportVarCount(llvm::StringRef *, size_t n_lines);
209 
210   bool ParseExportReduceCount(llvm::StringRef *, size_t n_lines);
211 
212   bool ParseBuildChecksum(llvm::StringRef *, size_t n_lines);
213 
214   bool ParsePragmaCount(llvm::StringRef *, size_t n_lines);
215 
216 public:
217   RSModuleDescriptor(const lldb::ModuleSP &module) : m_module(module) {}
218 
219   ~RSModuleDescriptor() = default;
220 
221   bool ParseRSInfo();
222 
223   void Dump(Stream &strm) const;
224 
225   void WarnIfVersionMismatch(Stream *s) const;
226 
227   const lldb::ModuleSP m_module;
228   std::vector<RSKernelDescriptor> m_kernels;
229   std::vector<RSGlobalDescriptor> m_globals;
230   std::vector<RSReductionDescriptor> m_reductions;
231   std::map<std::string, std::string> m_pragmas;
232   std::string m_resname;
233 };
234 
235 struct RSScriptGroupDescriptor {
236   struct Kernel {
237     ConstString m_name;
238     lldb::addr_t m_addr;
239   };
240   ConstString m_name;
241   std::vector<Kernel> m_kernels;
242 };
243 
244 typedef std::vector<RSScriptGroupDescriptorSP> RSScriptGroupList;
245 
246 class RSScriptGroupBreakpointResolver : public BreakpointResolver {
247 public:
248   RSScriptGroupBreakpointResolver(Breakpoint *bp, ConstString name,
249                                   const RSScriptGroupList &groups,
250                                   bool stop_on_all)
251       : BreakpointResolver(bp, BreakpointResolver::NameResolver),
252         m_group_name(name), m_script_groups(groups),
253         m_stop_on_all(stop_on_all) {}
254 
255   void GetDescription(Stream *strm) override {
256     if (strm)
257       strm->Printf("RenderScript ScriptGroup breakpoint for '%s'",
258                    m_group_name.AsCString());
259   }
260 
261   void Dump(Stream *s) const override {}
262 
263   Searcher::CallbackReturn SearchCallback(SearchFilter &filter,
264                                           SymbolContext &context, Address *addr,
265                                           bool containing) override;
266 
267   lldb::SearchDepth GetDepth() override { return lldb::eSearchDepthModule; }
268 
269   lldb::BreakpointResolverSP
270   CopyForBreakpoint(Breakpoint &breakpoint) override {
271     lldb::BreakpointResolverSP ret_sp(new RSScriptGroupBreakpointResolver(
272         &breakpoint, m_group_name, m_script_groups, m_stop_on_all));
273     return ret_sp;
274   }
275 
276 protected:
277   const RSScriptGroupDescriptorSP
278   FindScriptGroup(ConstString name) const {
279     for (auto sg : m_script_groups) {
280       if (ConstString::Compare(sg->m_name, name) == 0)
281         return sg;
282     }
283     return RSScriptGroupDescriptorSP();
284   }
285 
286   ConstString m_group_name;
287   const RSScriptGroupList &m_script_groups;
288   bool m_stop_on_all;
289 };
290 } // namespace lldb_renderscript
291 
292 class RenderScriptRuntime : public lldb_private::CPPLanguageRuntime {
293 public:
294   enum ModuleKind {
295     eModuleKindIgnored,
296     eModuleKindLibRS,
297     eModuleKindDriver,
298     eModuleKindImpl,
299     eModuleKindKernelObj
300   };
301 
302   ~RenderScriptRuntime() override;
303 
304   // Static Functions
305   static void Initialize();
306 
307   static void Terminate();
308 
309   static lldb_private::LanguageRuntime *
310   CreateInstance(Process *process, lldb::LanguageType language);
311 
312   static lldb::CommandObjectSP
313   GetCommandObject(CommandInterpreter &interpreter);
314 
315   static lldb_private::ConstString GetPluginNameStatic();
316 
317   static bool IsRenderScriptModule(const lldb::ModuleSP &module_sp);
318 
319   static ModuleKind GetModuleKind(const lldb::ModuleSP &module_sp);
320 
321   static void ModulesDidLoad(const lldb::ProcessSP &process_sp,
322                              const ModuleList &module_list);
323 
324   bool IsVTableName(const char *name) override;
325 
326   bool GetDynamicTypeAndAddress(ValueObject &in_value,
327                                 lldb::DynamicValueType use_dynamic,
328                                 TypeAndOrName &class_type_or_name,
329                                 Address &address,
330                                 Value::ValueType &value_type) override;
331 
332   TypeAndOrName FixUpDynamicType(const TypeAndOrName &type_and_or_name,
333                                  ValueObject &static_value) override;
334 
335   bool CouldHaveDynamicValue(ValueObject &in_value) override;
336 
337   lldb::BreakpointResolverSP CreateExceptionResolver(Breakpoint *bp,
338                                                      bool catch_bp,
339                                                      bool throw_bp) override;
340 
341   bool LoadModule(const lldb::ModuleSP &module_sp);
342 
343   void DumpModules(Stream &strm) const;
344 
345   void DumpContexts(Stream &strm) const;
346 
347   void DumpKernels(Stream &strm) const;
348 
349   bool DumpAllocation(Stream &strm, StackFrame *frame_ptr, const uint32_t id);
350 
351   void ListAllocations(Stream &strm, StackFrame *frame_ptr,
352                        const uint32_t index);
353 
354   bool RecomputeAllAllocations(Stream &strm, StackFrame *frame_ptr);
355 
356   bool PlaceBreakpointOnKernel(
357       lldb::TargetSP target, Stream &messages, const char *name,
358       const lldb_renderscript::RSCoordinate *coords = nullptr);
359 
360   bool PlaceBreakpointOnReduction(
361       lldb::TargetSP target, Stream &messages, const char *reduce_name,
362       const lldb_renderscript::RSCoordinate *coords = nullptr,
363       int kernel_types = ~(0));
364 
365   bool PlaceBreakpointOnScriptGroup(lldb::TargetSP target, Stream &strm,
366                                     ConstString name, bool stop_on_all);
367 
368   void SetBreakAllKernels(bool do_break, lldb::TargetSP target);
369 
370   void DumpStatus(Stream &strm) const;
371 
372   void ModulesDidLoad(const ModuleList &module_list) override;
373 
374   bool LoadAllocation(Stream &strm, const uint32_t alloc_id,
375                       const char *filename, StackFrame *frame_ptr);
376 
377   bool SaveAllocation(Stream &strm, const uint32_t alloc_id,
378                       const char *filename, StackFrame *frame_ptr);
379 
380   void Update();
381 
382   void Initiate();
383 
384   const lldb_renderscript::RSScriptGroupList &GetScriptGroups() const {
385     return m_scriptGroups;
386   };
387 
388   bool IsKnownKernel(ConstString name) {
389     for (const auto &module : m_rsmodules)
390       for (const auto &kernel : module->m_kernels)
391         if (kernel.m_name == name)
392           return true;
393     return false;
394   }
395 
396   // PluginInterface protocol
397   lldb_private::ConstString GetPluginName() override;
398 
399   uint32_t GetPluginVersion() override;
400 
401   static bool GetKernelCoordinate(lldb_renderscript::RSCoordinate &coord,
402                                   Thread *thread_ptr);
403 
404   bool ResolveKernelName(lldb::addr_t kernel_address, ConstString &name);
405 
406 protected:
407   struct ScriptDetails;
408   struct AllocationDetails;
409   struct Element;
410 
411   lldb_renderscript::RSScriptGroupList m_scriptGroups;
412 
413   void InitSearchFilter(lldb::TargetSP target) {
414     if (!m_filtersp)
415       m_filtersp.reset(new SearchFilterForUnconstrainedSearches(target));
416   }
417 
418   void FixupScriptDetails(lldb_renderscript::RSModuleDescriptorSP rsmodule_sp);
419 
420   void LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind);
421 
422   bool RefreshAllocation(AllocationDetails *alloc, StackFrame *frame_ptr);
423 
424   bool EvalRSExpression(const char *expression, StackFrame *frame_ptr,
425                         uint64_t *result);
426 
427   lldb::BreakpointSP CreateScriptGroupBreakpoint(ConstString name,
428                                                  bool multi);
429 
430   lldb::BreakpointSP CreateKernelBreakpoint(ConstString name);
431 
432   lldb::BreakpointSP CreateReductionBreakpoint(ConstString name,
433                                                int kernel_types);
434 
435   void BreakOnModuleKernels(
436       const lldb_renderscript::RSModuleDescriptorSP rsmodule_sp);
437 
438   struct RuntimeHook;
439   typedef void (RenderScriptRuntime::*CaptureStateFn)(
440       RuntimeHook *hook_info,
441       ExecutionContext &context); // Please do this!
442 
443   struct HookDefn {
444     const char *name;
445     const char *symbol_name_m32; // mangled name for the 32 bit architectures
446     const char *symbol_name_m64; // mangled name for the 64 bit archs
447     uint32_t version;
448     ModuleKind kind;
449     CaptureStateFn grabber;
450   };
451 
452   struct RuntimeHook {
453     lldb::addr_t address;
454     const HookDefn *defn;
455     lldb::BreakpointSP bp_sp;
456   };
457 
458   typedef std::shared_ptr<RuntimeHook> RuntimeHookSP;
459 
460   lldb::ModuleSP m_libRS;
461   lldb::ModuleSP m_libRSDriver;
462   lldb::ModuleSP m_libRSCpuRef;
463   std::vector<lldb_renderscript::RSModuleDescriptorSP> m_rsmodules;
464 
465   std::vector<std::unique_ptr<ScriptDetails>> m_scripts;
466   std::vector<std::unique_ptr<AllocationDetails>> m_allocations;
467 
468   std::map<lldb::addr_t, lldb_renderscript::RSModuleDescriptorSP>
469       m_scriptMappings;
470   std::map<lldb::addr_t, RuntimeHookSP> m_runtimeHooks;
471   std::map<lldb::user_id_t, std::unique_ptr<lldb_renderscript::RSCoordinate>>
472       m_conditional_breaks;
473 
474   lldb::SearchFilterSP
475       m_filtersp; // Needed to create breakpoints through Target API
476 
477   bool m_initiated;
478   bool m_debuggerPresentFlagged;
479   bool m_breakAllKernels;
480   static const HookDefn s_runtimeHookDefns[];
481   static const size_t s_runtimeHookCount;
482   LLVMUserExpression::IRPasses *m_ir_passes;
483 
484 private:
485   RenderScriptRuntime(Process *process); // Call CreateInstance instead.
486 
487   static bool HookCallback(void *baton, StoppointCallbackContext *ctx,
488                            lldb::user_id_t break_id,
489                            lldb::user_id_t break_loc_id);
490 
491   static bool KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx,
492                                   lldb::user_id_t break_id,
493                                   lldb::user_id_t break_loc_id);
494 
495   void HookCallback(RuntimeHook *hook_info, ExecutionContext &context);
496 
497   // Callback function when 'debugHintScriptGroup2' executes on the target.
498   void CaptureDebugHintScriptGroup2(RuntimeHook *hook_info,
499                                     ExecutionContext &context);
500 
501   void CaptureScriptInit(RuntimeHook *hook_info, ExecutionContext &context);
502 
503   void CaptureAllocationInit(RuntimeHook *hook_info, ExecutionContext &context);
504 
505   void CaptureAllocationDestroy(RuntimeHook *hook_info,
506                                 ExecutionContext &context);
507 
508   void CaptureSetGlobalVar(RuntimeHook *hook_info, ExecutionContext &context);
509 
510   void CaptureScriptInvokeForEachMulti(RuntimeHook *hook_info,
511                                        ExecutionContext &context);
512 
513   AllocationDetails *FindAllocByID(Stream &strm, const uint32_t alloc_id);
514 
515   std::shared_ptr<uint8_t> GetAllocationData(AllocationDetails *alloc,
516                                              StackFrame *frame_ptr);
517 
518   void SetElementSize(Element &elem);
519 
520   static bool GetFrameVarAsUnsigned(const lldb::StackFrameSP,
521                                     const char *var_name, uint64_t &val);
522 
523   void FindStructTypeName(Element &elem, StackFrame *frame_ptr);
524 
525   size_t PopulateElementHeaders(const std::shared_ptr<uint8_t> header_buffer,
526                                 size_t offset, const Element &elem);
527 
528   size_t CalculateElementHeaderSize(const Element &elem);
529 
530   void SetConditional(lldb::BreakpointSP bp, lldb_private::Stream &messages,
531                       const lldb_renderscript::RSCoordinate &coord);
532   //
533   // Helper functions for jitting the runtime
534   //
535 
536   bool JITDataPointer(AllocationDetails *alloc, StackFrame *frame_ptr,
537                       uint32_t x = 0, uint32_t y = 0, uint32_t z = 0);
538 
539   bool JITTypePointer(AllocationDetails *alloc, StackFrame *frame_ptr);
540 
541   bool JITTypePacked(AllocationDetails *alloc, StackFrame *frame_ptr);
542 
543   bool JITElementPacked(Element &elem, const lldb::addr_t context,
544                         StackFrame *frame_ptr);
545 
546   bool JITAllocationSize(AllocationDetails *alloc, StackFrame *frame_ptr);
547 
548   bool JITSubelements(Element &elem, const lldb::addr_t context,
549                       StackFrame *frame_ptr);
550 
551   bool JITAllocationStride(AllocationDetails *alloc, StackFrame *frame_ptr);
552 
553   // Search for a script detail object using a target address.
554   // If a script does not currently exist this function will return nullptr.
555   // If 'create' is true and there is no previous script with this address,
556   // then a new Script detail object will be created for this address and
557   // returned.
558   ScriptDetails *LookUpScript(lldb::addr_t address, bool create);
559 
560   // Search for a previously saved allocation detail object using a target
561   // address.
562   // If an allocation does not exist for this address then nullptr will be
563   // returned.
564   AllocationDetails *LookUpAllocation(lldb::addr_t address);
565 
566   // Creates a new allocation with the specified address assigning a new ID and
567   // removes
568   // any previous stored allocation which has the same address.
569   AllocationDetails *CreateAllocation(lldb::addr_t address);
570 
571   bool GetOverrideExprOptions(clang::TargetOptions &prototype) override;
572 
573   bool GetIRPasses(LLVMUserExpression::IRPasses &passes) override;
574 };
575 
576 } // namespace lldb_private
577 
578 #endif // liblldb_RenderScriptRuntime_h_
579