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
ObjCLanguageRuntime(Process * process)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
IsAllowedRuntimeValue(ConstString name)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
AddClass(ObjCISA isa,const ClassDescriptorSP & descriptor_sp,const char * class_name)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
AddToMethodCache(lldb::addr_t class_addr,lldb::addr_t selector,lldb::addr_t impl_addr)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
AddToMethodCache(lldb::addr_t class_addr,llvm::StringRef sel_str,lldb::addr_t impl_addr)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
LookupInMethodCache(lldb::addr_t class_addr,lldb::addr_t selector)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
LookupInMethodCache(lldb::addr_t class_addr,llvm::StringRef sel_str)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
LookupInCompleteClassCache(ConstString & name)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
GetByteOffsetForIvar(CompilerType & parent_qual_type,const char * ivar_name)167 size_t ObjCLanguageRuntime::GetByteOffsetForIvar(CompilerType &parent_qual_type,
168 const char *ivar_name) {
169 return LLDB_INVALID_IVAR_OFFSET;
170 }
171
IsPointerValid(lldb::addr_t value,uint32_t ptr_size,bool allow_NULLs,bool allow_tagged,bool check_version_specific) const172 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
GetISA(ConstString name)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
GetDescriptorIterator(ConstString name)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>
GetDescriptorIteratorPair(bool update_if_needed)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 ObjCLanguageRuntime::ObjCISA
GetParentClass(ObjCLanguageRuntime::ObjCISA isa)239 ObjCLanguageRuntime::GetParentClass(ObjCLanguageRuntime::ObjCISA isa) {
240 ClassDescriptorSP objc_class_sp(GetClassDescriptorFromISA(isa));
241 if (objc_class_sp) {
242 ClassDescriptorSP objc_super_class_sp(objc_class_sp->GetSuperclass());
243 if (objc_super_class_sp)
244 return objc_super_class_sp->GetISA();
245 }
246 return 0;
247 }
248
249 ObjCLanguageRuntime::ClassDescriptorSP
GetClassDescriptorFromClassName(ConstString class_name)250 ObjCLanguageRuntime::GetClassDescriptorFromClassName(
251 ConstString class_name) {
252 ISAToDescriptorIterator pos = GetDescriptorIterator(class_name);
253 if (pos != m_isa_to_descriptor.end())
254 return pos->second;
255 return ClassDescriptorSP();
256 }
257
258 ObjCLanguageRuntime::ClassDescriptorSP
GetClassDescriptor(ValueObject & valobj)259 ObjCLanguageRuntime::GetClassDescriptor(ValueObject &valobj) {
260 ClassDescriptorSP objc_class_sp;
261 // if we get an invalid VO (which might still happen when playing around with
262 // pointers returned by the expression parser, don't consider this a valid
263 // ObjC object)
264 if (valobj.GetCompilerType().IsValid()) {
265 addr_t isa_pointer = valobj.GetPointerValue();
266 if (isa_pointer != LLDB_INVALID_ADDRESS) {
267 ExecutionContext exe_ctx(valobj.GetExecutionContextRef());
268
269 Process *process = exe_ctx.GetProcessPtr();
270 if (process) {
271 Status error;
272 ObjCISA isa = process->ReadPointerFromMemory(isa_pointer, error);
273 if (isa != LLDB_INVALID_ADDRESS)
274 objc_class_sp = GetClassDescriptorFromISA(isa);
275 }
276 }
277 }
278 return objc_class_sp;
279 }
280
281 ObjCLanguageRuntime::ClassDescriptorSP
GetNonKVOClassDescriptor(ValueObject & valobj)282 ObjCLanguageRuntime::GetNonKVOClassDescriptor(ValueObject &valobj) {
283 ObjCLanguageRuntime::ClassDescriptorSP objc_class_sp(
284 GetClassDescriptor(valobj));
285 if (objc_class_sp) {
286 if (!objc_class_sp->IsKVO())
287 return objc_class_sp;
288
289 ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
290 if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
291 return non_kvo_objc_class_sp;
292 }
293 return ClassDescriptorSP();
294 }
295
296 ObjCLanguageRuntime::ClassDescriptorSP
GetClassDescriptorFromISA(ObjCISA isa)297 ObjCLanguageRuntime::GetClassDescriptorFromISA(ObjCISA isa) {
298 if (isa) {
299 UpdateISAToDescriptorMap();
300
301 ObjCLanguageRuntime::ISAToDescriptorIterator pos =
302 m_isa_to_descriptor.find(isa);
303 if (pos != m_isa_to_descriptor.end())
304 return pos->second;
305
306 if (ABISP abi_sp = m_process->GetABI()) {
307 pos = m_isa_to_descriptor.find(abi_sp->FixCodeAddress(isa));
308 if (pos != m_isa_to_descriptor.end())
309 return pos->second;
310 }
311 }
312 return ClassDescriptorSP();
313 }
314
315 ObjCLanguageRuntime::ClassDescriptorSP
GetNonKVOClassDescriptor(ObjCISA isa)316 ObjCLanguageRuntime::GetNonKVOClassDescriptor(ObjCISA isa) {
317 if (isa) {
318 ClassDescriptorSP objc_class_sp = GetClassDescriptorFromISA(isa);
319 if (objc_class_sp && objc_class_sp->IsValid()) {
320 if (!objc_class_sp->IsKVO())
321 return objc_class_sp;
322
323 ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
324 if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
325 return non_kvo_objc_class_sp;
326 }
327 }
328 return ClassDescriptorSP();
329 }
330
331 CompilerType
RealizeType(const char * name,bool for_expression)332 ObjCLanguageRuntime::EncodingToType::RealizeType(const char *name,
333 bool for_expression) {
334 if (m_scratch_ast_ctx_sp)
335 return RealizeType(*m_scratch_ast_ctx_sp, name, for_expression);
336 return CompilerType();
337 }
338
339 ObjCLanguageRuntime::EncodingToType::~EncodingToType() = default;
340
GetEncodingToType()341 ObjCLanguageRuntime::EncodingToTypeSP ObjCLanguageRuntime::GetEncodingToType() {
342 return nullptr;
343 }
344
GetTypeBitSize(const CompilerType & compiler_type,uint64_t & size)345 bool ObjCLanguageRuntime::GetTypeBitSize(const CompilerType &compiler_type,
346 uint64_t &size) {
347 void *opaque_ptr = compiler_type.GetOpaqueQualType();
348 size = m_type_size_cache.Lookup(opaque_ptr);
349 // an ObjC object will at least have an ISA, so 0 is definitely not OK
350 if (size > 0)
351 return true;
352
353 ClassDescriptorSP class_descriptor_sp =
354 GetClassDescriptorFromClassName(compiler_type.GetTypeName());
355 if (!class_descriptor_sp)
356 return false;
357
358 int32_t max_offset = INT32_MIN;
359 uint64_t sizeof_max = 0;
360 bool found = false;
361
362 for (size_t idx = 0; idx < class_descriptor_sp->GetNumIVars(); idx++) {
363 const auto &ivar = class_descriptor_sp->GetIVarAtIndex(idx);
364 int32_t cur_offset = ivar.m_offset;
365 if (cur_offset > max_offset) {
366 max_offset = cur_offset;
367 sizeof_max = ivar.m_size;
368 found = true;
369 }
370 }
371
372 size = 8 * (max_offset + sizeof_max);
373 if (found)
374 m_type_size_cache.Insert(opaque_ptr, size);
375
376 return found;
377 }
378
379 lldb::BreakpointPreconditionSP
GetBreakpointExceptionPrecondition(LanguageType language,bool throw_bp)380 ObjCLanguageRuntime::GetBreakpointExceptionPrecondition(LanguageType language,
381 bool throw_bp) {
382 if (language != eLanguageTypeObjC)
383 return lldb::BreakpointPreconditionSP();
384 if (!throw_bp)
385 return lldb::BreakpointPreconditionSP();
386 BreakpointPreconditionSP precondition_sp(
387 new ObjCLanguageRuntime::ObjCExceptionPrecondition());
388 return precondition_sp;
389 }
390
391 // Exception breakpoint Precondition class for ObjC:
AddClassName(const char * class_name)392 void ObjCLanguageRuntime::ObjCExceptionPrecondition::AddClassName(
393 const char *class_name) {
394 m_class_names.insert(class_name);
395 }
396
397 ObjCLanguageRuntime::ObjCExceptionPrecondition::ObjCExceptionPrecondition() =
398 default;
399
EvaluatePrecondition(StoppointCallbackContext & context)400 bool ObjCLanguageRuntime::ObjCExceptionPrecondition::EvaluatePrecondition(
401 StoppointCallbackContext &context) {
402 return true;
403 }
404
GetDescription(Stream & stream,lldb::DescriptionLevel level)405 void ObjCLanguageRuntime::ObjCExceptionPrecondition::GetDescription(
406 Stream &stream, lldb::DescriptionLevel level) {}
407
ConfigurePrecondition(Args & args)408 Status ObjCLanguageRuntime::ObjCExceptionPrecondition::ConfigurePrecondition(
409 Args &args) {
410 Status error;
411 if (args.GetArgumentCount() > 0)
412 error.SetErrorString(
413 "The ObjC Exception breakpoint doesn't support extra options.");
414 return error;
415 }
416
417 std::optional<CompilerType>
GetRuntimeType(CompilerType base_type)418 ObjCLanguageRuntime::GetRuntimeType(CompilerType base_type) {
419 CompilerType class_type;
420 bool is_pointer_type = false;
421
422 if (TypeSystemClang::IsObjCObjectPointerType(base_type, &class_type))
423 is_pointer_type = true;
424 else if (TypeSystemClang::IsObjCObjectOrInterfaceType(base_type))
425 class_type = base_type;
426 else
427 return std::nullopt;
428
429 if (!class_type)
430 return std::nullopt;
431
432 ConstString class_name(class_type.GetTypeName());
433 if (!class_name)
434 return std::nullopt;
435
436 TypeSP complete_objc_class_type_sp = LookupInCompleteClassCache(class_name);
437 if (!complete_objc_class_type_sp)
438 return std::nullopt;
439
440 CompilerType complete_class(
441 complete_objc_class_type_sp->GetFullCompilerType());
442 if (complete_class.GetCompleteType()) {
443 if (is_pointer_type)
444 return complete_class.GetPointerType();
445 else
446 return complete_class;
447 }
448
449 return std::nullopt;
450 }
451