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"
23#include "lldb/Utility/Log.h"
24#include "lldb/Utility/Timer.h"
26
27#include "llvm/ADT/StringRef.h"
28#include "llvm/Support/DJB.h"
29#include <optional>
30
31using namespace lldb;
32using namespace lldb_private;
33
35
36// Destructor
38
45
47 static ConstString g_self = ConstString("self");
48 static ConstString g_cmd = ConstString("_cmd");
49 return name == g_self || name == g_cmd;
50}
51
53 const ClassDescriptorSP &descriptor_sp,
54 const char *class_name) {
55 if (isa != 0) {
56 m_isa_to_descriptor[isa] = descriptor_sp;
57 // class_name is assumed to be valid
58 m_hash_to_isa_map.insert(std::make_pair(llvm::djbHash(class_name), isa));
59 return true;
60 }
61 return false;
62}
63
65 lldb::addr_t selector,
66 lldb::addr_t impl_addr) {
67 Log *log = GetLog(LLDBLog::Step);
68 LLDB_LOGF(log,
69 "Caching: class 0x%" PRIx64 " selector 0x%" PRIx64
70 " implementation 0x%" PRIx64 ".",
71 class_addr, selector, impl_addr);
72 m_impl_cache.insert(std::pair<ClassAndSel, lldb::addr_t>(
73 ClassAndSel(class_addr, selector), impl_addr));
74}
75
77 llvm::StringRef sel_str,
78 lldb::addr_t impl_addr) {
79 Log *log = GetLog(LLDBLog::Step);
80
81 LLDB_LOG(log, "Caching: class {0} selector {1} implementation {2}.",
82 class_addr, sel_str, impl_addr);
83
84 m_impl_str_cache.insert(std::pair<ClassAndSelStr, lldb::addr_t>(
85 ClassAndSelStr(class_addr, sel_str), impl_addr));
86}
87
89 lldb::addr_t selector) {
90 MsgImplMap::iterator pos, end = m_impl_cache.end();
91 pos = m_impl_cache.find(ClassAndSel(class_addr, selector));
92 if (pos != end)
93 return (*pos).second;
95}
96
98 llvm::StringRef sel_str) {
99 MsgImplStrMap::iterator pos, end = m_impl_str_cache.end();
100 pos = m_impl_str_cache.find(ClassAndSelStr(class_addr, sel_str));
101 if (pos != end)
102 return (*pos).second;
104}
105
108 CompleteClassMap::iterator complete_class_iter =
109 m_complete_class_cache.find(name);
110
111 if (complete_class_iter != m_complete_class_cache.end()) {
112 // Check the weak pointer to make sure the type hasn't been unloaded
113 TypeSP complete_type_sp(complete_class_iter->second.lock());
114
115 if (complete_type_sp)
116 return complete_type_sp;
117 else
118 m_complete_class_cache.erase(name);
119 }
120
121 if (m_negative_complete_class_cache.count(name) > 0)
122 return TypeSP();
123
124 const ModuleList &modules = m_process->GetTarget().GetImages();
125
126 SymbolContextList sc_list;
127 modules.FindSymbolsWithNameAndType(name, eSymbolTypeObjCClass, sc_list);
128 const size_t matching_symbols = sc_list.GetSize();
129
130 if (matching_symbols) {
131 SymbolContext sc;
132
133 sc_list.GetContextAtIndex(0, sc);
134
135 ModuleSP module_sp(sc.module_sp);
136
137 if (!module_sp)
138 return TypeSP();
139
140 TypeQuery query(name.GetStringRef(), TypeQueryOptions::e_exact_match);
141 TypeResults results;
142 module_sp->FindTypes(query, results);
143 for (const TypeSP &type_sp : results.GetTypeMap().Types()) {
145 type_sp->GetForwardCompilerType())) {
146 if (TypePayloadClang(type_sp->GetPayload()).IsCompleteObjCClass()) {
147 m_complete_class_cache[name] = type_sp;
148 return type_sp;
149 }
150 }
151 }
152 }
154 return TypeSP();
155}
156
158 const char *ivar_name) {
160}
161
163 lldb::addr_t value, uint32_t ptr_size, bool allow_NULLs, bool allow_tagged,
164 bool check_version_specific) const {
165 if (!value)
166 return allow_NULLs;
167 if ((value % 2) == 1 && allow_tagged)
168 return true;
169 if ((value % ptr_size) == 0)
170 return (check_version_specific ? CheckPointer(value, ptr_size) : true);
171 else
172 return false;
173}
174
178 if (pos != m_isa_to_descriptor.end())
179 return pos->first;
180 return 0;
181}
182
186
187 if (name) {
189 if (m_hash_to_isa_map.empty()) {
190 // No name hashes were provided, we need to just linearly power through
191 // the names and find a match
193 pos != end; ++pos) {
194 if (pos->second->GetClassName() == name)
195 return pos;
196 }
197 } else {
198 // Name hashes were provided, so use them to efficiently lookup name to
199 // isa/descriptor
200 const uint32_t name_hash = llvm::djbHash(name.GetStringRef());
201 std::pair<HashToISAIterator, HashToISAIterator> range =
202 m_hash_to_isa_map.equal_range(name_hash);
203 for (HashToISAIterator range_pos = range.first; range_pos != range.second;
204 ++range_pos) {
206 m_isa_to_descriptor.find(range_pos->second);
207 if (pos != m_isa_to_descriptor.end()) {
208 if (pos->second->GetClassName() == name)
209 return pos;
210 }
211 }
212 }
213 }
214 return end;
215}
216
227
229 const ModuleList &module_list) {
230 if (!HasReadObjCLibrary()) {
231 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
232
233 size_t num_modules = module_list.GetSize();
234 for (size_t i = 0; i < num_modules; i++) {
235 auto mod = module_list.GetModuleAtIndex(i);
236 if (IsModuleObjCLibrary(mod)) {
237 ReadObjCLibrary(mod);
238 break;
239 }
240 }
241 }
242}
243
247 if (objc_class_sp) {
248 ClassDescriptorSP objc_super_class_sp(objc_class_sp->GetSuperclass());
249 if (objc_super_class_sp)
250 return objc_super_class_sp->GetISA();
251 }
252 return 0;
253}
254
257 ConstString class_name) {
259 if (pos != m_isa_to_descriptor.end())
260 return pos->second;
261 return ClassDescriptorSP();
262}
263
266 ClassDescriptorSP objc_class_sp;
267 // if we get an invalid VO (which might still happen when playing around with
268 // pointers returned by the expression parser, don't consider this a valid
269 // ObjC object)
270 if (valobj.GetCompilerType().IsValid()) {
271 addr_t isa_pointer = valobj.GetPointerValue().address;
272 if (isa_pointer != LLDB_INVALID_ADDRESS) {
274
275 Process *process = exe_ctx.GetProcessPtr();
276 if (process) {
278 ObjCISA isa = process->ReadPointerFromMemory(isa_pointer, error);
279 if (isa != LLDB_INVALID_ADDRESS)
280 objc_class_sp = GetClassDescriptorFromISA(isa);
281 }
282 }
283 }
284 return objc_class_sp;
285}
286
290 GetClassDescriptor(valobj));
291 if (objc_class_sp) {
292 if (!objc_class_sp->IsKVO())
293 return objc_class_sp;
294
295 ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
296 if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
297 return non_kvo_objc_class_sp;
298 }
299 return ClassDescriptorSP();
300}
301
304 if (isa) {
306
308 m_isa_to_descriptor.find(isa);
309 if (pos != m_isa_to_descriptor.end())
310 return pos->second;
311
312 if (ABISP abi_sp = m_process->GetABI()) {
313 pos = m_isa_to_descriptor.find(abi_sp->FixCodeAddress(isa));
314 if (pos != m_isa_to_descriptor.end())
315 return pos->second;
316 }
317 }
318 return ClassDescriptorSP();
319}
320
323 if (isa) {
324 ClassDescriptorSP objc_class_sp = GetClassDescriptorFromISA(isa);
325 if (objc_class_sp && objc_class_sp->IsValid()) {
326 if (!objc_class_sp->IsKVO())
327 return objc_class_sp;
328
329 ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
330 if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
331 return non_kvo_objc_class_sp;
332 }
333 }
334 return ClassDescriptorSP();
335}
336
339 bool for_expression) {
341 return RealizeType(*m_scratch_ast_ctx_sp, name, for_expression);
342 return CompilerType();
343}
344
346
350
351std::optional<uint64_t>
353 void *opaque_ptr = compiler_type.GetOpaqueQualType();
354 uint64_t cached_size = m_type_size_cache.Lookup(opaque_ptr);
355 if (cached_size > 0)
356 return cached_size;
357
358 ClassDescriptorSP class_descriptor_sp =
360 if (!class_descriptor_sp)
361 return {};
362
363 int32_t max_offset = INT32_MIN;
364 uint64_t sizeof_max = 0;
365 bool found = false;
366
367 for (size_t idx = 0; idx < class_descriptor_sp->GetNumIVars(); idx++) {
368 const auto &ivar = class_descriptor_sp->GetIVarAtIndex(idx);
369 int32_t cur_offset = ivar.m_offset;
370 if (cur_offset > max_offset) {
371 max_offset = cur_offset;
372 sizeof_max = ivar.m_size;
373 found = true;
374 }
375 }
376
377 uint64_t size = 8 * (max_offset + sizeof_max);
378 if (found && size > 0) {
379 m_type_size_cache.Insert(opaque_ptr, size);
380 return size;
381 }
382
383 return {};
384}
385
388 bool throw_bp) {
389 if (language != eLanguageTypeObjC)
391 if (!throw_bp)
393 BreakpointPreconditionSP precondition_sp(
395 return precondition_sp;
396}
397
398// Exception breakpoint Precondition class for ObjC:
400 const char *class_name) {
401 m_class_names.insert(class_name);
402}
403
405 default;
406
411
414
416 Args &args) {
418 if (args.GetArgumentCount() > 0)
420 "The ObjC Exception breakpoint doesn't support extra options.");
421 return error;
422}
423
425 Target &target) {
426 assert(class_name);
427
428 auto *persistent_state = llvm::cast<ClangPersistentVariables>(
430 if (!persistent_state)
431 return {};
432
433 auto clang_modules_decl_vendor_sp =
434 persistent_state->GetClangModulesDeclVendor();
435 if (!clang_modules_decl_vendor_sp)
436 return {};
437
438 auto types = clang_modules_decl_vendor_sp->FindTypes(
439 class_name, /*max_matches*/ UINT32_MAX);
440 if (types.empty())
441 return {};
442
443 return types.front();
444}
445
447 auto *runtime_vendor = GetDeclVendor();
448 if (!runtime_vendor)
449 return {};
450
451 std::vector<CompilerDecl> compiler_decls;
452 runtime_vendor->FindDecls(class_name, false, UINT32_MAX, compiler_decls);
453 if (compiler_decls.empty())
454 return {};
455
456 auto *ctx =
457 llvm::dyn_cast<TypeSystemClang>(compiler_decls[0].GetTypeSystem());
458 if (!ctx)
459 return {};
460
461 return ctx->GetTypeForDecl(compiler_decls[0].GetOpaqueDecl());
462}
463
464std::optional<CompilerType>
466 CompilerType class_type;
467 bool is_pointer_type = false;
468
469 if (TypeSystemClang::IsObjCObjectPointerType(base_type, &class_type))
470 is_pointer_type = true;
472 class_type = base_type;
473 else
474 return std::nullopt;
475
476 if (!class_type)
477 return std::nullopt;
478
479 ConstString class_name(class_type.GetTypeName());
480 if (!class_name)
481 return std::nullopt;
482
483 if (TypeSP complete_objc_class_type_sp =
484 LookupInCompleteClassCache(class_name)) {
485 if (CompilerType complete_class =
486 complete_objc_class_type_sp->GetFullCompilerType();
487 complete_class.GetCompleteType())
488 return is_pointer_type ? complete_class.GetPointerType() : complete_class;
489 }
490
491 assert(m_process);
492 if (CompilerType found =
493 LookupInModulesVendor(class_name, m_process->GetTarget()))
494 return is_pointer_type ? found.GetPointerType() : found;
495
496 if (CompilerType found = LookupInRuntime(class_name))
497 return is_pointer_type ? found.GetPointerType() : found;
498
499 return std::nullopt;
500}
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:369
#define LLDB_LOGF(log,...)
Definition Log.h:383
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
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:354
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition Process.cpp:2329
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:2681
TypeIterable Types() const
Definition TypeMap.h:50
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:332
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