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 return AddClass(isa, descriptor_sp, llvm::djbHash(class_name));
56}
57
59 lldb::addr_t selector,
60 lldb::addr_t impl_addr) {
61 Log *log = GetLog(LLDBLog::Step);
62 LLDB_LOGF(log,
63 "Caching: class 0x%" PRIx64 " selector 0x%" PRIx64
64 " implementation 0x%" PRIx64 ".",
65 class_addr, selector, impl_addr);
66 m_impl_cache.insert(std::pair<ClassAndSel, lldb::addr_t>(
67 ClassAndSel(class_addr, selector), impl_addr));
68}
69
71 llvm::StringRef sel_str,
72 lldb::addr_t impl_addr) {
73 Log *log = GetLog(LLDBLog::Step);
74
75 LLDB_LOG(log, "Caching: class {0} selector {1} implementation {2}.",
76 class_addr, sel_str, impl_addr);
77
78 m_impl_str_cache.insert(std::pair<ClassAndSelStr, lldb::addr_t>(
79 ClassAndSelStr(class_addr, sel_str), impl_addr));
80}
81
83 lldb::addr_t selector) {
84 MsgImplMap::iterator pos, end = m_impl_cache.end();
85 pos = m_impl_cache.find(ClassAndSel(class_addr, selector));
86 if (pos != end)
87 return (*pos).second;
89}
90
92 llvm::StringRef sel_str) {
93 MsgImplStrMap::iterator pos, end = m_impl_str_cache.end();
94 pos = m_impl_str_cache.find(ClassAndSelStr(class_addr, sel_str));
95 if (pos != end)
96 return (*pos).second;
98}
99
102 CompleteClassMap::iterator complete_class_iter =
103 m_complete_class_cache.find(name);
104
105 if (complete_class_iter != m_complete_class_cache.end()) {
106 // Check the weak pointer to make sure the type hasn't been unloaded
107 TypeSP complete_type_sp(complete_class_iter->second.lock());
108
109 if (complete_type_sp)
110 return complete_type_sp;
111 else
112 m_complete_class_cache.erase(name);
113 }
114
115 if (m_negative_complete_class_cache.count(name) > 0)
116 return TypeSP();
117
118 const ModuleList &modules = m_process->GetTarget().GetImages();
119
120 SymbolContextList sc_list;
121 modules.FindSymbolsWithNameAndType(name, eSymbolTypeObjCClass, sc_list);
122 const size_t matching_symbols = sc_list.GetSize();
123
124 if (matching_symbols) {
125 SymbolContext sc;
126
127 sc_list.GetContextAtIndex(0, sc);
128
129 ModuleSP module_sp(sc.module_sp);
130
131 if (!module_sp)
132 return TypeSP();
133
134 TypeQuery query(name.GetStringRef(), TypeQueryOptions::e_exact_match);
135 TypeResults results;
136 module_sp->FindTypes(query, results);
137 for (const TypeSP &type_sp : results.GetTypeMap().Types()) {
139 type_sp->GetForwardCompilerType())) {
140 if (TypePayloadClang(type_sp->GetPayload()).IsCompleteObjCClass()) {
141 m_complete_class_cache[name] = type_sp;
142 return type_sp;
143 }
144 }
145 }
146 }
148 return TypeSP();
149}
150
152 const char *ivar_name) {
154}
155
157 lldb::addr_t value, uint32_t ptr_size, bool allow_NULLs, bool allow_tagged,
158 bool check_version_specific) const {
159 if (!value)
160 return allow_NULLs;
161 if ((value % 2) == 1 && allow_tagged)
162 return true;
163 if ((value % ptr_size) == 0)
164 return (check_version_specific ? CheckPointer(value, ptr_size) : true);
165 else
166 return false;
167}
168
172 if (pos != m_isa_to_descriptor.end())
173 return pos->first;
174 return 0;
175}
176
179 if (!name)
180 return m_isa_to_descriptor.end();
181
183
184 if (m_hash_to_isa_map.empty()) {
185 // No name hashes were provided, we need to just linearly power through
186 // the names and find a match
187 for (auto it = m_isa_to_descriptor.begin(), end = m_isa_to_descriptor.end();
188 it != end; ++it)
189 if (it->second->GetClassName() == name)
190 return it;
191 return m_isa_to_descriptor.end();
192 }
193
194 // Name hashes were provided, so use them to efficiently lookup name to
195 // isa/descriptor
196 const uint32_t name_hash = llvm::djbHash(name.GetStringRef());
197 auto matches_it = m_hash_to_isa_map.find(name_hash);
198 if (matches_it == m_hash_to_isa_map.end())
199 return m_isa_to_descriptor.end();
200
201 for (auto isa : matches_it->second)
202 if (auto pos = m_isa_to_descriptor.find(isa);
203 pos != m_isa_to_descriptor.end() && pos->second->GetClassName() == name)
204 return pos;
205
206 return m_isa_to_descriptor.end();
207}
208
219
221 const ModuleList &module_list) {
222 if (!HasReadObjCLibrary()) {
223 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
224
225 size_t num_modules = module_list.GetSize();
226 for (size_t i = 0; i < num_modules; i++) {
227 auto mod = module_list.GetModuleAtIndex(i);
228 if (IsModuleObjCLibrary(mod)) {
229 ReadObjCLibrary(mod);
230 break;
231 }
232 }
233 }
234}
235
239 if (objc_class_sp) {
240 ClassDescriptorSP objc_super_class_sp(objc_class_sp->GetSuperclass());
241 if (objc_super_class_sp)
242 return objc_super_class_sp->GetISA();
243 }
244 return 0;
245}
246
249 ConstString class_name) {
251 if (pos != m_isa_to_descriptor.end())
252 return pos->second;
253 return ClassDescriptorSP();
254}
255
258 ClassDescriptorSP objc_class_sp;
259 // if we get an invalid VO (which might still happen when playing around with
260 // pointers returned by the expression parser, don't consider this a valid
261 // ObjC object)
262 if (valobj.GetCompilerType().IsValid()) {
263 addr_t isa_pointer = valobj.GetPointerValue().address;
264 if (isa_pointer != LLDB_INVALID_ADDRESS) {
266
267 Process *process = exe_ctx.GetProcessPtr();
268 if (process) {
270 ObjCISA isa = process->ReadPointerFromMemory(isa_pointer, error);
271 if (isa != LLDB_INVALID_ADDRESS)
272 objc_class_sp = GetClassDescriptorFromISA(isa);
273 }
274 }
275 }
276 return objc_class_sp;
277}
278
282 GetClassDescriptor(valobj));
283 if (objc_class_sp) {
284 if (!objc_class_sp->IsKVO())
285 return objc_class_sp;
286
287 ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
288 if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
289 return non_kvo_objc_class_sp;
290 }
291 return ClassDescriptorSP();
292}
293
296 if (isa) {
298
300 m_isa_to_descriptor.find(isa);
301 if (pos != m_isa_to_descriptor.end())
302 return pos->second;
303
304 if (ABISP abi_sp = m_process->GetABI()) {
305 pos = m_isa_to_descriptor.find(abi_sp->FixCodeAddress(isa));
306 if (pos != m_isa_to_descriptor.end())
307 return pos->second;
308 }
309 }
310 return ClassDescriptorSP();
311}
312
315 if (isa) {
316 ClassDescriptorSP objc_class_sp = GetClassDescriptorFromISA(isa);
317 if (objc_class_sp && objc_class_sp->IsValid()) {
318 if (!objc_class_sp->IsKVO())
319 return objc_class_sp;
320
321 ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
322 if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
323 return non_kvo_objc_class_sp;
324 }
325 }
326 return ClassDescriptorSP();
327}
328
331 bool for_expression) {
333 return RealizeType(*m_scratch_ast_ctx_sp, name, for_expression);
334 return CompilerType();
335}
336
338
342
343std::optional<uint64_t>
345 void *opaque_ptr = compiler_type.GetOpaqueQualType();
346 uint64_t cached_size = m_type_size_cache.Lookup(opaque_ptr);
347 if (cached_size > 0)
348 return cached_size;
349
350 ClassDescriptorSP class_descriptor_sp =
352 if (!class_descriptor_sp)
353 return {};
354
355 int32_t max_offset = INT32_MIN;
356 uint64_t sizeof_max = 0;
357 bool found = false;
358
359 for (size_t idx = 0; idx < class_descriptor_sp->GetNumIVars(); idx++) {
360 const auto &ivar = class_descriptor_sp->GetIVarAtIndex(idx);
361 int32_t cur_offset = ivar.m_offset;
362 if (cur_offset > max_offset) {
363 max_offset = cur_offset;
364 sizeof_max = ivar.m_size;
365 found = true;
366 }
367 }
368
369 uint64_t size = 8 * (max_offset + sizeof_max);
370 if (found && size > 0) {
371 m_type_size_cache.Insert(opaque_ptr, size);
372 return size;
373 }
374
375 return {};
376}
377
380 bool throw_bp) {
381 if (language != eLanguageTypeObjC)
383 if (!throw_bp)
385 BreakpointPreconditionSP precondition_sp(
387 return precondition_sp;
388}
389
390// Exception breakpoint Precondition class for ObjC:
392 const char *class_name) {
393 m_class_names.insert(class_name);
394}
395
397 default;
398
403
406
408 Args &args) {
410 if (args.GetArgumentCount() > 0)
412 "The ObjC Exception breakpoint doesn't support extra options.");
413 return error;
414}
415
417 Target &target) {
418 assert(class_name);
419
420 auto *persistent_state = llvm::cast<ClangPersistentVariables>(
422 if (!persistent_state)
423 return {};
424
425 auto clang_modules_decl_vendor_sp =
426 persistent_state->GetClangModulesDeclVendor();
427 if (!clang_modules_decl_vendor_sp)
428 return {};
429
430 auto types = clang_modules_decl_vendor_sp->FindTypes(
431 class_name, /*max_matches*/ UINT32_MAX);
432 if (types.empty())
433 return {};
434
435 return types.front();
436}
437
439 auto *runtime_vendor = GetDeclVendor();
440 if (!runtime_vendor)
441 return {};
442
443 std::vector<CompilerDecl> compiler_decls;
444 runtime_vendor->FindDecls(class_name, false, UINT32_MAX, compiler_decls);
445 if (compiler_decls.empty())
446 return {};
447
448 auto *ctx =
449 llvm::dyn_cast<TypeSystemClang>(compiler_decls[0].GetTypeSystem());
450 if (!ctx)
451 return {};
452
453 return ctx->GetTypeForDecl(compiler_decls[0].GetOpaqueDecl());
454}
455
456std::optional<CompilerType>
458 CompilerType class_type;
459 bool is_pointer_type = false;
460
461 if (TypeSystemClang::IsObjCObjectPointerType(base_type, &class_type))
462 is_pointer_type = true;
464 class_type = base_type;
465 else
466 return std::nullopt;
467
468 if (!class_type)
469 return std::nullopt;
470
471 ConstString class_name(class_type.GetTypeName());
472 if (!class_name)
473 return std::nullopt;
474
475 if (TypeSP complete_objc_class_type_sp =
476 LookupInCompleteClassCache(class_name)) {
477 if (CompilerType complete_class =
478 complete_objc_class_type_sp->GetFullCompilerType();
479 complete_class.GetCompleteType())
480 return is_pointer_type ? complete_class.GetPointerType() : complete_class;
481 }
482
483 assert(m_process);
484 if (CompilerType found =
485 LookupInModulesVendor(class_name, m_process->GetTarget()))
486 return is_pointer_type ? found.GetPointerType() : found;
487
488 if (CompilerType found = LookupInRuntime(class_name))
489 return is_pointer_type ? found.GetPointerType() : found;
490
491 return std::nullopt;
492}
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
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:357
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition Process.cpp:2505
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