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 "llvm/Support/Error.h"
31#include <optional>
32
33using namespace lldb;
34using namespace lldb_private;
35
37
38// Destructor
40
42 // These are the only object file formats clang can emit Objective-C
43 // metadata for; it aborts on any other.
44 switch (arch.GetTriple().getObjectFormat()) {
45 case llvm::Triple::MachO:
46 case llvm::Triple::ELF:
47 case llvm::Triple::COFF:
48 return true;
49 default:
50 return false;
51 }
52}
53
60
62 static ConstString g_self = ConstString("self");
63 static ConstString g_cmd = ConstString("_cmd");
64 return name == g_self || name == g_cmd;
65}
66
68 const ClassDescriptorSP &descriptor_sp,
69 const char *class_name) {
70 return AddClass(isa, descriptor_sp, llvm::djbHash(class_name));
71}
72
74 lldb::addr_t selector,
75 lldb::addr_t impl_addr) {
76 Log *log = GetLog(LLDBLog::Step);
77 LLDB_LOGF(log,
78 "Caching: class 0x%" PRIx64 " selector 0x%" PRIx64
79 " implementation 0x%" PRIx64 ".",
80 class_addr, selector, impl_addr);
81 m_impl_cache.insert(std::pair<ClassAndSel, lldb::addr_t>(
82 ClassAndSel(class_addr, selector), impl_addr));
83}
84
86 llvm::StringRef sel_str,
87 lldb::addr_t impl_addr) {
88 Log *log = GetLog(LLDBLog::Step);
89
90 LLDB_LOG(log, "Caching: class {0} selector {1} implementation {2}.",
91 class_addr, sel_str, impl_addr);
92
93 m_impl_str_cache.insert(std::pair<ClassAndSelStr, lldb::addr_t>(
94 ClassAndSelStr(class_addr, sel_str), impl_addr));
95}
96
98 lldb::addr_t selector) {
99 MsgImplMap::iterator pos, end = m_impl_cache.end();
100 pos = m_impl_cache.find(ClassAndSel(class_addr, selector));
101 if (pos != end)
102 return (*pos).second;
104}
105
107 llvm::StringRef sel_str) {
108 MsgImplStrMap::iterator pos, end = m_impl_str_cache.end();
109 pos = m_impl_str_cache.find(ClassAndSelStr(class_addr, sel_str));
110 if (pos != end)
111 return (*pos).second;
113}
114
117 CompleteClassMap::iterator complete_class_iter =
118 m_complete_class_cache.find(name);
119
120 if (complete_class_iter != m_complete_class_cache.end()) {
121 // Check the weak pointer to make sure the type hasn't been unloaded
122 TypeSP complete_type_sp(complete_class_iter->second.lock());
123
124 if (complete_type_sp)
125 return complete_type_sp;
126 else
127 m_complete_class_cache.erase(name);
128 }
129
130 if (m_negative_complete_class_cache.count(name) > 0)
131 return TypeSP();
132
133 const ModuleList &modules = m_process->GetTarget().GetImages();
134
135 SymbolContextList sc_list;
136 modules.FindSymbolsWithNameAndType(name, eSymbolTypeObjCClass, sc_list);
137 const size_t matching_symbols = sc_list.GetSize();
138
139 if (matching_symbols) {
140 SymbolContext sc;
141
142 sc_list.GetContextAtIndex(0, sc);
143
144 ModuleSP module_sp(sc.module_sp);
145
146 if (!module_sp)
147 return TypeSP();
148
149 TypeQuery query(name.GetStringRef(), TypeQueryOptions::e_exact_match);
150 TypeResults results;
151 module_sp->FindTypes(query, results);
152 for (const TypeSP &type_sp : results.GetTypeMap().Types()) {
154 type_sp->GetForwardCompilerType())) {
155 if (TypePayloadClang(type_sp->GetPayload()).IsCompleteObjCClass()) {
156 m_complete_class_cache[name] = type_sp;
157 return type_sp;
158 }
159 }
160 }
161 }
163 return TypeSP();
164}
165
167 const char *ivar_name) {
169}
170
172 lldb::addr_t value, uint32_t ptr_size, bool allow_NULLs, bool allow_tagged,
173 bool check_version_specific) const {
174 if (!value)
175 return allow_NULLs;
176 if ((value % 2) == 1 && allow_tagged)
177 return true;
178 if ((value % ptr_size) == 0)
179 return (check_version_specific ? CheckPointer(value, ptr_size) : true);
180 else
181 return false;
182}
183
187 if (pos != m_isa_to_descriptor.end())
188 return pos->first;
189 return 0;
190}
191
194 if (!name)
195 return m_isa_to_descriptor.end();
196
198
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 (auto it = m_isa_to_descriptor.begin(), end = m_isa_to_descriptor.end();
203 it != end; ++it)
204 if (it->second->GetClassName() == name)
205 return it;
206 return m_isa_to_descriptor.end();
207 }
208
209 // Name hashes were provided, so use them to efficiently lookup name to
210 // isa/descriptor
211 const uint32_t name_hash = llvm::djbHash(name.GetStringRef());
212 auto matches_it = m_hash_to_isa_map.find(name_hash);
213 if (matches_it == m_hash_to_isa_map.end())
214 return m_isa_to_descriptor.end();
215
216 for (auto isa : matches_it->second)
217 if (auto pos = m_isa_to_descriptor.find(isa);
218 pos != m_isa_to_descriptor.end() && pos->second->GetClassName() == name)
219 return pos;
220
221 return m_isa_to_descriptor.end();
222}
223
234
236 const ModuleList &module_list) {
237 if (!HasReadObjCLibrary()) {
238 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
239
240 size_t num_modules = module_list.GetSize();
241 for (size_t i = 0; i < num_modules; i++) {
242 auto mod = module_list.GetModuleAtIndex(i);
243 if (IsModuleObjCLibrary(mod)) {
244 ReadObjCLibrary(mod);
245 break;
246 }
247 }
248 }
249}
250
254 if (objc_class_sp) {
255 ClassDescriptorSP objc_super_class_sp(objc_class_sp->GetSuperclass());
256 if (objc_super_class_sp)
257 return objc_super_class_sp->GetISA();
258 }
259 return 0;
260}
261
264 ConstString class_name) {
266 if (pos != m_isa_to_descriptor.end())
267 return pos->second;
268 return ClassDescriptorSP();
269}
270
273 ClassDescriptorSP objc_class_sp;
274 // if we get an invalid VO (which might still happen when playing around with
275 // pointers returned by the expression parser, don't consider this a valid
276 // ObjC object)
277 if (valobj.GetCompilerType().IsValid()) {
278 addr_t isa_pointer = valobj.GetPointerValue().address;
279 if (isa_pointer != LLDB_INVALID_ADDRESS) {
281
282 Process *process = exe_ctx.GetProcessPtr();
283 if (process) {
284 std::optional<lldb::addr_t> isa = llvm::expectedToOptional(
285 process->ReadPointerFromMemory(isa_pointer));
286 if (isa)
287 objc_class_sp = GetClassDescriptorFromISA(*isa);
288 }
289 }
290 }
291 return objc_class_sp;
292}
293
295 TaggedPointerVendor *tagged_pointer_vendor = GetTaggedPointerVendor();
296 if (!tagged_pointer_vendor)
297 return false;
298
299 // Only Objective-C object values can be tagged pointers.
300 if (!(in_value.GetTypeInfo() & lldb::eTypeIsObjC))
301 return false;
302
303 addr_t ptr = in_value.IsPointerType() ? in_value.GetPointerValue().address
304 : in_value.GetAddressOf().address;
305 if (ptr == LLDB_INVALID_ADDRESS)
306 return false;
307
308 return tagged_pointer_vendor->IsPossibleTaggedPointer(ptr);
309}
310
314 GetClassDescriptor(valobj));
315 if (objc_class_sp) {
316 if (!objc_class_sp->IsKVO())
317 return objc_class_sp;
318
319 ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
320 if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
321 return non_kvo_objc_class_sp;
322 }
323 return ClassDescriptorSP();
324}
325
328 if (isa) {
330
332 m_isa_to_descriptor.find(isa);
333 if (pos != m_isa_to_descriptor.end())
334 return pos->second;
335
336 if (ABISP abi_sp = m_process->GetABI()) {
337 pos = m_isa_to_descriptor.find(abi_sp->FixCodeAddress(isa));
338 if (pos != m_isa_to_descriptor.end())
339 return pos->second;
340 }
341 }
342 return ClassDescriptorSP();
343}
344
347 if (isa) {
348 ClassDescriptorSP objc_class_sp = GetClassDescriptorFromISA(isa);
349 if (objc_class_sp && objc_class_sp->IsValid()) {
350 if (!objc_class_sp->IsKVO())
351 return objc_class_sp;
352
353 ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
354 if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
355 return non_kvo_objc_class_sp;
356 }
357 }
358 return ClassDescriptorSP();
359}
360
363 bool for_expression) {
365 return RealizeType(*m_scratch_ast_ctx_sp, name, for_expression);
366 return CompilerType();
367}
368
370
374
375std::optional<uint64_t>
377 void *opaque_ptr = compiler_type.GetOpaqueQualType();
378 uint64_t cached_size = m_type_size_cache.Lookup(opaque_ptr);
379 if (cached_size > 0)
380 return cached_size;
381
382 ClassDescriptorSP class_descriptor_sp =
384 if (!class_descriptor_sp)
385 return {};
386
387 int32_t max_offset = INT32_MIN;
388 uint64_t sizeof_max = 0;
389 bool found = false;
390
391 for (size_t idx = 0; idx < class_descriptor_sp->GetNumIVars(); idx++) {
392 const auto &ivar = class_descriptor_sp->GetIVarAtIndex(idx);
393 int32_t cur_offset = ivar.m_offset;
394 if (cur_offset > max_offset) {
395 max_offset = cur_offset;
396 sizeof_max = ivar.m_size;
397 found = true;
398 }
399 }
400
401 uint64_t size = 8 * (max_offset + sizeof_max);
402 if (found && size > 0) {
403 m_type_size_cache.Insert(opaque_ptr, size);
404 return size;
405 }
406
407 return {};
408}
409
412 bool throw_bp) {
413 if (language != eLanguageTypeObjC)
415 if (!throw_bp)
417 BreakpointPreconditionSP precondition_sp(
419 return precondition_sp;
420}
421
422// Exception breakpoint Precondition class for ObjC:
424 const char *class_name) {
425 m_class_names.insert(class_name);
426}
427
429 default;
430
435
438
440 Args &args) {
442 if (args.GetArgumentCount() > 0)
444 "The ObjC Exception breakpoint doesn't support extra options.");
445 return error;
446}
447
449 Target &target) {
450 assert(class_name);
451
452 auto *persistent_state = llvm::cast<ClangPersistentVariables>(
454 if (!persistent_state)
455 return {};
456
457 auto clang_modules_decl_vendor_sp =
458 persistent_state->GetClangModulesDeclVendor();
459 if (!clang_modules_decl_vendor_sp)
460 return {};
461
462 auto types = clang_modules_decl_vendor_sp->FindTypes(
463 class_name, /*max_matches*/ UINT32_MAX);
464 if (types.empty())
465 return {};
466
467 return types.front();
468}
469
471 auto *runtime_vendor = GetDeclVendor();
472 if (!runtime_vendor)
473 return {};
474
475 std::vector<CompilerDecl> compiler_decls;
476 runtime_vendor->FindDecls(class_name, false, UINT32_MAX, compiler_decls);
477 if (compiler_decls.empty())
478 return {};
479
480 auto *ctx =
481 llvm::dyn_cast<TypeSystemClang>(compiler_decls[0].GetTypeSystem());
482 if (!ctx)
483 return {};
484
485 return ctx->GetTypeForDecl(compiler_decls[0].GetOpaqueDecl());
486}
487
488std::optional<CompilerType>
490 CompilerType class_type;
491 bool is_pointer_type = false;
492
493 if (TypeSystemClang::IsObjCObjectPointerType(base_type, &class_type))
494 is_pointer_type = true;
496 class_type = base_type;
497 else
498 return std::nullopt;
499
500 if (!class_type)
501 return std::nullopt;
502
503 ConstString class_name(class_type.GetTypeName());
504 if (!class_name)
505 return std::nullopt;
506
507 if (TypeSP complete_objc_class_type_sp =
508 LookupInCompleteClassCache(class_name)) {
509 if (CompilerType complete_class =
510 complete_objc_class_type_sp->GetFullCompilerType();
511 complete_class.GetCompleteType())
512 return is_pointer_type ? complete_class.GetPointerType() : complete_class;
513 }
514
515 assert(m_process);
516 if (CompilerType found =
517 LookupInModulesVendor(class_name, m_process->GetTarget()))
518 return is_pointer_type ? found.GetPointerType() : found;
519
520 if (CompilerType found = LookupInRuntime(class_name))
521 return is_pointer_type ? found.GetPointerType() : found;
522
523 return std::nullopt;
524}
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:545
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:367
llvm::Expected< lldb::addr_t > ReadPointerFromMemory(lldb::addr_t vm_addr)
Definition Process.cpp:2561
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:2787
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