1 //===-- RenderScriptRuntime.h -----------------------------------*- 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 #ifndef liblldb_RenderScriptRuntime_h_
11 #define liblldb_RenderScriptRuntime_h_
12 
13 // C Includes
14 // C++ Includes
15 #include <array>
16 #include <map>
17 #include <memory>
18 #include <string>
19 #include <vector>
20 
21 // Other libraries and framework includes
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 // Project includes
25 #include "lldb/Core/Module.h"
26 #include "lldb/Expression/LLVMUserExpression.h"
27 #include "lldb/Target/CPPLanguageRuntime.h"
28 #include "lldb/Target/LanguageRuntime.h"
29 #include "lldb/lldb-private.h"
30 
31 namespace lldb_private {
32 namespace lldb_renderscript {
33 
34 typedef uint32_t RSSlot;
35 class RSModuleDescriptor;
36 struct RSGlobalDescriptor;
37 struct RSKernelDescriptor;
38 struct RSReductionDescriptor;
39 
40 typedef std::shared_ptr<RSModuleDescriptor> RSModuleDescriptorSP;
41 typedef std::shared_ptr<RSGlobalDescriptor> RSGlobalDescriptorSP;
42 typedef std::shared_ptr<RSKernelDescriptor> RSKernelDescriptorSP;
43 struct RSCoordinate {
44   uint32_t x, y, z;
45 
46   RSCoordinate() : x(), y(), z(){};
47 
48   bool operator==(const lldb_renderscript::RSCoordinate &rhs) {
49     return x == rhs.x && y == rhs.y && z == rhs.z;
50   }
51 };
52 
53 // Breakpoint Resolvers decide where a breakpoint is placed, so having our own
54 // allows us to limit the search scope to RS kernel modules. As well as check
55 // for .expand kernels as a fallback.
56 class RSBreakpointResolver : public BreakpointResolver {
57 public:
58   RSBreakpointResolver(Breakpoint *bp, ConstString name)
59       : BreakpointResolver(bp, BreakpointResolver::NameResolver),
60         m_kernel_name(name) {}
61 
62   void GetDescription(Stream *strm) override {
63     if (strm)
64       strm->Printf("RenderScript kernel breakpoint for '%s'",
65                    m_kernel_name.AsCString());
66   }
67 
68   void Dump(Stream *s) const override {}
69 
70   Searcher::CallbackReturn SearchCallback(SearchFilter &filter,
71                                           SymbolContext &context, Address *addr,
72                                           bool containing) override;
73 
74   Searcher::Depth GetDepth() override { return Searcher::eDepthModule; }
75 
76   lldb::BreakpointResolverSP
77   CopyForBreakpoint(Breakpoint &breakpoint) override {
78     lldb::BreakpointResolverSP ret_sp(
79         new RSBreakpointResolver(&breakpoint, m_kernel_name));
80     return ret_sp;
81   }
82 
83 protected:
84   ConstString m_kernel_name;
85 };
86 
87 struct RSKernelDescriptor {
88 public:
89   RSKernelDescriptor(const RSModuleDescriptor *module, llvm::StringRef name,
90                      uint32_t slot)
91       : m_module(module), m_name(name), m_slot(slot) {}
92 
93   void Dump(Stream &strm) const;
94 
95   const RSModuleDescriptor *m_module;
96   ConstString m_name;
97   RSSlot m_slot;
98 };
99 
100 struct RSGlobalDescriptor {
101 public:
102   RSGlobalDescriptor(const RSModuleDescriptor *module, llvm::StringRef name)
103       : m_module(module), m_name(name) {}
104 
105   void Dump(Stream &strm) const;
106 
107   const RSModuleDescriptor *m_module;
108   ConstString m_name;
109 };
110 
111 struct RSReductionDescriptor {
112   RSReductionDescriptor(const RSModuleDescriptor *module, uint32_t sig,
113                         uint32_t accum_data_size, llvm::StringRef name,
114                         llvm::StringRef init_name, llvm::StringRef accum_name,
115                         llvm::StringRef comb_name, llvm::StringRef outc_name,
116                         llvm::StringRef halter_name = ".")
117       : m_module(module), m_reduce_name(name), m_init_name(init_name),
118         m_accum_name(accum_name), m_comb_name(comb_name),
119         m_outc_name(outc_name), m_halter_name(halter_name) {
120     // TODO Check whether the combiner is an autogenerated name, and track
121     // this
122   }
123 
124   void Dump(Stream &strm) const;
125 
126   const RSModuleDescriptor *m_module;
127   ConstString m_reduce_name; // This is the name given to the general reduction
128                              // as a group as passed to pragma
129   // reduce(m_reduce_name). There is no kernel function with this name
130   ConstString m_init_name;  // The name of the initializer name. "." if no
131                             // initializer given
132   ConstString m_accum_name; // The accumulator function name. "." if not given
133   ConstString m_comb_name; // The name of the combiner function. If this was not
134                            // given, a name is generated by the
135                            // compiler. TODO
136   ConstString m_outc_name; // The name of the outconverter
137 
138   ConstString m_halter_name; // The name of the halter function. XXX This is not
139                              // yet specified by the RenderScript
140   // compiler or runtime, and its semantics and existence is still under
141   // discussion by the
142   // RenderScript Contributors
143   RSSlot m_accum_sig; // metatdata signature for this reduction (bitwise mask of
144                       // type information (see
145                       // libbcc/include/bcinfo/MetadataExtractor.h
146   uint32_t m_accum_data_size; // Data size of the accumulator function input
147   bool m_comb_name_generated; // Was the combiner name generated by the compiler
148 };
149 
150 class RSModuleDescriptor {
151   bool ParseExportForeachCount(llvm::StringRef *, size_t n_lines);
152 
153   bool ParseExportVarCount(llvm::StringRef *, size_t n_lines);
154 
155   bool ParseExportReduceCount(llvm::StringRef *, size_t n_lines);
156 
157   bool ParseBuildChecksum(llvm::StringRef *, size_t n_lines);
158 
159   bool ParsePragmaCount(llvm::StringRef *, size_t n_lines);
160 
161 public:
162   RSModuleDescriptor(const lldb::ModuleSP &module) : m_module(module) {}
163 
164   ~RSModuleDescriptor() = default;
165 
166   bool ParseRSInfo();
167 
168   void Dump(Stream &strm) const;
169 
170   const lldb::ModuleSP m_module;
171   std::vector<RSKernelDescriptor> m_kernels;
172   std::vector<RSGlobalDescriptor> m_globals;
173   std::vector<RSReductionDescriptor> m_reductions;
174   std::map<std::string, std::string> m_pragmas;
175   std::string m_resname;
176 };
177 
178 } // namespace lldb_renderscript
179 
180 class RenderScriptRuntime : public lldb_private::CPPLanguageRuntime {
181 public:
182   enum ModuleKind {
183     eModuleKindIgnored,
184     eModuleKindLibRS,
185     eModuleKindDriver,
186     eModuleKindImpl,
187     eModuleKindKernelObj
188   };
189 
190   ~RenderScriptRuntime() override;
191 
192   //------------------------------------------------------------------
193   // Static Functions
194   //------------------------------------------------------------------
195   static void Initialize();
196 
197   static void Terminate();
198 
199   static lldb_private::LanguageRuntime *
200   CreateInstance(Process *process, lldb::LanguageType language);
201 
202   static lldb::CommandObjectSP
203   GetCommandObject(CommandInterpreter &interpreter);
204 
205   static lldb_private::ConstString GetPluginNameStatic();
206 
207   static bool IsRenderScriptModule(const lldb::ModuleSP &module_sp);
208 
209   static ModuleKind GetModuleKind(const lldb::ModuleSP &module_sp);
210 
211   static void ModulesDidLoad(const lldb::ProcessSP &process_sp,
212                              const ModuleList &module_list);
213 
214   bool IsVTableName(const char *name) override;
215 
216   bool GetDynamicTypeAndAddress(ValueObject &in_value,
217                                 lldb::DynamicValueType use_dynamic,
218                                 TypeAndOrName &class_type_or_name,
219                                 Address &address,
220                                 Value::ValueType &value_type) override;
221 
222   TypeAndOrName FixUpDynamicType(const TypeAndOrName &type_and_or_name,
223                                  ValueObject &static_value) override;
224 
225   bool CouldHaveDynamicValue(ValueObject &in_value) override;
226 
227   lldb::BreakpointResolverSP CreateExceptionResolver(Breakpoint *bp,
228                                                      bool catch_bp,
229                                                      bool throw_bp) override;
230 
231   bool LoadModule(const lldb::ModuleSP &module_sp);
232 
233   void DumpModules(Stream &strm) const;
234 
235   void DumpContexts(Stream &strm) const;
236 
237   void DumpKernels(Stream &strm) const;
238 
239   bool DumpAllocation(Stream &strm, StackFrame *frame_ptr, const uint32_t id);
240 
241   void ListAllocations(Stream &strm, StackFrame *frame_ptr,
242                        const uint32_t index);
243 
244   bool RecomputeAllAllocations(Stream &strm, StackFrame *frame_ptr);
245 
246   bool PlaceBreakpointOnKernel(
247       lldb::TargetSP target, Stream &messages, const char *name,
248       const lldb_renderscript::RSCoordinate *coords = nullptr);
249 
250   void SetBreakAllKernels(bool do_break, lldb::TargetSP target);
251 
252   void Status(Stream &strm) const;
253 
254   void ModulesDidLoad(const ModuleList &module_list) override;
255 
256   bool LoadAllocation(Stream &strm, const uint32_t alloc_id,
257                       const char *filename, StackFrame *frame_ptr);
258 
259   bool SaveAllocation(Stream &strm, const uint32_t alloc_id,
260                       const char *filename, StackFrame *frame_ptr);
261 
262   void Update();
263 
264   void Initiate();
265 
266   //------------------------------------------------------------------
267   // PluginInterface protocol
268   //------------------------------------------------------------------
269   lldb_private::ConstString GetPluginName() override;
270 
271   uint32_t GetPluginVersion() override;
272 
273   static bool GetKernelCoordinate(lldb_renderscript::RSCoordinate &coord,
274                                   Thread *thread_ptr);
275 
276 protected:
277   struct ScriptDetails;
278   struct AllocationDetails;
279   struct Element;
280 
281   void InitSearchFilter(lldb::TargetSP target) {
282     if (!m_filtersp)
283       m_filtersp.reset(new SearchFilterForUnconstrainedSearches(target));
284   }
285 
286   void FixupScriptDetails(lldb_renderscript::RSModuleDescriptorSP rsmodule_sp);
287 
288   void LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind);
289 
290   bool RefreshAllocation(AllocationDetails *alloc, StackFrame *frame_ptr);
291 
292   bool EvalRSExpression(const char *expression, StackFrame *frame_ptr,
293                         uint64_t *result);
294 
295   lldb::BreakpointSP CreateKernelBreakpoint(const ConstString &name);
296 
297   void BreakOnModuleKernels(
298       const lldb_renderscript::RSModuleDescriptorSP rsmodule_sp);
299 
300   struct RuntimeHook;
301   typedef void (RenderScriptRuntime::*CaptureStateFn)(
302       RuntimeHook *hook_info,
303       ExecutionContext &context); // Please do this!
304 
305   struct HookDefn {
306     const char *name;
307     const char *symbol_name_m32; // mangled name for the 32 bit architectures
308     const char *symbol_name_m64; // mangled name for the 64 bit archs
309     uint32_t version;
310     ModuleKind kind;
311     CaptureStateFn grabber;
312   };
313 
314   struct RuntimeHook {
315     lldb::addr_t address;
316     const HookDefn *defn;
317     lldb::BreakpointSP bp_sp;
318   };
319 
320   typedef std::shared_ptr<RuntimeHook> RuntimeHookSP;
321 
322   lldb::ModuleSP m_libRS;
323   lldb::ModuleSP m_libRSDriver;
324   lldb::ModuleSP m_libRSCpuRef;
325   std::vector<lldb_renderscript::RSModuleDescriptorSP> m_rsmodules;
326 
327   std::vector<std::unique_ptr<ScriptDetails>> m_scripts;
328   std::vector<std::unique_ptr<AllocationDetails>> m_allocations;
329 
330   std::map<lldb::addr_t, lldb_renderscript::RSModuleDescriptorSP>
331       m_scriptMappings;
332   std::map<lldb::addr_t, RuntimeHookSP> m_runtimeHooks;
333   std::map<lldb::user_id_t, std::unique_ptr<lldb_renderscript::RSCoordinate>>
334       m_conditional_breaks;
335 
336   lldb::SearchFilterSP
337       m_filtersp; // Needed to create breakpoints through Target API
338 
339   bool m_initiated;
340   bool m_debuggerPresentFlagged;
341   bool m_breakAllKernels;
342   static const HookDefn s_runtimeHookDefns[];
343   static const size_t s_runtimeHookCount;
344   LLVMUserExpression::IRPasses *m_ir_passes;
345 
346 private:
347   RenderScriptRuntime(Process *process); // Call CreateInstance instead.
348 
349   static bool HookCallback(void *baton, StoppointCallbackContext *ctx,
350                            lldb::user_id_t break_id,
351                            lldb::user_id_t break_loc_id);
352 
353   static bool KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx,
354                                   lldb::user_id_t break_id,
355                                   lldb::user_id_t break_loc_id);
356 
357   void HookCallback(RuntimeHook *hook_info, ExecutionContext &context);
358 
359   void CaptureScriptInit(RuntimeHook *hook_info, ExecutionContext &context);
360 
361   void CaptureAllocationInit(RuntimeHook *hook_info, ExecutionContext &context);
362 
363   void CaptureAllocationDestroy(RuntimeHook *hook_info,
364                                 ExecutionContext &context);
365 
366   void CaptureSetGlobalVar(RuntimeHook *hook_info, ExecutionContext &context);
367 
368   void CaptureScriptInvokeForEachMulti(RuntimeHook *hook_info,
369                                        ExecutionContext &context);
370 
371   AllocationDetails *FindAllocByID(Stream &strm, const uint32_t alloc_id);
372 
373   std::shared_ptr<uint8_t> GetAllocationData(AllocationDetails *alloc,
374                                              StackFrame *frame_ptr);
375 
376   void SetElementSize(Element &elem);
377 
378   static bool GetFrameVarAsUnsigned(const lldb::StackFrameSP,
379                                     const char *var_name, uint64_t &val);
380 
381   void FindStructTypeName(Element &elem, StackFrame *frame_ptr);
382 
383   size_t PopulateElementHeaders(const std::shared_ptr<uint8_t> header_buffer,
384                                 size_t offset, const Element &elem);
385 
386   size_t CalculateElementHeaderSize(const Element &elem);
387 
388   void SetConditional(lldb::BreakpointSP bp, lldb_private::Stream &messages,
389                       const lldb_renderscript::RSCoordinate &coord);
390   //
391   // Helper functions for jitting the runtime
392   //
393 
394   bool JITDataPointer(AllocationDetails *alloc, StackFrame *frame_ptr,
395                       uint32_t x = 0, uint32_t y = 0, uint32_t z = 0);
396 
397   bool JITTypePointer(AllocationDetails *alloc, StackFrame *frame_ptr);
398 
399   bool JITTypePacked(AllocationDetails *alloc, StackFrame *frame_ptr);
400 
401   bool JITElementPacked(Element &elem, const lldb::addr_t context,
402                         StackFrame *frame_ptr);
403 
404   bool JITAllocationSize(AllocationDetails *alloc, StackFrame *frame_ptr);
405 
406   bool JITSubelements(Element &elem, const lldb::addr_t context,
407                       StackFrame *frame_ptr);
408 
409   bool JITAllocationStride(AllocationDetails *alloc, StackFrame *frame_ptr);
410 
411   // Search for a script detail object using a target address.
412   // If a script does not currently exist this function will return nullptr.
413   // If 'create' is true and there is no previous script with this address,
414   // then a new Script detail object will be created for this address and
415   // returned.
416   ScriptDetails *LookUpScript(lldb::addr_t address, bool create);
417 
418   // Search for a previously saved allocation detail object using a target
419   // address.
420   // If an allocation does not exist for this address then nullptr will be
421   // returned.
422   AllocationDetails *LookUpAllocation(lldb::addr_t address);
423 
424   // Creates a new allocation with the specified address assigning a new ID and
425   // removes
426   // any previous stored allocation which has the same address.
427   AllocationDetails *CreateAllocation(lldb::addr_t address);
428 
429   bool GetOverrideExprOptions(clang::TargetOptions &prototype) override;
430 
431   bool GetIRPasses(LLVMUserExpression::IRPasses &passes) override;
432 };
433 
434 } // namespace lldb_private
435 
436 #endif // liblldb_RenderScriptRuntime_h_
437