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"
18#include "lldb/Symbol/Type.h"
21#include "lldb/Target/ABI.h"
22#include "lldb/Target/Target.h"
24#include "lldb/Utility/Log.h"
25#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
40 : LanguageRuntime(process), m_impl_cache(), m_impl_str_cache(),
41 m_has_new_literals_and_indexing(eLazyBoolCalculate),
42 m_isa_to_descriptor(), m_hash_to_isa_map(), m_type_size_cache(),
43 m_isa_to_descriptor_stop_id(UINT32_MAX), m_complete_class_cache(),
44 m_negative_complete_class_cache() {}
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 if (log) {
69 LLDB_LOGF(log,
70 "Caching: class 0x%" PRIx64 " selector 0x%" PRIx64
71 " implementation 0x%" PRIx64 ".",
72 class_addr, selector, impl_addr);
73 }
74 m_impl_cache.insert(std::pair<ClassAndSel, lldb::addr_t>(
75 ClassAndSel(class_addr, selector), impl_addr));
76}
77
79 llvm::StringRef sel_str,
80 lldb::addr_t impl_addr) {
81 Log *log = GetLog(LLDBLog::Step);
82
83 LLDB_LOG(log, "Caching: class {0} selector {1} implementation {2}.",
84 class_addr, sel_str, impl_addr);
85
86 m_impl_str_cache.insert(std::pair<ClassAndSelStr, lldb::addr_t>(
87 ClassAndSelStr(class_addr, sel_str), impl_addr));
88}
89
91 lldb::addr_t selector) {
92 MsgImplMap::iterator pos, end = m_impl_cache.end();
93 pos = m_impl_cache.find(ClassAndSel(class_addr, selector));
94 if (pos != end)
95 return (*pos).second;
97}
98
100 llvm::StringRef sel_str) {
101 MsgImplStrMap::iterator pos, end = m_impl_str_cache.end();
102 pos = m_impl_str_cache.find(ClassAndSelStr(class_addr, sel_str));
103 if (pos != end)
104 return (*pos).second;
106}
107
110 CompleteClassMap::iterator complete_class_iter =
111 m_complete_class_cache.find(name);
112
113 if (complete_class_iter != m_complete_class_cache.end()) {
114 // Check the weak pointer to make sure the type hasn't been unloaded
115 TypeSP complete_type_sp(complete_class_iter->second.lock());
116
117 if (complete_type_sp)
118 return complete_type_sp;
119 else
120 m_complete_class_cache.erase(name);
121 }
122
123 if (m_negative_complete_class_cache.count(name) > 0)
124 return TypeSP();
125
126 const ModuleList &modules = m_process->GetTarget().GetImages();
127
128 SymbolContextList sc_list;
129 modules.FindSymbolsWithNameAndType(name, eSymbolTypeObjCClass, sc_list);
130 const size_t matching_symbols = sc_list.GetSize();
131
132 if (matching_symbols) {
133 SymbolContext sc;
134
135 sc_list.GetContextAtIndex(0, sc);
136
137 ModuleSP module_sp(sc.module_sp);
138
139 if (!module_sp)
140 return TypeSP();
141
142 TypeQuery query(name.GetStringRef(), TypeQueryOptions::e_exact_match);
143 TypeResults results;
144 module_sp->FindTypes(query, results);
145 for (const TypeSP &type_sp : results.GetTypeMap().Types()) {
147 type_sp->GetForwardCompilerType())) {
148 if (TypePayloadClang(type_sp->GetPayload()).IsCompleteObjCClass()) {
149 m_complete_class_cache[name] = type_sp;
150 return type_sp;
151 }
152 }
153 }
154 }
156 return TypeSP();
157}
158
160 const char *ivar_name) {
162}
163
165 lldb::addr_t value, uint32_t ptr_size, bool allow_NULLs, bool allow_tagged,
166 bool check_version_specific) const {
167 if (!value)
168 return allow_NULLs;
169 if ((value % 2) == 1 && allow_tagged)
170 return true;
171 if ((value % ptr_size) == 0)
172 return (check_version_specific ? CheckPointer(value, ptr_size) : true);
173 else
174 return false;
175}
176
180 if (pos != m_isa_to_descriptor.end())
181 return pos->first;
182 return 0;
183}
184
188
189 if (name) {
191 if (m_hash_to_isa_map.empty()) {
192 // No name hashes were provided, we need to just linearly power through
193 // the names and find a match
195 pos != end; ++pos) {
196 if (pos->second->GetClassName() == name)
197 return pos;
198 }
199 } else {
200 // Name hashes were provided, so use them to efficiently lookup name to
201 // isa/descriptor
202 const uint32_t name_hash = llvm::djbHash(name.GetStringRef());
203 std::pair<HashToISAIterator, HashToISAIterator> range =
204 m_hash_to_isa_map.equal_range(name_hash);
205 for (HashToISAIterator range_pos = range.first; range_pos != range.second;
206 ++range_pos) {
208 m_isa_to_descriptor.find(range_pos->second);
209 if (pos != m_isa_to_descriptor.end()) {
210 if (pos->second->GetClassName() == name)
211 return pos;
212 }
213 }
214 }
215 }
216 return end;
217}
218
222 if (update_if_needed)
224
228}
229
231 const ModuleList &module_list) {
232 if (!HasReadObjCLibrary()) {
233 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
234
235 size_t num_modules = module_list.GetSize();
236 for (size_t i = 0; i < num_modules; i++) {
237 auto mod = module_list.GetModuleAtIndex(i);
238 if (IsModuleObjCLibrary(mod)) {
239 ReadObjCLibrary(mod);
240 break;
241 }
242 }
243 }
244}
245
249 if (objc_class_sp) {
250 ClassDescriptorSP objc_super_class_sp(objc_class_sp->GetSuperclass());
251 if (objc_super_class_sp)
252 return objc_super_class_sp->GetISA();
253 }
254 return 0;
255}
256
259 ConstString class_name) {
261 if (pos != m_isa_to_descriptor.end())
262 return pos->second;
263 return ClassDescriptorSP();
264}
265
268 ClassDescriptorSP objc_class_sp;
269 // if we get an invalid VO (which might still happen when playing around with
270 // pointers returned by the expression parser, don't consider this a valid
271 // ObjC object)
272 if (valobj.GetCompilerType().IsValid()) {
273 addr_t isa_pointer = valobj.GetPointerValue();
274 if (isa_pointer != LLDB_INVALID_ADDRESS) {
276
277 Process *process = exe_ctx.GetProcessPtr();
278 if (process) {
280 ObjCISA isa = process->ReadPointerFromMemory(isa_pointer, error);
281 if (isa != LLDB_INVALID_ADDRESS)
282 objc_class_sp = GetClassDescriptorFromISA(isa);
283 }
284 }
285 }
286 return objc_class_sp;
287}
288
292 GetClassDescriptor(valobj));
293 if (objc_class_sp) {
294 if (!objc_class_sp->IsKVO())
295 return objc_class_sp;
296
297 ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
298 if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
299 return non_kvo_objc_class_sp;
300 }
301 return ClassDescriptorSP();
302}
303
306 if (isa) {
308
310 m_isa_to_descriptor.find(isa);
311 if (pos != m_isa_to_descriptor.end())
312 return pos->second;
313
314 if (ABISP abi_sp = m_process->GetABI()) {
315 pos = m_isa_to_descriptor.find(abi_sp->FixCodeAddress(isa));
316 if (pos != m_isa_to_descriptor.end())
317 return pos->second;
318 }
319 }
320 return ClassDescriptorSP();
321}
322
325 if (isa) {
326 ClassDescriptorSP objc_class_sp = GetClassDescriptorFromISA(isa);
327 if (objc_class_sp && objc_class_sp->IsValid()) {
328 if (!objc_class_sp->IsKVO())
329 return objc_class_sp;
330
331 ClassDescriptorSP non_kvo_objc_class_sp(objc_class_sp->GetSuperclass());
332 if (non_kvo_objc_class_sp && non_kvo_objc_class_sp->IsValid())
333 return non_kvo_objc_class_sp;
334 }
335 }
336 return ClassDescriptorSP();
337}
338
341 bool for_expression) {
342 if (m_scratch_ast_ctx_sp)
343 return RealizeType(*m_scratch_ast_ctx_sp, name, for_expression);
344 return CompilerType();
345}
346
348
350 return nullptr;
351}
352
353std::optional<uint64_t>
355 void *opaque_ptr = compiler_type.GetOpaqueQualType();
356 uint64_t cached_size = m_type_size_cache.Lookup(opaque_ptr);
357 if (cached_size > 0)
358 return cached_size;
359
360 ClassDescriptorSP class_descriptor_sp =
362 if (!class_descriptor_sp)
363 return {};
364
365 int32_t max_offset = INT32_MIN;
366 uint64_t sizeof_max = 0;
367 bool found = false;
368
369 for (size_t idx = 0; idx < class_descriptor_sp->GetNumIVars(); idx++) {
370 const auto &ivar = class_descriptor_sp->GetIVarAtIndex(idx);
371 int32_t cur_offset = ivar.m_offset;
372 if (cur_offset > max_offset) {
373 max_offset = cur_offset;
374 sizeof_max = ivar.m_size;
375 found = true;
376 }
377 }
378
379 uint64_t size = 8 * (max_offset + sizeof_max);
380 if (found && size > 0) {
381 m_type_size_cache.Insert(opaque_ptr, size);
382 return size;
383 }
384
385 return {};
386}
387
390 bool throw_bp) {
391 if (language != eLanguageTypeObjC)
393 if (!throw_bp)
395 BreakpointPreconditionSP precondition_sp(
397 return precondition_sp;
398}
399
400// Exception breakpoint Precondition class for ObjC:
402 const char *class_name) {
403 m_class_names.insert(class_name);
404}
405
407 default;
408
410 StoppointCallbackContext &context) {
411 return true;
412}
413
415 Stream &stream, lldb::DescriptionLevel level) {}
416
418 Args &args) {
420 if (args.GetArgumentCount() > 0)
421 error.SetErrorString(
422 "The ObjC Exception breakpoint doesn't support extra options.");
423 return error;
424}
425
426std::optional<CompilerType>
428 CompilerType class_type;
429 bool is_pointer_type = false;
430
431 if (TypeSystemClang::IsObjCObjectPointerType(base_type, &class_type))
432 is_pointer_type = true;
434 class_type = base_type;
435 else
436 return std::nullopt;
437
438 if (!class_type)
439 return std::nullopt;
440
441 ConstString class_name(class_type.GetTypeName());
442 if (!class_name)
443 return std::nullopt;
444
445 TypeSP complete_objc_class_type_sp = LookupInCompleteClassCache(class_name);
446 if (!complete_objc_class_type_sp)
447 return std::nullopt;
448
449 CompilerType complete_class(
450 complete_objc_class_type_sp->GetFullCompilerType());
451 if (complete_class.GetCompleteType()) {
452 if (is_pointer_type)
453 return complete_class.GetPointerType();
454 else
455 return complete_class;
456 }
457
458 return std::nullopt;
459}
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:359
#define LLDB_LOGF(log,...)
Definition: Log.h:366
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:116
Generic representation of a type in a programming language.
Definition: CompilerType.h:36
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
lldb::opaque_compiler_type_t GetOpaqueQualType() const
Definition: CompilerType.h:287
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.
Definition: ConstString.h:197
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
Process * GetProcessPtr() const
Returns a pointer to the process object.
A collection class for Module objects.
Definition: ModuleList.h:103
std::recursive_mutex & GetMutex() const
Definition: ModuleList.h:230
void FindSymbolsWithNameAndType(ConstString name, lldb::SymbolType symbol_type, SymbolContextList &sc_list) const
Definition: ModuleList.cpp:527
lldb::ModuleSP GetModuleAtIndex(size_t idx) const
Get the module shared pointer for the module at index idx.
Definition: ModuleList.cpp:429
size_t GetSize() const
Gets the size of the module list.
Definition: ModuleList.cpp:638
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
void GetDescription(Stream &stream, lldb::DescriptionLevel level) override
bool EvaluatePrecondition(StoppointCallbackContext &context) override
HashToISAMap::iterator HashToISAIterator
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)
bool IsAllowedRuntimeValue(ConstString name) override
Check whether the name is "self" or "_cmd" and should show up in "frame variable".
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:341
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition: Process.cpp:2259
const lldb::ABISP & GetABI()
Definition: Process.cpp:1531
Target & GetTarget()
Get the target object pointer for this module.
Definition: Process.h:1285
Process * m_process
Definition: Runtime.h:29
An error handling class.
Definition: Status.h:44
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.
Definition: SymbolContext.h:34
lldb::ModuleSP module_sp
The Module for a given query.
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition: Target.h:986
void Insert(_KeyType k, _ValueType v)
TypeIterable Types() const
Definition: TypeMap.h:49
The implementation of lldb::Type's m_payload field for TypeSystemClang.
A class that contains all state required for type lookups.
Definition: Type.h:98
This class tracks the state and results of a TypeQuery.
Definition: Type.h:310
TypeMap & GetTypeMap()
Definition: Type.h:352
static bool IsObjCObjectOrInterfaceType(const CompilerType &type)
static bool IsObjCObjectPointerType(const CompilerType &type, CompilerType *target_type=nullptr)
lldb::addr_t GetPointerValue(AddressType *address_type=nullptr)
CompilerType GetCompilerType()
Definition: ValueObject.h:352
const ExecutionContextRef & GetExecutionContextRef() const
Definition: ValueObject.h:330
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
#define UINT32_MAX
Definition: lldb-defines.h:19
#define LLDB_INVALID_IVAR_OFFSET
Definition: lldb-defines.h:84
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:331
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::ABI > ABISP
Definition: lldb-forward.h:315
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
LanguageType
Programming language type.
@ eLanguageTypeObjC
Objective-C.
std::shared_ptr< lldb_private::Type > TypeSP
Definition: lldb-forward.h:457
std::shared_ptr< lldb_private::BreakpointPrecondition > BreakpointPreconditionSP
Definition: lldb-forward.h:325
@ eSymbolTypeObjCClass
uint64_t addr_t
Definition: lldb-types.h:80
std::shared_ptr< lldb_private::Module > ModuleSP
Definition: lldb-forward.h:371