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 // Project includes
23 #include "lldb/lldb-private.h"
24 #include "lldb/Target/LanguageRuntime.h"
25 #include "lldb/Target/CPPLanguageRuntime.h"
26 #include "lldb/Core/Module.h"
27 
28 namespace lldb_private {
29 namespace lldb_renderscript {
30 
31 typedef uint32_t RSSlot;
32 class RSModuleDescriptor;
33 struct RSGlobalDescriptor;
34 struct RSKernelDescriptor;
35 
36 typedef std::shared_ptr<RSModuleDescriptor> RSModuleDescriptorSP;
37 typedef std::shared_ptr<RSGlobalDescriptor> RSGlobalDescriptorSP;
38 typedef std::shared_ptr<RSKernelDescriptor> RSKernelDescriptorSP;
39 
40 // Breakpoint Resolvers decide where a breakpoint is placed,
41 // so having our own allows us to limit the search scope to RS kernel modules.
42 // As well as check for .expand kernels as a fallback.
43 class RSBreakpointResolver : public BreakpointResolver
44 {
45 public:
46     RSBreakpointResolver(Breakpoint *bkpt, ConstString name):
47                          BreakpointResolver (bkpt, BreakpointResolver::NameResolver),
48                          m_kernel_name(name)
49     {
50     }
51 
52     void
53     GetDescription(Stream *strm) override
54     {
55         if (strm)
56             strm->Printf("RenderScript kernel breakpoint for '%s'", m_kernel_name.AsCString());
57     }
58 
59     void
60     Dump(Stream *s) const override
61     {
62     }
63 
64     Searcher::CallbackReturn
65     SearchCallback(SearchFilter &filter,
66                    SymbolContext &context,
67                    Address *addr,
68                    bool containing) override;
69 
70     Searcher::Depth
71     GetDepth() override
72     {
73         return Searcher::eDepthModule;
74     }
75 
76     lldb::BreakpointResolverSP
77     CopyForBreakpoint(Breakpoint &breakpoint) override
78     {
79         lldb::BreakpointResolverSP ret_sp(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 {
89 public:
90     RSKernelDescriptor(const RSModuleDescriptor *module, const char *name, uint32_t slot)
91         : m_module(module)
92         , m_name(name)
93         , m_slot(slot)
94     {
95     }
96 
97     void Dump(Stream &strm) const;
98 
99     const RSModuleDescriptor *m_module;
100     ConstString m_name;
101     RSSlot m_slot;
102 };
103 
104 struct RSGlobalDescriptor
105 {
106 public:
107     RSGlobalDescriptor(const RSModuleDescriptor *module, const char *name )
108         : m_module(module)
109         , m_name(name)
110     {
111     }
112 
113     void Dump(Stream &strm) const;
114 
115     const RSModuleDescriptor *m_module;
116     ConstString m_name;
117 };
118 
119 class RSModuleDescriptor
120 {
121 public:
122     RSModuleDescriptor(const lldb::ModuleSP &module)
123         : m_module(module)
124     {
125     }
126 
127     ~RSModuleDescriptor() = default;
128 
129     bool ParseRSInfo();
130 
131     void Dump(Stream &strm) const;
132 
133     const lldb::ModuleSP m_module;
134     std::vector<RSKernelDescriptor> m_kernels;
135     std::vector<RSGlobalDescriptor> m_globals;
136     std::map<std::string, std::string> m_pragmas;
137     std::string m_resname;
138 };
139 
140 } // namespace lldb_renderscript
141 
142 class RenderScriptRuntime : public lldb_private::CPPLanguageRuntime
143 {
144 public:
145     enum ModuleKind
146     {
147         eModuleKindIgnored,
148         eModuleKindLibRS,
149         eModuleKindDriver,
150         eModuleKindImpl,
151         eModuleKindKernelObj
152     };
153 
154     ~RenderScriptRuntime() override;
155 
156     //------------------------------------------------------------------
157     // Static Functions
158     //------------------------------------------------------------------
159     static void Initialize();
160 
161     static void Terminate();
162 
163     static lldb_private::LanguageRuntime *CreateInstance(Process *process, lldb::LanguageType language);
164 
165     static lldb::CommandObjectSP GetCommandObject(CommandInterpreter& interpreter);
166 
167     static lldb_private::ConstString GetPluginNameStatic();
168 
169     static bool IsRenderScriptModule(const lldb::ModuleSP &module_sp);
170 
171     static ModuleKind GetModuleKind(const lldb::ModuleSP &module_sp);
172 
173     static void ModulesDidLoad(const lldb::ProcessSP& process_sp, const ModuleList &module_list );
174 
175     bool IsVTableName(const char *name) override;
176 
177     bool GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic,
178                                   TypeAndOrName &class_type_or_name, Address &address,
179                                   Value::ValueType &value_type) override;
180 
181     TypeAndOrName
182     FixUpDynamicType(const TypeAndOrName& type_and_or_name,
183                      ValueObject& static_value) override;
184 
185     bool CouldHaveDynamicValue(ValueObject &in_value) override;
186 
187     lldb::BreakpointResolverSP CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp, bool throw_bp) override;
188 
189     bool LoadModule(const lldb::ModuleSP &module_sp);
190 
191     bool ProbeModules(const ModuleList module_list);
192 
193     void DumpModules(Stream &strm) const;
194 
195     void DumpContexts(Stream &strm) const;
196 
197     void DumpKernels(Stream &strm) const;
198 
199     bool DumpAllocation(Stream &strm, StackFrame* frame_ptr, const uint32_t id);
200 
201     void ListAllocations(Stream &strm, StackFrame* frame_ptr, bool recompute);
202 
203     void PlaceBreakpointOnKernel(Stream &strm, const char *name, const std::array<int,3> coords,
204                                  Error &error, lldb::TargetSP target);
205 
206     void SetBreakAllKernels(bool do_break, lldb::TargetSP target);
207 
208     void Status(Stream &strm) const;
209 
210     void ModulesDidLoad(const ModuleList &module_list) override;
211 
212     bool LoadAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr);
213 
214     bool SaveAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr);
215 
216     void Update();
217 
218     void Initiate();
219 
220     //------------------------------------------------------------------
221     // PluginInterface protocol
222     //------------------------------------------------------------------
223     lldb_private::ConstString GetPluginName() override;
224 
225     uint32_t GetPluginVersion() override;
226 
227 protected:
228     struct ScriptDetails;
229     struct AllocationDetails;
230     struct Element;
231 
232     void InitSearchFilter(lldb::TargetSP target)
233     {
234         if (!m_filtersp)
235             m_filtersp.reset(new SearchFilterForUnconstrainedSearches(target));
236     }
237 
238     void FixupScriptDetails(lldb_renderscript::RSModuleDescriptorSP rsmodule_sp);
239 
240     void LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind);
241 
242     bool RefreshAllocation(AllocationDetails* allocation, StackFrame* frame_ptr);
243 
244     bool EvalRSExpression(const char* expression, StackFrame* frame_ptr, uint64_t* result);
245 
246     lldb::BreakpointSP CreateKernelBreakpoint(const ConstString& name);
247 
248     void BreakOnModuleKernels(const lldb_renderscript::RSModuleDescriptorSP rsmodule_sp);
249 
250     struct RuntimeHook;
251     typedef void (RenderScriptRuntime::*CaptureStateFn)(RuntimeHook* hook_info, ExecutionContext &context);  // Please do this!
252 
253     struct HookDefn
254     {
255         const char * name;
256         const char * symbol_name_m32; // mangled name for the 32 bit architectures
257         const char * symbol_name_m64; // mangled name for the 64 bit archs
258         uint32_t version;
259         ModuleKind kind;
260         CaptureStateFn grabber;
261     };
262 
263     struct RuntimeHook
264     {
265         lldb::addr_t address;
266         const HookDefn  *defn;
267         lldb::BreakpointSP bp_sp;
268     };
269 
270     typedef std::shared_ptr<RuntimeHook> RuntimeHookSP;
271 
272     lldb::ModuleSP m_libRS;
273     lldb::ModuleSP m_libRSDriver;
274     lldb::ModuleSP m_libRSCpuRef;
275     std::vector<lldb_renderscript::RSModuleDescriptorSP> m_rsmodules;
276 
277     std::vector<std::unique_ptr<ScriptDetails>> m_scripts;
278     std::vector<std::unique_ptr<AllocationDetails>> m_allocations;
279 
280     std::map<lldb::addr_t, lldb_renderscript::RSModuleDescriptorSP> m_scriptMappings;
281     std::map<lldb::addr_t, RuntimeHookSP> m_runtimeHooks;
282     std::map<lldb::user_id_t, std::shared_ptr<int>> m_conditional_breaks;
283 
284     lldb::SearchFilterSP m_filtersp; // Needed to create breakpoints through Target API
285 
286     bool m_initiated;
287     bool m_debuggerPresentFlagged;
288     bool m_breakAllKernels;
289     static const HookDefn s_runtimeHookDefns[];
290     static const size_t s_runtimeHookCount;
291 
292 private:
293     // Used to index expression format strings
294     enum ExpressionStrings
295     {
296        eExprGetOffsetPtr = 0,
297        eExprAllocGetType,
298        eExprTypeDimX,
299        eExprTypeDimY,
300        eExprTypeDimZ,
301        eExprTypeElemPtr,
302        eExprElementType,
303        eExprElementKind,
304        eExprElementVec,
305        eExprElementFieldCount,
306        eExprSubelementsId,
307        eExprSubelementsName,
308        eExprSubelementsArrSize
309     };
310 
311     RenderScriptRuntime(Process *process); // Call CreateInstance instead.
312 
313     static bool HookCallback(void *baton, StoppointCallbackContext *ctx, lldb::user_id_t break_id,
314                              lldb::user_id_t break_loc_id);
315 
316     static bool KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx,
317                                     lldb::user_id_t break_id, lldb::user_id_t break_loc_id);
318 
319     void HookCallback(RuntimeHook* hook_info, ExecutionContext& context);
320 
321     bool GetArgSimple(ExecutionContext& context, uint32_t arg, uint64_t* data);
322 
323     void CaptureScriptInit1(RuntimeHook* hook_info, ExecutionContext& context);
324     void CaptureAllocationInit1(RuntimeHook* hook_info, ExecutionContext& context);
325     void CaptureAllocationDestroy(RuntimeHook* hook_info, ExecutionContext& context);
326     void CaptureSetGlobalVar1(RuntimeHook* hook_info, ExecutionContext& context);
327 
328     AllocationDetails* FindAllocByID(Stream &strm, const uint32_t alloc_id);
329     std::shared_ptr<uint8_t> GetAllocationData(AllocationDetails* allocation, StackFrame* frame_ptr);
330     void SetElementSize(Element& elem);
331     static bool GetFrameVarAsUnsigned(const lldb::StackFrameSP, const char* var_name, uint64_t& val);
332     void FindStructTypeName(Element& elem, StackFrame* frame_ptr);
333 
334     size_t PopulateElementHeaders(const std::shared_ptr<uint8_t> header_buffer, size_t offset, const Element& elem);
335     size_t CalculateElementHeaderSize(const Element& elem);
336 
337     //
338     // Helper functions for jitting the runtime
339     //
340     const char* JITTemplate(ExpressionStrings e);
341 
342     bool JITDataPointer(AllocationDetails* allocation, StackFrame* frame_ptr,
343                         unsigned int x = 0, unsigned int y = 0, unsigned int z = 0);
344 
345     bool JITTypePointer(AllocationDetails* allocation, StackFrame* frame_ptr);
346 
347     bool JITTypePacked(AllocationDetails* allocation, StackFrame* frame_ptr);
348 
349     bool JITElementPacked(Element& elem, const lldb::addr_t context, StackFrame* frame_ptr);
350 
351     bool JITAllocationSize(AllocationDetails* allocation, StackFrame* frame_ptr);
352 
353     bool JITSubelements(Element& elem, const lldb::addr_t context, StackFrame* frame_ptr);
354 
355     bool JITAllocationStride(AllocationDetails* allocation, StackFrame* frame_ptr);
356 
357     // Search for a script detail object using a target address.
358     // If a script does not currently exist this function will return nullptr.
359     // If 'create' is true and there is no previous script with this address,
360     // then a new Script detail object will be created for this address and returned.
361     ScriptDetails* LookUpScript(lldb::addr_t address, bool create);
362 
363     // Search for a previously saved allocation detail object using a target address.
364     // If an allocation does not exist for this address then nullptr will be returned.
365     // If 'create' is true and there is no previous allocation then a new allocation
366     // detail object will be created for this address and returned.
367     AllocationDetails* LookUpAllocation(lldb::addr_t address, bool create);
368 };
369 
370 } // namespace lldb_private
371 
372 #endif // liblldb_RenderScriptRuntime_h_
373