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
294 TaggedPointerVendor *tagged_pointer_vendor = GetTaggedPointerVendor();
295 if (!tagged_pointer_vendor)
296 return false;
297
298 // Only Objective-C object values can be tagged pointers.
299 if (!(in_value.GetTypeInfo() & lldb::eTypeIsObjC))
300 return false;
301
302 addr_t ptr = in_value.IsPointerType() ? in_value.GetPointerValue().address
303 : in_value.GetAddressOf().address;
304 if (ptr == LLDB_INVALID_ADDRESS)
305 return false;
306
307 return tagged_pointer_vendor->IsPossibleTaggedPointer(ptr);
308}
309
313 GetClassDescriptor(valobj));
314 if (objc_class_sp) {
315 if (!objc_class_sp->IsKVO())
316 return objc_class_sp;
317
318 ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
319 if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
320 return non_kvo_objc_class_sp;
321 }
322 return ClassDescriptorSP();
323}
324
327 if (isa) {
329
331 m_isa_to_descriptor.find(isa);
332 if (pos != m_isa_to_descriptor.end())
333 return pos->second;
334
335 if (ABISP abi_sp = m_process->GetABI()) {
336 pos = m_isa_to_descriptor.find(abi_sp->FixCodeAddress(isa));
337 if (pos != m_isa_to_descriptor.end())
338 return pos->second;
339 }
340 }
341 return ClassDescriptorSP();
342}
343
346 if (isa) {
347 ClassDescriptorSP objc_class_sp = GetClassDescriptorFromISA(isa);
348 if (objc_class_sp && objc_class_sp->IsValid()) {
349 if (!objc_class_sp->IsKVO())
350 return objc_class_sp;
351
352 ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
353 if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
354 return non_kvo_objc_class_sp;
355 }
356 }
357 return ClassDescriptorSP();
358}
359
362 bool for_expression) {
364 return RealizeType(*m_scratch_ast_ctx_sp, name, for_expression);
365 return CompilerType();
366}
367
369
373
374std::optional<uint64_t>
376 void *opaque_ptr = compiler_type.GetOpaqueQualType();
377 uint64_t cached_size = m_type_size_cache.Lookup(opaque_ptr);
378 if (cached_size > 0)
379 return cached_size;
380
381 ClassDescriptorSP class_descriptor_sp =
383 if (!class_descriptor_sp)
384 return {};
385
386 int32_t max_offset = INT32_MIN;
387 uint64_t sizeof_max = 0;
388 bool found = false;
389
390 for (size_t idx = 0; idx < class_descriptor_sp->GetNumIVars(); idx++) {
391 const auto &ivar = class_descriptor_sp->GetIVarAtIndex(idx);
392 int32_t cur_offset = ivar.m_offset;
393 if (cur_offset > max_offset) {
394 max_offset = cur_offset;
395 sizeof_max = ivar.m_size;
396 found = true;
397 }
398 }
399
400 uint64_t size = 8 * (max_offset + sizeof_max);
401 if (found && size > 0) {
402 m_type_size_cache.Insert(opaque_ptr, size);
403 return size;
404 }
405
406 return {};
407}
408
411 bool throw_bp) {
412 if (language != eLanguageTypeObjC)
414 if (!throw_bp)
416 BreakpointPreconditionSP precondition_sp(
418 return precondition_sp;
419}
420
421// Exception breakpoint Precondition class for ObjC:
423 const char *class_name) {
424 m_class_names.insert(class_name);
425}
426
428 default;
429
434
437
439 Args &args) {
441 if (args.GetArgumentCount() > 0)
443 "The ObjC Exception breakpoint doesn't support extra options.");
444 return error;
445}
446
448 Target &target) {
449 assert(class_name);
450
451 auto *persistent_state = llvm::cast<ClangPersistentVariables>(
453 if (!persistent_state)
454 return {};
455
456 auto clang_modules_decl_vendor_sp =
457 persistent_state->GetClangModulesDeclVendor();
458 if (!clang_modules_decl_vendor_sp)
459 return {};
460
461 auto types = clang_modules_decl_vendor_sp->FindTypes(
462 class_name, /*max_matches*/ UINT32_MAX);
463 if (types.empty())
464 return {};
465
466 return types.front();
467}
468
470 auto *runtime_vendor = GetDeclVendor();
471 if (!runtime_vendor)
472 return {};
473
474 std::vector<CompilerDecl> compiler_decls;
475 runtime_vendor->FindDecls(class_name, false, UINT32_MAX, compiler_decls);
476 if (compiler_decls.empty())
477 return {};
478
479 auto *ctx =
480 llvm::dyn_cast<TypeSystemClang>(compiler_decls[0].GetTypeSystem());
481 if (!ctx)
482 return {};
483
484 return ctx->GetTypeForDecl(compiler_decls[0].GetOpaqueDecl());
485}
486
487std::optional<CompilerType>
489 CompilerType class_type;
490 bool is_pointer_type = false;
491
492 if (TypeSystemClang::IsObjCObjectPointerType(base_type, &class_type))
493 is_pointer_type = true;
495 class_type = base_type;
496 else
497 return std::nullopt;
498
499 if (!class_type)
500 return std::nullopt;
501
502 ConstString class_name(class_type.GetTypeName());
503 if (!class_name)
504 return std::nullopt;
505
506 if (TypeSP complete_objc_class_type_sp =
507 LookupInCompleteClassCache(class_name)) {
508 if (CompilerType complete_class =
509 complete_objc_class_type_sp->GetFullCompilerType();
510 complete_class.GetCompleteType())
511 return is_pointer_type ? complete_class.GetPointerType() : complete_class;
512 }
513
514 assert(m_process);
515 if (CompilerType found =
516 LookupInModulesVendor(class_name, m_process->GetTarget()))
517 return is_pointer_type ? found.GetPointerType() : found;
518
519 if (CompilerType found = LookupInRuntime(class_name))
520 return is_pointer_type ? found.GetPointerType() : found;
521
522 return std::nullopt;
523}
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:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
An architecture specification class.
Definition ArchSpec.h:32
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:544
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 bool IsPossibleTaggedPointer(lldb::addr_t ptr)=0
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)
bool IsTaggedPointerValue(ValueObject &in_value)
virtual TaggedPointerVendor * GetTaggedPointerVendor()
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:359
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition Process.cpp:2517
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:2776
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)
uint32_t GetTypeInfo(CompilerType *pointee_or_element_compiler_type=nullptr)
CompilerType GetCompilerType()
const ExecutionContextRef & GetExecutionContextRef() const
virtual AddrAndType GetAddressOf(bool scalar_is_load_address=true)
#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:338
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