1 //===-- ObjCLanguageRuntime.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 LLDB_SOURCE_PLUGINS_LANGUAGERUNTIME_OBJC_OBJCLANGUAGERUNTIME_H
10 #define LLDB_SOURCE_PLUGINS_LANGUAGERUNTIME_OBJC_OBJCLANGUAGERUNTIME_H
11 
12 #include <functional>
13 #include <map>
14 #include <memory>
15 #include <unordered_set>
16 
17 #include "llvm/Support/Casting.h"
18 
19 #include "lldb/Breakpoint/BreakpointPrecondition.h"
20 #include "lldb/Core/PluginInterface.h"
21 #include "lldb/Core/ThreadSafeDenseMap.h"
22 #include "lldb/Symbol/CompilerType.h"
23 #include "lldb/Symbol/Type.h"
24 #include "lldb/Target/LanguageRuntime.h"
25 #include "lldb/lldb-private.h"
26 
27 class CommandObjectObjC_ClassTable_Dump;
28 
29 namespace lldb_private {
30 
31 class TypeSystemClang;
32 class UtilityFunction;
33 
34 class ObjCLanguageRuntime : public LanguageRuntime {
35 public:
36   enum class ObjCRuntimeVersions {
37     eObjC_VersionUnknown = 0,
38     eAppleObjC_V1 = 1,
39     eAppleObjC_V2 = 2
40   };
41 
42   typedef lldb::addr_t ObjCISA;
43 
44   class ClassDescriptor;
45   typedef std::shared_ptr<ClassDescriptor> ClassDescriptorSP;
46 
47   // the information that we want to support retrieving from an ObjC class this
48   // needs to be pure virtual since there are at least 2 different
49   // implementations of the runtime, and more might come
50   class ClassDescriptor {
51   public:
52     ClassDescriptor()
53         : m_is_kvo(eLazyBoolCalculate), m_is_cf(eLazyBoolCalculate),
54           m_type_wp() {}
55 
56     virtual ~ClassDescriptor() = default;
57 
58     virtual ConstString GetClassName() = 0;
59 
60     virtual ClassDescriptorSP GetSuperclass() = 0;
61 
62     virtual ClassDescriptorSP GetMetaclass() const = 0;
63 
64     // virtual if any implementation has some other version-specific rules but
65     // for the known v1/v2 this is all that needs to be done
66     virtual bool IsKVO() {
67       if (m_is_kvo == eLazyBoolCalculate) {
68         const char *class_name = GetClassName().AsCString();
69         if (class_name && *class_name)
70           m_is_kvo =
71               (LazyBool)(strstr(class_name, "NSKVONotifying_") == class_name);
72       }
73       return (m_is_kvo == eLazyBoolYes);
74     }
75 
76     // virtual if any implementation has some other version-specific rules but
77     // for the known v1/v2 this is all that needs to be done
78     virtual bool IsCFType() {
79       if (m_is_cf == eLazyBoolCalculate) {
80         const char *class_name = GetClassName().AsCString();
81         if (class_name && *class_name)
82           m_is_cf = (LazyBool)(strcmp(class_name, "__NSCFType") == 0 ||
83                                strcmp(class_name, "NSCFType") == 0);
84       }
85       return (m_is_cf == eLazyBoolYes);
86     }
87 
88     virtual bool IsValid() = 0;
89 
90     virtual bool GetTaggedPointerInfo(uint64_t *info_bits = nullptr,
91                                       uint64_t *value_bits = nullptr,
92                                       uint64_t *payload = nullptr) = 0;
93 
94     virtual uint64_t GetInstanceSize() = 0;
95 
96     // use to implement version-specific additional constraints on pointers
97     virtual bool CheckPointer(lldb::addr_t value, uint32_t ptr_size) const {
98       return true;
99     }
100 
101     virtual ObjCISA GetISA() = 0;
102 
103     // This should return true iff the interface could be completed
104     virtual bool
105     Describe(std::function<void(ObjCISA)> const &superclass_func,
106              std::function<bool(const char *, const char *)> const
107                  &instance_method_func,
108              std::function<bool(const char *, const char *)> const
109                  &class_method_func,
110              std::function<bool(const char *, const char *, lldb::addr_t,
111                                 uint64_t)> const &ivar_func) const {
112       return false;
113     }
114 
115     lldb::TypeSP GetType() { return m_type_wp.lock(); }
116 
117     void SetType(const lldb::TypeSP &type_sp) { m_type_wp = type_sp; }
118 
119     struct iVarDescriptor {
120       ConstString m_name;
121       CompilerType m_type;
122       uint64_t m_size;
123       int32_t m_offset;
124     };
125 
126     virtual size_t GetNumIVars() { return 0; }
127 
128     virtual iVarDescriptor GetIVarAtIndex(size_t idx) {
129       return iVarDescriptor();
130     }
131 
132   protected:
133     bool IsPointerValid(lldb::addr_t value, uint32_t ptr_size,
134                         bool allow_NULLs = false, bool allow_tagged = false,
135                         bool check_version_specific = false) const;
136 
137   private:
138     LazyBool m_is_kvo;
139     LazyBool m_is_cf;
140     lldb::TypeWP m_type_wp;
141   };
142 
143   class EncodingToType {
144   public:
145     virtual ~EncodingToType();
146 
147     virtual CompilerType RealizeType(TypeSystemClang &ast_ctx, const char *name,
148                                      bool for_expression) = 0;
149     virtual CompilerType RealizeType(const char *name, bool for_expression);
150 
151   protected:
152     std::unique_ptr<TypeSystemClang> m_scratch_ast_ctx_up;
153   };
154 
155   class ObjCExceptionPrecondition : public BreakpointPrecondition {
156   public:
157     ObjCExceptionPrecondition();
158 
159     ~ObjCExceptionPrecondition() override = default;
160 
161     bool EvaluatePrecondition(StoppointCallbackContext &context) override;
162     void GetDescription(Stream &stream, lldb::DescriptionLevel level) override;
163     Status ConfigurePrecondition(Args &args) override;
164 
165   protected:
166     void AddClassName(const char *class_name);
167 
168   private:
169     std::unordered_set<std::string> m_class_names;
170   };
171 
172   static lldb::BreakpointPreconditionSP
173   GetBreakpointExceptionPrecondition(lldb::LanguageType language,
174                                      bool throw_bp);
175 
176   class TaggedPointerVendor {
177   public:
178     virtual ~TaggedPointerVendor() = default;
179 
180     virtual bool IsPossibleTaggedPointer(lldb::addr_t ptr) = 0;
181 
182     virtual ObjCLanguageRuntime::ClassDescriptorSP
183     GetClassDescriptor(lldb::addr_t ptr) = 0;
184 
185   protected:
186     TaggedPointerVendor() = default;
187 
188   private:
189     TaggedPointerVendor(const TaggedPointerVendor &) = delete;
190     const TaggedPointerVendor &operator=(const TaggedPointerVendor &) = delete;
191   };
192 
193   ~ObjCLanguageRuntime() override;
194 
195   static char ID;
196 
197   bool isA(const void *ClassID) const override {
198     return ClassID == &ID || LanguageRuntime::isA(ClassID);
199   }
200 
201   static bool classof(const LanguageRuntime *runtime) {
202     return runtime->isA(&ID);
203   }
204 
205   static ObjCLanguageRuntime *Get(Process &process) {
206     return llvm::cast_or_null<ObjCLanguageRuntime>(
207         process.GetLanguageRuntime(lldb::eLanguageTypeObjC));
208   }
209 
210   virtual TaggedPointerVendor *GetTaggedPointerVendor() { return nullptr; }
211 
212   typedef std::shared_ptr<EncodingToType> EncodingToTypeSP;
213 
214   virtual EncodingToTypeSP GetEncodingToType();
215 
216   virtual ClassDescriptorSP GetClassDescriptor(ValueObject &in_value);
217 
218   ClassDescriptorSP GetNonKVOClassDescriptor(ValueObject &in_value);
219 
220   virtual ClassDescriptorSP
221   GetClassDescriptorFromClassName(ConstString class_name);
222 
223   virtual ClassDescriptorSP GetClassDescriptorFromISA(ObjCISA isa);
224 
225   ClassDescriptorSP GetNonKVOClassDescriptor(ObjCISA isa);
226 
227   lldb::LanguageType GetLanguageType() const override {
228     return lldb::eLanguageTypeObjC;
229   }
230 
231   virtual bool IsModuleObjCLibrary(const lldb::ModuleSP &module_sp) = 0;
232 
233   virtual bool ReadObjCLibrary(const lldb::ModuleSP &module_sp) = 0;
234 
235   virtual bool HasReadObjCLibrary() = 0;
236 
237   lldb::addr_t LookupInMethodCache(lldb::addr_t class_addr, lldb::addr_t sel);
238 
239   void AddToMethodCache(lldb::addr_t class_addr, lldb::addr_t sel,
240                         lldb::addr_t impl_addr);
241 
242   TypeAndOrName LookupInClassNameCache(lldb::addr_t class_addr);
243 
244   void AddToClassNameCache(lldb::addr_t class_addr, const char *name,
245                            lldb::TypeSP type_sp);
246 
247   void AddToClassNameCache(lldb::addr_t class_addr,
248                            const TypeAndOrName &class_or_type_name);
249 
250   lldb::TypeSP LookupInCompleteClassCache(ConstString &name);
251 
252   llvm::Optional<CompilerType> GetRuntimeType(CompilerType base_type) override;
253 
254   virtual UtilityFunction *CreateObjectChecker(const char *) = 0;
255 
256   virtual ObjCRuntimeVersions GetRuntimeVersion() const {
257     return ObjCRuntimeVersions::eObjC_VersionUnknown;
258   }
259 
260   bool IsValidISA(ObjCISA isa) {
261     UpdateISAToDescriptorMap();
262     return m_isa_to_descriptor.count(isa) > 0;
263   }
264 
265   virtual void UpdateISAToDescriptorMapIfNeeded() = 0;
266 
267   void UpdateISAToDescriptorMap() {
268     if (m_process && m_process->GetStopID() != m_isa_to_descriptor_stop_id) {
269       UpdateISAToDescriptorMapIfNeeded();
270     }
271   }
272 
273   virtual ObjCISA GetISA(ConstString name);
274 
275   virtual ObjCISA GetParentClass(ObjCISA isa);
276 
277   // Finds the byte offset of the child_type ivar in parent_type.  If it can't
278   // find the offset, returns LLDB_INVALID_IVAR_OFFSET.
279 
280   virtual size_t GetByteOffsetForIvar(CompilerType &parent_qual_type,
281                                       const char *ivar_name);
282 
283   bool HasNewLiteralsAndIndexing() {
284     if (m_has_new_literals_and_indexing == eLazyBoolCalculate) {
285       if (CalculateHasNewLiteralsAndIndexing())
286         m_has_new_literals_and_indexing = eLazyBoolYes;
287       else
288         m_has_new_literals_and_indexing = eLazyBoolNo;
289     }
290 
291     return (m_has_new_literals_and_indexing == eLazyBoolYes);
292   }
293 
294   void SymbolsDidLoad(const ModuleList &module_list) override {
295     m_negative_complete_class_cache.clear();
296   }
297 
298   bool GetTypeBitSize(const CompilerType &compiler_type,
299                       uint64_t &size) override;
300 
301   /// Check whether the name is "self" or "_cmd" and should show up in
302   /// "frame variable".
303   bool IsAllowedRuntimeValue(ConstString name) override;
304 
305 protected:
306   // Classes that inherit from ObjCLanguageRuntime can see and modify these
307   ObjCLanguageRuntime(Process *process);
308 
309   virtual bool CalculateHasNewLiteralsAndIndexing() { return false; }
310 
311   bool ISAIsCached(ObjCISA isa) const {
312     return m_isa_to_descriptor.find(isa) != m_isa_to_descriptor.end();
313   }
314 
315   bool AddClass(ObjCISA isa, const ClassDescriptorSP &descriptor_sp) {
316     if (isa != 0) {
317       m_isa_to_descriptor[isa] = descriptor_sp;
318       return true;
319     }
320     return false;
321   }
322 
323   bool AddClass(ObjCISA isa, const ClassDescriptorSP &descriptor_sp,
324                 const char *class_name);
325 
326   bool AddClass(ObjCISA isa, const ClassDescriptorSP &descriptor_sp,
327                 uint32_t class_name_hash) {
328     if (isa != 0) {
329       m_isa_to_descriptor[isa] = descriptor_sp;
330       m_hash_to_isa_map.insert(std::make_pair(class_name_hash, isa));
331       return true;
332     }
333     return false;
334   }
335 
336 private:
337   // We keep a map of <Class,Selector>->Implementation so we don't have to call
338   // the resolver function over and over.
339 
340   // FIXME: We need to watch for the loading of Protocols, and flush the cache
341   // for any
342   // class that we see so changed.
343 
344   struct ClassAndSel {
345     ClassAndSel() {
346       sel_addr = LLDB_INVALID_ADDRESS;
347       class_addr = LLDB_INVALID_ADDRESS;
348     }
349 
350     ClassAndSel(lldb::addr_t in_sel_addr, lldb::addr_t in_class_addr)
351         : class_addr(in_class_addr), sel_addr(in_sel_addr) {}
352 
353     bool operator==(const ClassAndSel &rhs) {
354       if (class_addr == rhs.class_addr && sel_addr == rhs.sel_addr)
355         return true;
356       else
357         return false;
358     }
359 
360     bool operator<(const ClassAndSel &rhs) const {
361       if (class_addr < rhs.class_addr)
362         return true;
363       else if (class_addr > rhs.class_addr)
364         return false;
365       else {
366         if (sel_addr < rhs.sel_addr)
367           return true;
368         else
369           return false;
370       }
371     }
372 
373     lldb::addr_t class_addr;
374     lldb::addr_t sel_addr;
375   };
376 
377   typedef std::map<ClassAndSel, lldb::addr_t> MsgImplMap;
378   typedef std::map<ObjCISA, ClassDescriptorSP> ISAToDescriptorMap;
379   typedef std::multimap<uint32_t, ObjCISA> HashToISAMap;
380   typedef ISAToDescriptorMap::iterator ISAToDescriptorIterator;
381   typedef HashToISAMap::iterator HashToISAIterator;
382   typedef ThreadSafeDenseMap<void *, uint64_t> TypeSizeCache;
383 
384   MsgImplMap m_impl_cache;
385   LazyBool m_has_new_literals_and_indexing;
386   ISAToDescriptorMap m_isa_to_descriptor;
387   HashToISAMap m_hash_to_isa_map;
388   TypeSizeCache m_type_size_cache;
389 
390 protected:
391   uint32_t m_isa_to_descriptor_stop_id;
392 
393   typedef std::map<ConstString, lldb::TypeWP> CompleteClassMap;
394   CompleteClassMap m_complete_class_cache;
395 
396   struct ConstStringSetHelpers {
397     size_t operator()(ConstString arg) const // for hashing
398     {
399       return (size_t)arg.GetCString();
400     }
401     bool operator()(ConstString arg1,
402                     ConstString arg2) const // for equality
403     {
404       return arg1.operator==(arg2);
405     }
406   };
407   typedef std::unordered_set<ConstString, ConstStringSetHelpers,
408                              ConstStringSetHelpers>
409       CompleteClassSet;
410   CompleteClassSet m_negative_complete_class_cache;
411 
412   ISAToDescriptorIterator GetDescriptorIterator(ConstString name);
413 
414   friend class ::CommandObjectObjC_ClassTable_Dump;
415 
416   std::pair<ISAToDescriptorIterator, ISAToDescriptorIterator>
417   GetDescriptorIteratorPair(bool update_if_needed = true);
418 
419   void ReadObjCLibraryIfNeeded(const ModuleList &module_list);
420 
421   ObjCLanguageRuntime(const ObjCLanguageRuntime &) = delete;
422   const ObjCLanguageRuntime &operator=(const ObjCLanguageRuntime &) = delete;
423 };
424 
425 } // namespace lldb_private
426 
427 #endif // LLDB_SOURCE_PLUGINS_LANGUAGERUNTIME_OBJC_OBJCLANGUAGERUNTIME_H
428