1 //===-- ObjCLanguageRuntime.cpp -------------------------------------------===//
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 #include "clang/AST/Type.h"
9 
10 #include "ObjCLanguageRuntime.h"
11 
12 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
13 #include "lldb/Core/MappedHash.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/PluginManager.h"
16 #include "lldb/Core/ValueObject.h"
17 #include "lldb/Symbol/SymbolContext.h"
18 #include "lldb/Symbol/SymbolFile.h"
19 #include "lldb/Symbol/Type.h"
20 #include "lldb/Symbol/TypeList.h"
21 #include "lldb/Symbol/Variable.h"
22 #include "lldb/Target/ABI.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Utility/LLDBLog.h"
25 #include "lldb/Utility/Log.h"
26 #include "lldb/Utility/Timer.h"
27 
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/Support/DJB.h"
30 #include <optional>
31 
32 using namespace lldb;
33 using namespace lldb_private;
34 
35 char ObjCLanguageRuntime::ID = 0;
36 
37 // Destructor
38 ObjCLanguageRuntime::~ObjCLanguageRuntime() = default;
39 
40 ObjCLanguageRuntime::ObjCLanguageRuntime(Process *process)
41     : LanguageRuntime(process), m_impl_cache(), m_impl_str_cache(),
42       m_has_new_literals_and_indexing(eLazyBoolCalculate),
43       m_isa_to_descriptor(), m_hash_to_isa_map(), m_type_size_cache(),
44       m_isa_to_descriptor_stop_id(UINT32_MAX), m_complete_class_cache(),
45       m_negative_complete_class_cache() {}
46 
47 bool ObjCLanguageRuntime::IsAllowedRuntimeValue(ConstString name) {
48   static ConstString g_self = ConstString("self");
49   static ConstString g_cmd = ConstString("_cmd");
50   return name == g_self || name == g_cmd;
51 }
52 
53 bool ObjCLanguageRuntime::AddClass(ObjCISA isa,
54                                    const ClassDescriptorSP &descriptor_sp,
55                                    const char *class_name) {
56   if (isa != 0) {
57     m_isa_to_descriptor[isa] = descriptor_sp;
58     // class_name is assumed to be valid
59     m_hash_to_isa_map.insert(std::make_pair(llvm::djbHash(class_name), isa));
60     return true;
61   }
62   return false;
63 }
64 
65 void ObjCLanguageRuntime::AddToMethodCache(lldb::addr_t class_addr,
66                                            lldb::addr_t selector,
67                                            lldb::addr_t impl_addr) {
68   Log *log = GetLog(LLDBLog::Step);
69   if (log) {
70     LLDB_LOGF(log,
71               "Caching: class 0x%" PRIx64 " selector 0x%" PRIx64
72               " implementation 0x%" PRIx64 ".",
73               class_addr, selector, impl_addr);
74   }
75   m_impl_cache.insert(std::pair<ClassAndSel, lldb::addr_t>(
76       ClassAndSel(class_addr, selector), impl_addr));
77 }
78 
79 void ObjCLanguageRuntime::AddToMethodCache(lldb::addr_t class_addr,
80                                            llvm::StringRef sel_str,
81                                            lldb::addr_t impl_addr) {
82   Log *log = GetLog(LLDBLog::Step);
83 
84   LLDB_LOG(log, "Caching: class {0} selector {1} implementation {2}.",
85            class_addr, sel_str, impl_addr);
86 
87   m_impl_str_cache.insert(std::pair<ClassAndSelStr, lldb::addr_t>(
88       ClassAndSelStr(class_addr, sel_str), impl_addr));
89 }
90 
91 lldb::addr_t ObjCLanguageRuntime::LookupInMethodCache(lldb::addr_t class_addr,
92                                                       lldb::addr_t selector) {
93   MsgImplMap::iterator pos, end = m_impl_cache.end();
94   pos = m_impl_cache.find(ClassAndSel(class_addr, selector));
95   if (pos != end)
96     return (*pos).second;
97   return LLDB_INVALID_ADDRESS;
98 }
99 
100 lldb::addr_t ObjCLanguageRuntime::LookupInMethodCache(lldb::addr_t class_addr,
101                                                       llvm::StringRef sel_str) {
102   MsgImplStrMap::iterator pos, end = m_impl_str_cache.end();
103   pos = m_impl_str_cache.find(ClassAndSelStr(class_addr, sel_str));
104   if (pos != end)
105     return (*pos).second;
106   return LLDB_INVALID_ADDRESS;
107 }
108 
109 lldb::TypeSP
110 ObjCLanguageRuntime::LookupInCompleteClassCache(ConstString &name) {
111   CompleteClassMap::iterator complete_class_iter =
112       m_complete_class_cache.find(name);
113 
114   if (complete_class_iter != m_complete_class_cache.end()) {
115     // Check the weak pointer to make sure the type hasn't been unloaded
116     TypeSP complete_type_sp(complete_class_iter->second.lock());
117 
118     if (complete_type_sp)
119       return complete_type_sp;
120     else
121       m_complete_class_cache.erase(name);
122   }
123 
124   if (m_negative_complete_class_cache.count(name) > 0)
125     return TypeSP();
126 
127   const ModuleList &modules = m_process->GetTarget().GetImages();
128 
129   SymbolContextList sc_list;
130   modules.FindSymbolsWithNameAndType(name, eSymbolTypeObjCClass, sc_list);
131   const size_t matching_symbols = sc_list.GetSize();
132 
133   if (matching_symbols) {
134     SymbolContext sc;
135 
136     sc_list.GetContextAtIndex(0, sc);
137 
138     ModuleSP module_sp(sc.module_sp);
139 
140     if (!module_sp)
141       return TypeSP();
142 
143     const bool exact_match = true;
144     const uint32_t max_matches = UINT32_MAX;
145     TypeList types;
146 
147     llvm::DenseSet<SymbolFile *> searched_symbol_files;
148     module_sp->FindTypes(name, exact_match, max_matches, searched_symbol_files,
149                          types);
150 
151     for (uint32_t i = 0; i < types.GetSize(); ++i) {
152       TypeSP type_sp(types.GetTypeAtIndex(i));
153 
154       if (TypeSystemClang::IsObjCObjectOrInterfaceType(
155               type_sp->GetForwardCompilerType())) {
156         if (TypePayloadClang(type_sp->GetPayload()).IsCompleteObjCClass()) {
157           m_complete_class_cache[name] = type_sp;
158           return type_sp;
159         }
160       }
161     }
162   }
163   m_negative_complete_class_cache.insert(name);
164   return TypeSP();
165 }
166 
167 size_t ObjCLanguageRuntime::GetByteOffsetForIvar(CompilerType &parent_qual_type,
168                                                  const char *ivar_name) {
169   return LLDB_INVALID_IVAR_OFFSET;
170 }
171 
172 bool ObjCLanguageRuntime::ClassDescriptor::IsPointerValid(
173     lldb::addr_t value, uint32_t ptr_size, bool allow_NULLs, bool allow_tagged,
174     bool check_version_specific) const {
175   if (!value)
176     return allow_NULLs;
177   if ((value % 2) == 1 && allow_tagged)
178     return true;
179   if ((value % ptr_size) == 0)
180     return (check_version_specific ? CheckPointer(value, ptr_size) : true);
181   else
182     return false;
183 }
184 
185 ObjCLanguageRuntime::ObjCISA
186 ObjCLanguageRuntime::GetISA(ConstString name) {
187   ISAToDescriptorIterator pos = GetDescriptorIterator(name);
188   if (pos != m_isa_to_descriptor.end())
189     return pos->first;
190   return 0;
191 }
192 
193 ObjCLanguageRuntime::ISAToDescriptorIterator
194 ObjCLanguageRuntime::GetDescriptorIterator(ConstString name) {
195   ISAToDescriptorIterator end = m_isa_to_descriptor.end();
196 
197   if (name) {
198     UpdateISAToDescriptorMap();
199     if (m_hash_to_isa_map.empty()) {
200       // No name hashes were provided, we need to just linearly power through
201       // the names and find a match
202       for (ISAToDescriptorIterator pos = m_isa_to_descriptor.begin();
203            pos != end; ++pos) {
204         if (pos->second->GetClassName() == name)
205           return pos;
206       }
207     } else {
208       // Name hashes were provided, so use them to efficiently lookup name to
209       // isa/descriptor
210       const uint32_t name_hash = llvm::djbHash(name.GetStringRef());
211       std::pair<HashToISAIterator, HashToISAIterator> range =
212           m_hash_to_isa_map.equal_range(name_hash);
213       for (HashToISAIterator range_pos = range.first; range_pos != range.second;
214            ++range_pos) {
215         ISAToDescriptorIterator pos =
216             m_isa_to_descriptor.find(range_pos->second);
217         if (pos != m_isa_to_descriptor.end()) {
218           if (pos->second->GetClassName() == name)
219             return pos;
220         }
221       }
222     }
223   }
224   return end;
225 }
226 
227 std::pair<ObjCLanguageRuntime::ISAToDescriptorIterator,
228           ObjCLanguageRuntime::ISAToDescriptorIterator>
229 ObjCLanguageRuntime::GetDescriptorIteratorPair(bool update_if_needed) {
230   if (update_if_needed)
231     UpdateISAToDescriptorMapIfNeeded();
232 
233   return std::pair<ObjCLanguageRuntime::ISAToDescriptorIterator,
234                    ObjCLanguageRuntime::ISAToDescriptorIterator>(
235       m_isa_to_descriptor.begin(), m_isa_to_descriptor.end());
236 }
237 
238 void ObjCLanguageRuntime::ReadObjCLibraryIfNeeded(
239     const ModuleList &module_list) {
240   if (!HasReadObjCLibrary()) {
241     std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
242 
243     size_t num_modules = module_list.GetSize();
244     for (size_t i = 0; i < num_modules; i++) {
245       auto mod = module_list.GetModuleAtIndex(i);
246       if (IsModuleObjCLibrary(mod)) {
247         ReadObjCLibrary(mod);
248         break;
249       }
250     }
251   }
252 }
253 
254 ObjCLanguageRuntime::ObjCISA
255 ObjCLanguageRuntime::GetParentClass(ObjCLanguageRuntime::ObjCISA isa) {
256   ClassDescriptorSP objc_class_sp(GetClassDescriptorFromISA(isa));
257   if (objc_class_sp) {
258     ClassDescriptorSP objc_super_class_sp(objc_class_sp->GetSuperclass());
259     if (objc_super_class_sp)
260       return objc_super_class_sp->GetISA();
261   }
262   return 0;
263 }
264 
265 ObjCLanguageRuntime::ClassDescriptorSP
266 ObjCLanguageRuntime::GetClassDescriptorFromClassName(
267     ConstString class_name) {
268   ISAToDescriptorIterator pos = GetDescriptorIterator(class_name);
269   if (pos != m_isa_to_descriptor.end())
270     return pos->second;
271   return ClassDescriptorSP();
272 }
273 
274 ObjCLanguageRuntime::ClassDescriptorSP
275 ObjCLanguageRuntime::GetClassDescriptor(ValueObject &valobj) {
276   ClassDescriptorSP objc_class_sp;
277   // if we get an invalid VO (which might still happen when playing around with
278   // pointers returned by the expression parser, don't consider this a valid
279   // ObjC object)
280   if (valobj.GetCompilerType().IsValid()) {
281     addr_t isa_pointer = valobj.GetPointerValue();
282     if (isa_pointer != LLDB_INVALID_ADDRESS) {
283       ExecutionContext exe_ctx(valobj.GetExecutionContextRef());
284 
285       Process *process = exe_ctx.GetProcessPtr();
286       if (process) {
287         Status error;
288         ObjCISA isa = process->ReadPointerFromMemory(isa_pointer, error);
289         if (isa != LLDB_INVALID_ADDRESS)
290           objc_class_sp = GetClassDescriptorFromISA(isa);
291       }
292     }
293   }
294   return objc_class_sp;
295 }
296 
297 ObjCLanguageRuntime::ClassDescriptorSP
298 ObjCLanguageRuntime::GetNonKVOClassDescriptor(ValueObject &valobj) {
299   ObjCLanguageRuntime::ClassDescriptorSP objc_class_sp(
300       GetClassDescriptor(valobj));
301   if (objc_class_sp) {
302     if (!objc_class_sp->IsKVO())
303       return objc_class_sp;
304 
305     ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
306     if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
307       return non_kvo_objc_class_sp;
308   }
309   return ClassDescriptorSP();
310 }
311 
312 ObjCLanguageRuntime::ClassDescriptorSP
313 ObjCLanguageRuntime::GetClassDescriptorFromISA(ObjCISA isa) {
314   if (isa) {
315     UpdateISAToDescriptorMap();
316 
317     ObjCLanguageRuntime::ISAToDescriptorIterator pos =
318         m_isa_to_descriptor.find(isa);
319     if (pos != m_isa_to_descriptor.end())
320       return pos->second;
321 
322     if (ABISP abi_sp = m_process->GetABI()) {
323       pos = m_isa_to_descriptor.find(abi_sp->FixCodeAddress(isa));
324       if (pos != m_isa_to_descriptor.end())
325         return pos->second;
326     }
327   }
328   return ClassDescriptorSP();
329 }
330 
331 ObjCLanguageRuntime::ClassDescriptorSP
332 ObjCLanguageRuntime::GetNonKVOClassDescriptor(ObjCISA isa) {
333   if (isa) {
334     ClassDescriptorSP objc_class_sp = GetClassDescriptorFromISA(isa);
335     if (objc_class_sp && objc_class_sp->IsValid()) {
336       if (!objc_class_sp->IsKVO())
337         return objc_class_sp;
338 
339       ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
340       if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
341         return non_kvo_objc_class_sp;
342     }
343   }
344   return ClassDescriptorSP();
345 }
346 
347 CompilerType
348 ObjCLanguageRuntime::EncodingToType::RealizeType(const char *name,
349                                                  bool for_expression) {
350   if (m_scratch_ast_ctx_sp)
351     return RealizeType(*m_scratch_ast_ctx_sp, name, for_expression);
352   return CompilerType();
353 }
354 
355 ObjCLanguageRuntime::EncodingToType::~EncodingToType() = default;
356 
357 ObjCLanguageRuntime::EncodingToTypeSP ObjCLanguageRuntime::GetEncodingToType() {
358   return nullptr;
359 }
360 
361 bool ObjCLanguageRuntime::GetTypeBitSize(const CompilerType &compiler_type,
362                                          uint64_t &size) {
363   void *opaque_ptr = compiler_type.GetOpaqueQualType();
364   size = m_type_size_cache.Lookup(opaque_ptr);
365   // an ObjC object will at least have an ISA, so 0 is definitely not OK
366   if (size > 0)
367     return true;
368 
369   ClassDescriptorSP class_descriptor_sp =
370       GetClassDescriptorFromClassName(compiler_type.GetTypeName());
371   if (!class_descriptor_sp)
372     return false;
373 
374   int32_t max_offset = INT32_MIN;
375   uint64_t sizeof_max = 0;
376   bool found = false;
377 
378   for (size_t idx = 0; idx < class_descriptor_sp->GetNumIVars(); idx++) {
379     const auto &ivar = class_descriptor_sp->GetIVarAtIndex(idx);
380     int32_t cur_offset = ivar.m_offset;
381     if (cur_offset > max_offset) {
382       max_offset = cur_offset;
383       sizeof_max = ivar.m_size;
384       found = true;
385     }
386   }
387 
388   size = 8 * (max_offset + sizeof_max);
389   if (found)
390     m_type_size_cache.Insert(opaque_ptr, size);
391 
392   return found;
393 }
394 
395 lldb::BreakpointPreconditionSP
396 ObjCLanguageRuntime::GetBreakpointExceptionPrecondition(LanguageType language,
397                                                         bool throw_bp) {
398   if (language != eLanguageTypeObjC)
399     return lldb::BreakpointPreconditionSP();
400   if (!throw_bp)
401     return lldb::BreakpointPreconditionSP();
402   BreakpointPreconditionSP precondition_sp(
403       new ObjCLanguageRuntime::ObjCExceptionPrecondition());
404   return precondition_sp;
405 }
406 
407 // Exception breakpoint Precondition class for ObjC:
408 void ObjCLanguageRuntime::ObjCExceptionPrecondition::AddClassName(
409     const char *class_name) {
410   m_class_names.insert(class_name);
411 }
412 
413 ObjCLanguageRuntime::ObjCExceptionPrecondition::ObjCExceptionPrecondition() =
414     default;
415 
416 bool ObjCLanguageRuntime::ObjCExceptionPrecondition::EvaluatePrecondition(
417     StoppointCallbackContext &context) {
418   return true;
419 }
420 
421 void ObjCLanguageRuntime::ObjCExceptionPrecondition::GetDescription(
422     Stream &stream, lldb::DescriptionLevel level) {}
423 
424 Status ObjCLanguageRuntime::ObjCExceptionPrecondition::ConfigurePrecondition(
425     Args &args) {
426   Status error;
427   if (args.GetArgumentCount() > 0)
428     error.SetErrorString(
429         "The ObjC Exception breakpoint doesn't support extra options.");
430   return error;
431 }
432 
433 std::optional<CompilerType>
434 ObjCLanguageRuntime::GetRuntimeType(CompilerType base_type) {
435   CompilerType class_type;
436   bool is_pointer_type = false;
437 
438   if (TypeSystemClang::IsObjCObjectPointerType(base_type, &class_type))
439     is_pointer_type = true;
440   else if (TypeSystemClang::IsObjCObjectOrInterfaceType(base_type))
441     class_type = base_type;
442   else
443     return std::nullopt;
444 
445   if (!class_type)
446     return std::nullopt;
447 
448   ConstString class_name(class_type.GetTypeName());
449   if (!class_name)
450     return std::nullopt;
451 
452   TypeSP complete_objc_class_type_sp = LookupInCompleteClassCache(class_name);
453   if (!complete_objc_class_type_sp)
454     return std::nullopt;
455 
456   CompilerType complete_class(
457       complete_objc_class_type_sp->GetFullCompilerType());
458   if (complete_class.GetCompleteType()) {
459     if (is_pointer_type)
460       return complete_class.GetPointerType();
461     else
462       return complete_class;
463   }
464 
465   return std::nullopt;
466 }
467