LLDB mainline
ObjCLanguageRuntime.cpp
Go to the documentation of this file.
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
13#include "lldb/Core/Module.h"
17#include "lldb/Symbol/Type.h"
20#include "lldb/Target/ABI.h"
21#include "lldb/Target/Target.h"
24#include "lldb/Utility/Log.h"
25#include "lldb/Utility/Timer.h"
27
28#include "llvm/ADT/StringRef.h"
29#include "llvm/Support/DJB.h"
30#include <optional>
31
32using namespace lldb;
33using namespace lldb_private;
34
36
37// Destructor
39
41 // These are the only object file formats clang can emit Objective-C
42 // metadata for; it aborts on any other.
43 switch (arch.GetTriple().getObjectFormat()) {
44 case llvm::Triple::MachO:
45 case llvm::Triple::ELF:
46 case llvm::Triple::COFF:
47 return true;
48 default:
49 return false;
50 }
51}
52
59
61 static ConstString g_self = ConstString("self");
62 static ConstString g_cmd = ConstString("_cmd");
63 return name == g_self || name == g_cmd;
64}
65
67 const ClassDescriptorSP &descriptor_sp,
68 const char *class_name) {
69 return AddClass(isa, descriptor_sp, llvm::djbHash(class_name));
70}
71
73 lldb::addr_t selector,
74 lldb::addr_t impl_addr) {
75 Log *log = GetLog(LLDBLog::Step);
76 LLDB_LOGF(log,
77 "Caching: class 0x%" PRIx64 " selector 0x%" PRIx64
78 " implementation 0x%" PRIx64 ".",
79 class_addr, selector, impl_addr);
80 m_impl_cache.insert(std::pair<ClassAndSel, lldb::addr_t>(
81 ClassAndSel(class_addr, selector), impl_addr));
82}
83
85 llvm::StringRef sel_str,
86 lldb::addr_t impl_addr) {
87 Log *log = GetLog(LLDBLog::Step);
88
89 LLDB_LOG(log, "Caching: class {0} selector {1} implementation {2}.",
90 class_addr, sel_str, impl_addr);
91
92 m_impl_str_cache.insert(std::pair<ClassAndSelStr, lldb::addr_t>(
93 ClassAndSelStr(class_addr, sel_str), impl_addr));
94}
95
97 lldb::addr_t selector) {
98 MsgImplMap::iterator pos, end = m_impl_cache.end();
99 pos = m_impl_cache.find(ClassAndSel(class_addr, selector));
100 if (pos != end)
101 return (*pos).second;
103}
104
106 llvm::StringRef sel_str) {
107 MsgImplStrMap::iterator pos, end = m_impl_str_cache.end();
108 pos = m_impl_str_cache.find(ClassAndSelStr(class_addr, sel_str));
109 if (pos != end)
110 return (*pos).second;
112}
113
116 CompleteClassMap::iterator complete_class_iter =
117 m_complete_class_cache.find(name);
118
119 if (complete_class_iter != m_complete_class_cache.end()) {
120 // Check the weak pointer to make sure the type hasn't been unloaded
121 TypeSP complete_type_sp(complete_class_iter->second.lock());
122
123 if (complete_type_sp)
124 return complete_type_sp;
125 else
126 m_complete_class_cache.erase(name);
127 }
128
129 if (m_negative_complete_class_cache.count(name) > 0)
130 return TypeSP();
131
132 const ModuleList &modules = m_process->GetTarget().GetImages();
133
134 SymbolContextList sc_list;
135 modules.FindSymbolsWithNameAndType(name, eSymbolTypeObjCClass, sc_list);
136 const size_t matching_symbols = sc_list.GetSize();
137
138 if (matching_symbols) {
139 SymbolContext sc;
140
141 sc_list.GetContextAtIndex(0, sc);
142
143 ModuleSP module_sp(sc.module_sp);
144
145 if (!module_sp)
146 return TypeSP();
147
148 TypeQuery query(name.GetStringRef(), TypeQueryOptions::e_exact_match);
149 TypeResults results;
150 module_sp->FindTypes(query, results);
151 for (const TypeSP &type_sp : results.GetTypeMap().Types()) {
153 type_sp->GetForwardCompilerType())) {
154 if (TypePayloadClang(type_sp->GetPayload()).IsCompleteObjCClass()) {
155 m_complete_class_cache[name] = type_sp;
156 return type_sp;
157 }
158 }
159 }
160 }
162 return TypeSP();
163}
164
166 const char *ivar_name) {
168}
169
171 lldb::addr_t value, uint32_t ptr_size, bool allow_NULLs, bool allow_tagged,
172 bool check_version_specific) const {
173 if (!value)
174 return allow_NULLs;
175 if ((value % 2) == 1 && allow_tagged)
176 return true;
177 if ((value % ptr_size) == 0)
178 return (check_version_specific ? CheckPointer(value, ptr_size) : true);
179 else
180 return false;
181}
182
186 if (pos != m_isa_to_descriptor.end())
187 return pos->first;
188 return 0;
189}
190
193 if (!name)
194 return m_isa_to_descriptor.end();
195
197
198 if (m_hash_to_isa_map.empty()) {
199 // No name hashes were provided, we need to just linearly power through
200 // the names and find a match
201 for (auto it = m_isa_to_descriptor.begin(), end = m_isa_to_descriptor.end();
202 it != end; ++it)
203 if (it->second->GetClassName() == name)
204 return it;
205 return m_isa_to_descriptor.end();
206 }
207
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 auto matches_it = m_hash_to_isa_map.find(name_hash);
212 if (matches_it == m_hash_to_isa_map.end())
213 return m_isa_to_descriptor.end();
214
215 for (auto isa : matches_it->second)
216 if (auto pos = m_isa_to_descriptor.find(isa);
217 pos != m_isa_to_descriptor.end() && pos->second->GetClassName() == name)
218 return pos;
219
220 return m_isa_to_descriptor.end();
221}
222
233
235 const ModuleList &module_list) {
236 if (!HasReadObjCLibrary()) {
237 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
238
239 size_t num_modules = module_list.GetSize();
240 for (size_t i = 0; i < num_modules; i++) {
241 auto mod = module_list.GetModuleAtIndex(i);
242 if (IsModuleObjCLibrary(mod)) {
243 ReadObjCLibrary(mod);
244 break;
245 }
246 }
247 }
248}
249
253 if (objc_class_sp) {
254 ClassDescriptorSP objc_super_class_sp(objc_class_sp->GetSuperclass());
255 if (objc_super_class_sp)
256 return objc_super_class_sp->GetISA();
257 }
258 return 0;
259}
260
263 ConstString class_name) {
265 if (pos != m_isa_to_descriptor.end())
266 return pos->second;
267 return ClassDescriptorSP();
268}
269
272 ClassDescriptorSP objc_class_sp;
273 // if we get an invalid VO (which might still happen when playing around with
274 // pointers returned by the expression parser, don't consider this a valid
275 // ObjC object)
276 if (valobj.GetCompilerType().IsValid()) {
277 addr_t isa_pointer = valobj.GetPointerValue().address;
278 if (isa_pointer != LLDB_INVALID_ADDRESS) {
280
281 Process *process = exe_ctx.GetProcessPtr();
282 if (process) {
284 ObjCISA isa = process->ReadPointerFromMemory(isa_pointer, error);
285 if (isa != LLDB_INVALID_ADDRESS)
286 objc_class_sp = GetClassDescriptorFromISA(isa);
287 }
288 }
289 }
290 return objc_class_sp;
291}
292
296 GetClassDescriptor(valobj));
297 if (objc_class_sp) {
298 if (!objc_class_sp->IsKVO())
299 return objc_class_sp;
300
301 ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
302 if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
303 return non_kvo_objc_class_sp;
304 }
305 return ClassDescriptorSP();
306}
307
310 if (isa) {
312
314 m_isa_to_descriptor.find(isa);
315 if (pos != m_isa_to_descriptor.end())
316 return pos->second;
317
318 if (ABISP abi_sp = m_process->GetABI()) {
319 pos = m_isa_to_descriptor.find(abi_sp->FixCodeAddress(isa));
320 if (pos != m_isa_to_descriptor.end())
321 return pos->second;
322 }
323 }
324 return ClassDescriptorSP();
325}
326
329 if (isa) {
330 ClassDescriptorSP objc_class_sp = GetClassDescriptorFromISA(isa);
331 if (objc_class_sp && objc_class_sp->IsValid()) {
332 if (!objc_class_sp->IsKVO())
333 return objc_class_sp;
334
335 ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
336 if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
337 return non_kvo_objc_class_sp;
338 }
339 }
340 return ClassDescriptorSP();
341}
342
345 bool for_expression) {
347 return RealizeType(*m_scratch_ast_ctx_sp, name, for_expression);
348 return CompilerType();
349}
350
352
356
357std::optional<uint64_t>
359 void *opaque_ptr = compiler_type.GetOpaqueQualType();
360 uint64_t cached_size = m_type_size_cache.Lookup(opaque_ptr);
361 if (cached_size > 0)
362 return cached_size;
363
364 ClassDescriptorSP class_descriptor_sp =
366 if (!class_descriptor_sp)
367 return {};
368
369 int32_t max_offset = INT32_MIN;
370 uint64_t sizeof_max = 0;
371 bool found = false;
372
373 for (size_t idx = 0; idx < class_descriptor_sp->GetNumIVars(); idx++) {
374 const auto &ivar = class_descriptor_sp->GetIVarAtIndex(idx);
375 int32_t cur_offset = ivar.m_offset;
376 if (cur_offset > max_offset) {
377 max_offset = cur_offset;
378 sizeof_max = ivar.m_size;
379 found = true;
380 }
381 }
382
383 uint64_t size = 8 * (max_offset + sizeof_max);
384 if (found && size > 0) {
385 m_type_size_cache.Insert(opaque_ptr, size);
386 return size;
387 }
388
389 return {};
390}
391
394 bool throw_bp) {
395 if (language != eLanguageTypeObjC)
397 if (!throw_bp)
399 BreakpointPreconditionSP precondition_sp(
401 return precondition_sp;
402}
403
404// Exception breakpoint Precondition class for ObjC:
406 const char *class_name) {
407 m_class_names.insert(class_name);
408}
409
411 default;
412
417
420
422 Args &args) {
424 if (args.GetArgumentCount() > 0)
426 "The ObjC Exception breakpoint doesn't support extra options.");
427 return error;
428}
429
431 Target &target) {
432 assert(class_name);
433
434 auto *persistent_state = llvm::cast<ClangPersistentVariables>(
436 if (!persistent_state)
437 return {};
438
439 auto clang_modules_decl_vendor_sp =
440 persistent_state->GetClangModulesDeclVendor();
441 if (!clang_modules_decl_vendor_sp)
442 return {};
443
444 auto types = clang_modules_decl_vendor_sp->FindTypes(
445 class_name, /*max_matches*/ UINT32_MAX);
446 if (types.empty())
447 return {};
448
449 return types.front();
450}
451
453 auto *runtime_vendor = GetDeclVendor();
454 if (!runtime_vendor)
455 return {};
456
457 std::vector<CompilerDecl> compiler_decls;
458 runtime_vendor->FindDecls(class_name, false, UINT32_MAX, compiler_decls);
459 if (compiler_decls.empty())
460 return {};
461
462 auto *ctx =
463 llvm::dyn_cast<TypeSystemClang>(compiler_decls[0].GetTypeSystem());
464 if (!ctx)
465 return {};
466
467 return ctx->GetTypeForDecl(compiler_decls[0].GetOpaqueDecl());
468}
469
470std::optional<CompilerType>
472 CompilerType class_type;
473 bool is_pointer_type = false;
474
475 if (TypeSystemClang::IsObjCObjectPointerType(base_type, &class_type))
476 is_pointer_type = true;
478 class_type = base_type;
479 else
480 return std::nullopt;
481
482 if (!class_type)
483 return std::nullopt;
484
485 ConstString class_name(class_type.GetTypeName());
486 if (!class_name)
487 return std::nullopt;
488
489 if (TypeSP complete_objc_class_type_sp =
490 LookupInCompleteClassCache(class_name)) {
491 if (CompilerType complete_class =
492 complete_objc_class_type_sp->GetFullCompilerType();
493 complete_class.GetCompleteType())
494 return is_pointer_type ? complete_class.GetPointerType() : complete_class;
495 }
496
497 assert(m_process);
498 if (CompilerType found =
499 LookupInModulesVendor(class_name, m_process->GetTarget()))
500 return is_pointer_type ? found.GetPointerType() : found;
501
502 if (CompilerType found = LookupInRuntime(class_name))
503 return is_pointer_type ? found.GetPointerType() : found;
504
505 return std::nullopt;
506}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:364
#define LLDB_LOGF(log,...)
Definition Log.h:378
An architecture specification class.
Definition ArchSpec.h:32
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:460
A command line argument class.
Definition Args.h:33
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
Generic representation of a type in a programming language.
lldb::opaque_compiler_type_t GetOpaqueQualType() const
ConstString GetTypeName(bool BaseOnly=false) const
bool GetCompleteType() const
Type Completion.
A uniqued constant string class.
Definition ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
Process * GetProcessPtr() const
Returns a pointer to the process object.
virtual DeclVendor * GetDeclVendor()
A collection class for Module objects.
Definition ModuleList.h:125
std::recursive_mutex & GetMutex() const
Definition ModuleList.h:252
void FindSymbolsWithNameAndType(ConstString name, lldb::SymbolType symbol_type, SymbolContextList &sc_list) const
lldb::ModuleSP GetModuleAtIndex(size_t idx) const
Get the module shared pointer for the module at index idx.
size_t GetSize() const
Gets the size of the module list.
bool IsPointerValid(lldb::addr_t value, uint32_t ptr_size, bool allow_NULLs=false, bool allow_tagged=false, bool check_version_specific=false) const
virtual bool CheckPointer(lldb::addr_t value, uint32_t ptr_size) const
virtual CompilerType RealizeType(TypeSystemClang &ast_ctx, const char *name, bool for_expression)=0
std::shared_ptr< TypeSystemClang > m_scratch_ast_ctx_sp
void GetDescription(Stream &stream, lldb::DescriptionLevel level) override
bool EvaluatePrecondition(StoppointCallbackContext &context) override
virtual ObjCISA GetISA(ConstString name)
virtual EncodingToTypeSP GetEncodingToType()
std::shared_ptr< ClassDescriptor > ClassDescriptorSP
static bool IsSupportedForArchitecture(const ArchSpec &arch)
Returns whether the architecture's object file format supports Objective-C code generation.
bool AddClass(ObjCISA isa, const ClassDescriptorSP &descriptor_sp)
virtual bool ReadObjCLibrary(const lldb::ModuleSP &module_sp)=0
ISAToDescriptorMap::iterator ISAToDescriptorIterator
std::optional< uint64_t > GetTypeBitSize(const CompilerType &compiler_type) override
std::pair< ISAToDescriptorIterator, ISAToDescriptorIterator > GetDescriptorIteratorPair(bool update_if_needed=true)
virtual size_t GetByteOffsetForIvar(CompilerType &parent_qual_type, const char *ivar_name)
ISAToDescriptorIterator GetDescriptorIterator(ConstString name)
lldb::addr_t LookupInMethodCache(lldb::addr_t class_addr, lldb::addr_t sel)
lldb::TypeSP LookupInCompleteClassCache(ConstString &name)
virtual bool IsModuleObjCLibrary(const lldb::ModuleSP &module_sp)=0
ClassDescriptorSP GetNonKVOClassDescriptor(ValueObject &in_value)
virtual void UpdateISAToDescriptorMapIfNeeded()=0
std::optional< CompilerType > GetRuntimeType(CompilerType base_type) override
void ReadObjCLibraryIfNeeded(const ModuleList &module_list)
virtual ClassDescriptorSP GetClassDescriptorFromISA(ObjCISA isa)
CompilerType LookupInRuntime(ConstString class_name)
bool IsAllowedRuntimeValue(ConstString name) override
Check whether the name is "self" or "_cmd" and should show up in "frame variable".
CompilerType LookupInModulesVendor(ConstString class_name, Target &process)
virtual ClassDescriptorSP GetClassDescriptor(ValueObject &in_value)
virtual ClassDescriptorSP GetClassDescriptorFromClassName(ConstString class_name)
void AddToMethodCache(lldb::addr_t class_addr, lldb::addr_t sel, lldb::addr_t impl_addr)
static lldb::BreakpointPreconditionSP GetBreakpointExceptionPrecondition(lldb::LanguageType language, bool throw_bp)
virtual ObjCISA GetParentClass(ObjCISA isa)
std::shared_ptr< EncodingToType > EncodingToTypeSP
A plug-in interface definition class for debugging a process.
Definition Process.h:357
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition Process.cpp:2508
Process * m_process
Definition Runtime.h:29
An error handling class.
Definition Status.h:118
static Status FromErrorString(const char *str)
Definition Status.h:141
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
A stream class that can stream formatted output to a file.
Definition Stream.h:28
Defines a list of symbol context objects.
bool GetContextAtIndex(size_t idx, SymbolContext &sc) const
Get accessor for a symbol context at index idx.
uint32_t GetSize() const
Get accessor for a symbol context list size.
Defines a symbol context baton that can be handed other debug core functions.
lldb::ModuleSP module_sp
The Module for a given query.
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition Target.cpp:2743
TypeIterable Types() const
Definition TypeMap.h:48
The implementation of lldb::Type's m_payload field for TypeSystemClang.
A class that contains all state required for type lookups.
Definition Type.h:104
This class tracks the state and results of a TypeQuery.
Definition Type.h:344
TypeMap & GetTypeMap()
Definition Type.h:386
static bool IsObjCObjectOrInterfaceType(const CompilerType &type)
static bool IsObjCObjectPointerType(const CompilerType &type, CompilerType *target_type=nullptr)
CompilerType GetCompilerType()
const ExecutionContextRef & GetExecutionContextRef() const
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
#define LLDB_INVALID_IVAR_OFFSET
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:327
std::shared_ptr< lldb_private::ABI > ABISP
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
LanguageType
Programming language type.
@ eLanguageTypeC
Non-standardized C, such as K&R.
@ eLanguageTypeObjC
Objective-C.
std::shared_ptr< lldb_private::Type > TypeSP
std::shared_ptr< lldb_private::BreakpointPrecondition > BreakpointPreconditionSP
@ eSymbolTypeObjCClass
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Module > ModuleSP