1 //===-- AppleObjCRuntime.cpp ----------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "AppleObjCRuntime.h"
10 #include "AppleObjCRuntimeV1.h"
11 #include "AppleObjCRuntimeV2.h"
12 #include "AppleObjCTrampolineHandler.h"
13 #include "Plugins/Language/ObjC/NSString.h"
14 #include "Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h"
15 #include "Plugins/Process/Utility/HistoryThread.h"
16 #include "lldb/Breakpoint/BreakpointLocation.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/ModuleList.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/Section.h"
21 #include "lldb/DataFormatters/FormattersHelpers.h"
22 #include "lldb/Expression/DiagnosticManager.h"
23 #include "lldb/Expression/FunctionCaller.h"
24 #include "lldb/Symbol/ObjectFile.h"
25 #include "lldb/Target/ExecutionContext.h"
26 #include "lldb/Target/Process.h"
27 #include "lldb/Target/RegisterContext.h"
28 #include "lldb/Target/StopInfo.h"
29 #include "lldb/Target/Target.h"
30 #include "lldb/Target/Thread.h"
31 #include "lldb/Utility/ConstString.h"
32 #include "lldb/Utility/ErrorMessages.h"
33 #include "lldb/Utility/LLDBLog.h"
34 #include "lldb/Utility/Log.h"
35 #include "lldb/Utility/Scalar.h"
36 #include "lldb/Utility/Status.h"
37 #include "lldb/Utility/StreamString.h"
38 #include "lldb/ValueObject/ValueObject.h"
39 #include "lldb/ValueObject/ValueObjectConstResult.h"
40 #include "clang/AST/Type.h"
42 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
47 using namespace lldb_private
;
49 LLDB_PLUGIN_DEFINE(AppleObjCRuntime
)
51 char AppleObjCRuntime::ID
= 0;
53 AppleObjCRuntime::~AppleObjCRuntime() = default;
55 AppleObjCRuntime::AppleObjCRuntime(Process
*process
)
56 : ObjCLanguageRuntime(process
), m_read_objc_library(false),
57 m_objc_trampoline_handler_up(), m_Foundation_major() {
58 ReadObjCLibraryIfNeeded(process
->GetTarget().GetImages());
61 void AppleObjCRuntime::Initialize() {
62 AppleObjCRuntimeV2::Initialize();
63 AppleObjCRuntimeV1::Initialize();
66 void AppleObjCRuntime::Terminate() {
67 AppleObjCRuntimeV2::Terminate();
68 AppleObjCRuntimeV1::Terminate();
71 llvm::Error
AppleObjCRuntime::GetObjectDescription(Stream
&str
,
72 ValueObject
&valobj
) {
73 CompilerType
compiler_type(valobj
.GetCompilerType());
75 // ObjC objects can only be pointers (or numbers that actually represents
76 // pointers but haven't been typecast, because reasons..)
77 if (!compiler_type
.IsIntegerType(is_signed
) && !compiler_type
.IsPointerType())
78 return llvm::createStringError("not a pointer type");
80 // Make the argument list: we pass one arg, the address of our pointer, to
81 // the print function.
84 if (!valobj
.ResolveValue(val
.GetScalar()))
85 return llvm::createStringError("pointer value could not be resolved");
87 // Value Objects may not have a process in their ExecutionContextRef. But we
88 // need to have one in the ref we pass down to eventually call description.
89 // Get it from the target if it isn't present.
90 ExecutionContext exe_ctx
;
91 if (valobj
.GetProcessSP()) {
92 exe_ctx
= ExecutionContext(valobj
.GetExecutionContextRef());
94 exe_ctx
.SetContext(valobj
.GetTargetSP(), true);
95 if (!exe_ctx
.HasProcessScope())
96 return llvm::createStringError("no process");
98 return GetObjectDescription(str
, val
, exe_ctx
.GetBestExecutionContextScope());
102 AppleObjCRuntime::GetObjectDescription(Stream
&strm
, Value
&value
,
103 ExecutionContextScope
*exe_scope
) {
104 if (!m_read_objc_library
)
105 return llvm::createStringError("Objective-C runtime not loaded");
107 ExecutionContext exe_ctx
;
108 exe_scope
->CalculateExecutionContext(exe_ctx
);
109 Process
*process
= exe_ctx
.GetProcessPtr();
111 return llvm::createStringError("no process");
113 // We need other parts of the exe_ctx, but the processes have to match.
114 assert(m_process
== process
);
116 // Get the function address for the print function.
117 const Address
*function_address
= GetPrintForDebuggerAddr();
118 if (!function_address
)
119 return llvm::createStringError("no print function");
121 Target
*target
= exe_ctx
.GetTargetPtr();
122 CompilerType compiler_type
= value
.GetCompilerType();
124 if (!TypeSystemClang::IsObjCObjectPointerType(compiler_type
))
125 return llvm::createStringError(
126 "Value doesn't point to an ObjC object.\n");
128 // If it is not a pointer, see if we can make it into a pointer.
129 TypeSystemClangSP scratch_ts_sp
=
130 ScratchTypeSystemClang::GetForTarget(*target
);
132 return llvm::createStringError("no scratch type system");
134 CompilerType opaque_type
= scratch_ts_sp
->GetBasicType(eBasicTypeObjCID
);
137 scratch_ts_sp
->GetBasicType(eBasicTypeVoid
).GetPointerType();
138 // value.SetContext(Value::eContextTypeClangType, opaque_type_ptr);
139 value
.SetCompilerType(opaque_type
);
142 ValueList arg_value_list
;
143 arg_value_list
.PushValue(value
);
145 // This is the return value:
146 TypeSystemClangSP scratch_ts_sp
=
147 ScratchTypeSystemClang::GetForTarget(*target
);
149 return llvm::createStringError("no scratch type system");
151 CompilerType return_compiler_type
= scratch_ts_sp
->GetCStringType(true);
153 // ret.SetContext(Value::eContextTypeClangType, return_compiler_type);
154 ret
.SetCompilerType(return_compiler_type
);
156 if (!exe_ctx
.GetFramePtr()) {
157 Thread
*thread
= exe_ctx
.GetThreadPtr();
158 if (thread
== nullptr) {
159 exe_ctx
.SetThreadSP(process
->GetThreadList().GetSelectedThread());
160 thread
= exe_ctx
.GetThreadPtr();
163 exe_ctx
.SetFrameSP(thread
->GetSelectedFrame(DoNoSelectMostRelevantFrame
));
167 // Now we're ready to call the function:
169 DiagnosticManager diagnostics
;
170 lldb::addr_t wrapper_struct_addr
= LLDB_INVALID_ADDRESS
;
172 if (!m_print_object_caller_up
) {
174 m_print_object_caller_up
.reset(
175 exe_scope
->CalculateTarget()->GetFunctionCallerForLanguage(
176 eLanguageTypeObjC
, return_compiler_type
, *function_address
,
177 arg_value_list
, "objc-object-description", error
));
179 m_print_object_caller_up
.reset();
180 return llvm::createStringError(
182 "could not get function runner to call print for debugger "
186 m_print_object_caller_up
->InsertFunction(exe_ctx
, wrapper_struct_addr
,
189 m_print_object_caller_up
->WriteFunctionArguments(
190 exe_ctx
, wrapper_struct_addr
, arg_value_list
, diagnostics
);
193 EvaluateExpressionOptions options
;
194 options
.SetUnwindOnError(true);
195 options
.SetTryAllThreads(true);
196 options
.SetStopOthers(true);
197 options
.SetIgnoreBreakpoints(true);
198 options
.SetTimeout(process
->GetUtilityExpressionTimeout());
199 options
.SetIsForUtilityExpr(true);
201 ExpressionResults results
= m_print_object_caller_up
->ExecuteFunction(
202 exe_ctx
, &wrapper_struct_addr
, options
, diagnostics
, ret
);
203 if (results
!= eExpressionCompleted
)
204 return llvm::createStringError(
205 "could not evaluate print object function: " + toString(results
));
207 addr_t result_ptr
= ret
.GetScalar().ULongLong(LLDB_INVALID_ADDRESS
);
211 size_t full_buffer_len
= sizeof(buf
) - 1;
212 size_t curr_len
= full_buffer_len
;
213 while (curr_len
== full_buffer_len
) {
215 curr_len
= process
->ReadCStringFromMemory(result_ptr
+ cstr_len
, buf
,
217 strm
.Write(buf
, curr_len
);
218 cstr_len
+= curr_len
;
221 return llvm::Error::success();
222 return llvm::createStringError("empty object description");
225 lldb::ModuleSP
AppleObjCRuntime::GetObjCModule() {
226 ModuleSP
module_sp(m_objc_module_wp
.lock());
230 Process
*process
= GetProcess();
232 const ModuleList
&modules
= process
->GetTarget().GetImages();
233 for (uint32_t idx
= 0; idx
< modules
.GetSize(); idx
++) {
234 module_sp
= modules
.GetModuleAtIndex(idx
);
235 if (AppleObjCRuntime::AppleIsModuleObjCLibrary(module_sp
)) {
236 m_objc_module_wp
= module_sp
;
244 Address
*AppleObjCRuntime::GetPrintForDebuggerAddr() {
245 if (!m_PrintForDebugger_addr
) {
246 const ModuleList
&modules
= m_process
->GetTarget().GetImages();
248 SymbolContextList contexts
;
249 SymbolContext context
;
251 modules
.FindSymbolsWithNameAndType(ConstString("_NSPrintForDebugger"),
252 eSymbolTypeCode
, contexts
);
253 if (contexts
.IsEmpty()) {
254 modules
.FindSymbolsWithNameAndType(ConstString("_CFPrintForDebugger"),
255 eSymbolTypeCode
, contexts
);
256 if (contexts
.IsEmpty())
260 contexts
.GetContextAtIndex(0, context
);
262 m_PrintForDebugger_addr
=
263 std::make_unique
<Address
>(context
.symbol
->GetAddress());
266 return m_PrintForDebugger_addr
.get();
269 bool AppleObjCRuntime::CouldHaveDynamicValue(ValueObject
&in_value
) {
270 return in_value
.GetCompilerType().IsPossibleDynamicType(
272 false, // do not check C++
276 bool AppleObjCRuntime::GetDynamicTypeAndAddress(
277 ValueObject
&in_value
, lldb::DynamicValueType use_dynamic
,
278 TypeAndOrName
&class_type_or_name
, Address
&address
,
279 Value::ValueType
&value_type
) {
284 AppleObjCRuntime::FixUpDynamicType(const TypeAndOrName
&type_and_or_name
,
285 ValueObject
&static_value
) {
286 CompilerType
static_type(static_value
.GetCompilerType());
287 Flags
static_type_flags(static_type
.GetTypeInfo());
289 TypeAndOrName
ret(type_and_or_name
);
290 if (type_and_or_name
.HasType()) {
291 // The type will always be the type of the dynamic object. If our parent's
292 // type was a pointer, then our type should be a pointer to the type of the
293 // dynamic object. If a reference, then the original type should be
295 CompilerType orig_type
= type_and_or_name
.GetCompilerType();
296 CompilerType corrected_type
= orig_type
;
297 if (static_type_flags
.AllSet(eTypeIsPointer
))
298 corrected_type
= orig_type
.GetPointerType();
299 ret
.SetCompilerType(corrected_type
);
301 // If we are here we need to adjust our dynamic type name to include the
302 // correct & or * symbol
303 std::string
corrected_name(type_and_or_name
.GetName().GetCString());
304 if (static_type_flags
.AllSet(eTypeIsPointer
))
305 corrected_name
.append(" *");
306 // the parent type should be a correctly pointer'ed or referenc'ed type
307 ret
.SetCompilerType(static_type
);
308 ret
.SetName(corrected_name
.c_str());
313 bool AppleObjCRuntime::AppleIsModuleObjCLibrary(const ModuleSP
&module_sp
) {
315 const FileSpec
&module_file_spec
= module_sp
->GetFileSpec();
316 static ConstString
ObjCName("libobjc.A.dylib");
318 if (module_file_spec
) {
319 if (module_file_spec
.GetFilename() == ObjCName
)
326 // we use the version of Foundation to make assumptions about the ObjC runtime
328 uint32_t AppleObjCRuntime::GetFoundationVersion() {
329 if (!m_Foundation_major
) {
330 const ModuleList
&modules
= m_process
->GetTarget().GetImages();
331 for (uint32_t idx
= 0; idx
< modules
.GetSize(); idx
++) {
332 lldb::ModuleSP module_sp
= modules
.GetModuleAtIndex(idx
);
335 if (strcmp(module_sp
->GetFileSpec().GetFilename().AsCString(""),
336 "Foundation") == 0) {
337 m_Foundation_major
= module_sp
->GetVersion().getMajor();
338 return *m_Foundation_major
;
341 return LLDB_INVALID_MODULE_VERSION
;
343 return *m_Foundation_major
;
346 void AppleObjCRuntime::GetValuesForGlobalCFBooleans(lldb::addr_t
&cf_true
,
347 lldb::addr_t
&cf_false
) {
348 cf_true
= cf_false
= LLDB_INVALID_ADDRESS
;
351 bool AppleObjCRuntime::IsModuleObjCLibrary(const ModuleSP
&module_sp
) {
352 return AppleIsModuleObjCLibrary(module_sp
);
355 bool AppleObjCRuntime::ReadObjCLibrary(const ModuleSP
&module_sp
) {
356 // Maybe check here and if we have a handler already, and the UUID of this
357 // module is the same as the one in the current module, then we don't have to
359 m_objc_trampoline_handler_up
= std::make_unique
<AppleObjCTrampolineHandler
>(
360 m_process
->shared_from_this(), module_sp
);
361 if (m_objc_trampoline_handler_up
!= nullptr) {
362 m_read_objc_library
= true;
368 ThreadPlanSP
AppleObjCRuntime::GetStepThroughTrampolinePlan(Thread
&thread
,
370 ThreadPlanSP thread_plan_sp
;
371 if (m_objc_trampoline_handler_up
)
372 thread_plan_sp
= m_objc_trampoline_handler_up
->GetStepThroughDispatchPlan(
373 thread
, stop_others
);
374 return thread_plan_sp
;
378 ObjCLanguageRuntime::ObjCRuntimeVersions
379 AppleObjCRuntime::GetObjCVersion(Process
*process
, ModuleSP
&objc_module_sp
) {
381 return ObjCRuntimeVersions::eObjC_VersionUnknown
;
383 Target
&target
= process
->GetTarget();
384 if (target
.GetArchitecture().GetTriple().getVendor() !=
385 llvm::Triple::VendorType::Apple
)
386 return ObjCRuntimeVersions::eObjC_VersionUnknown
;
388 for (ModuleSP module_sp
: target
.GetImages().Modules()) {
389 // One tricky bit here is that we might get called as part of the initial
390 // module loading, but before all the pre-run libraries get winnowed from
391 // the module list. So there might actually be an old and incorrect ObjC
392 // library sitting around in the list, and we don't want to look at that.
393 // That's why we call IsLoadedInTarget.
395 if (AppleIsModuleObjCLibrary(module_sp
) &&
396 module_sp
->IsLoadedInTarget(&target
)) {
397 objc_module_sp
= module_sp
;
398 ObjectFile
*ofile
= module_sp
->GetObjectFile();
400 return ObjCRuntimeVersions::eObjC_VersionUnknown
;
402 SectionList
*sections
= module_sp
->GetSectionList();
404 return ObjCRuntimeVersions::eObjC_VersionUnknown
;
405 SectionSP v1_telltale_section_sp
=
406 sections
->FindSectionByName(ConstString("__OBJC"));
407 if (v1_telltale_section_sp
) {
408 return ObjCRuntimeVersions::eAppleObjC_V1
;
410 return ObjCRuntimeVersions::eAppleObjC_V2
;
414 return ObjCRuntimeVersions::eObjC_VersionUnknown
;
417 void AppleObjCRuntime::SetExceptionBreakpoints() {
418 const bool catch_bp
= false;
419 const bool throw_bp
= true;
420 const bool is_internal
= true;
422 if (!m_objc_exception_bp_sp
) {
423 m_objc_exception_bp_sp
= LanguageRuntime::CreateExceptionBreakpoint(
424 m_process
->GetTarget(), GetLanguageType(), catch_bp
, throw_bp
,
426 if (m_objc_exception_bp_sp
)
427 m_objc_exception_bp_sp
->SetBreakpointKind("ObjC exception");
429 m_objc_exception_bp_sp
->SetEnabled(true);
432 void AppleObjCRuntime::ClearExceptionBreakpoints() {
436 if (m_objc_exception_bp_sp
.get()) {
437 m_objc_exception_bp_sp
->SetEnabled(false);
441 bool AppleObjCRuntime::ExceptionBreakpointsAreSet() {
442 return m_objc_exception_bp_sp
&& m_objc_exception_bp_sp
->IsEnabled();
445 bool AppleObjCRuntime::ExceptionBreakpointsExplainStop(
446 lldb::StopInfoSP stop_reason
) {
450 if (!stop_reason
|| stop_reason
->GetStopReason() != eStopReasonBreakpoint
)
453 uint64_t break_site_id
= stop_reason
->GetValue();
454 return m_process
->GetBreakpointSiteList().StopPointSiteContainsBreakpoint(
455 break_site_id
, m_objc_exception_bp_sp
->GetID());
458 bool AppleObjCRuntime::CalculateHasNewLiteralsAndIndexing() {
462 Target
&target(m_process
->GetTarget());
464 static ConstString
s_method_signature(
465 "-[NSDictionary objectForKeyedSubscript:]");
466 static ConstString
s_arclite_method_signature(
467 "__arclite_objectForKeyedSubscript");
469 SymbolContextList sc_list
;
471 target
.GetImages().FindSymbolsWithNameAndType(s_method_signature
,
472 eSymbolTypeCode
, sc_list
);
473 if (sc_list
.IsEmpty())
474 target
.GetImages().FindSymbolsWithNameAndType(s_arclite_method_signature
,
475 eSymbolTypeCode
, sc_list
);
476 return !sc_list
.IsEmpty();
479 lldb::SearchFilterSP
AppleObjCRuntime::CreateExceptionSearchFilter() {
480 Target
&target
= m_process
->GetTarget();
482 FileSpecList filter_modules
;
483 if (target
.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple
) {
484 filter_modules
.Append(std::get
<0>(GetExceptionThrowLocation()));
486 return target
.GetSearchFilterForModuleList(&filter_modules
);
489 ValueObjectSP
AppleObjCRuntime::GetExceptionObjectForThread(
490 ThreadSP thread_sp
) {
491 auto *cpp_runtime
= m_process
->GetLanguageRuntime(eLanguageTypeC_plus_plus
);
492 if (!cpp_runtime
) return ValueObjectSP();
493 auto cpp_exception
= cpp_runtime
->GetExceptionObjectForThread(thread_sp
);
494 if (!cpp_exception
) return ValueObjectSP();
496 auto descriptor
= GetClassDescriptor(*cpp_exception
);
497 if (!descriptor
|| !descriptor
->IsValid()) return ValueObjectSP();
500 ConstString
class_name(descriptor
->GetClassName());
501 if (class_name
== "NSException")
502 return cpp_exception
;
503 descriptor
= descriptor
->GetSuperclass();
506 return ValueObjectSP();
509 /// Utility method for error handling in GetBacktraceThreadFromException.
510 /// \param msg The message to add to the log.
511 /// \return An invalid ThreadSP to be returned from
512 /// GetBacktraceThreadFromException.
514 static ThreadSP
FailExceptionParsing(llvm::StringRef msg
) {
515 Log
*log
= GetLog(LLDBLog::Language
);
516 LLDB_LOG(log
, "Failed getting backtrace from exception: {0}", msg
);
520 ThreadSP
AppleObjCRuntime::GetBacktraceThreadFromException(
521 lldb::ValueObjectSP exception_sp
) {
522 ValueObjectSP reserved_dict
=
523 exception_sp
->GetChildMemberWithName("reserved");
525 return FailExceptionParsing("Failed to get 'reserved' member.");
527 reserved_dict
= reserved_dict
->GetSyntheticValue();
529 return FailExceptionParsing("Failed to get synthetic value.");
531 TypeSystemClangSP scratch_ts_sp
=
532 ScratchTypeSystemClang::GetForTarget(*exception_sp
->GetTargetSP());
534 return FailExceptionParsing("Failed to get scratch AST.");
535 CompilerType objc_id
= scratch_ts_sp
->GetBasicType(lldb::eBasicTypeObjCID
);
536 ValueObjectSP return_addresses
;
538 auto objc_object_from_address
= [&exception_sp
, &objc_id
](uint64_t addr
,
541 value
.SetCompilerType(objc_id
);
542 auto object
= ValueObjectConstResult::Create(
543 exception_sp
->GetTargetSP().get(), value
, ConstString(name
));
544 object
= object
->GetDynamicValue(eDynamicDontRunTarget
);
548 for (size_t idx
= 0; idx
< reserved_dict
->GetNumChildrenIgnoringErrors();
550 ValueObjectSP dict_entry
= reserved_dict
->GetChildAtIndex(idx
);
553 data
.SetAddressByteSize(dict_entry
->GetProcessSP()->GetAddressByteSize());
555 dict_entry
->GetData(data
, error
);
556 if (error
.Fail()) return ThreadSP();
558 lldb::offset_t data_offset
= 0;
559 auto dict_entry_key
= data
.GetAddress(&data_offset
);
560 auto dict_entry_value
= data
.GetAddress(&data_offset
);
562 auto key_nsstring
= objc_object_from_address(dict_entry_key
, "key");
563 StreamString key_summary
;
564 if (lldb_private::formatters::NSStringSummaryProvider(
565 *key_nsstring
, key_summary
, TypeSummaryOptions()) &&
566 !key_summary
.Empty()) {
567 if (key_summary
.GetString() == "\"callStackReturnAddresses\"") {
568 return_addresses
= objc_object_from_address(dict_entry_value
,
569 "callStackReturnAddresses");
575 if (!return_addresses
)
576 return FailExceptionParsing("Failed to get return addresses.");
577 auto frames_value
= return_addresses
->GetChildMemberWithName("_frames");
579 return FailExceptionParsing("Failed to get frames_value.");
580 addr_t frames_addr
= frames_value
->GetValueAsUnsigned(0);
581 auto count_value
= return_addresses
->GetChildMemberWithName("_cnt");
583 return FailExceptionParsing("Failed to get count_value.");
584 size_t count
= count_value
->GetValueAsUnsigned(0);
585 auto ignore_value
= return_addresses
->GetChildMemberWithName("_ignore");
587 return FailExceptionParsing("Failed to get ignore_value.");
588 size_t ignore
= ignore_value
->GetValueAsUnsigned(0);
590 size_t ptr_size
= m_process
->GetAddressByteSize();
591 std::vector
<lldb::addr_t
> pcs
;
592 for (size_t idx
= 0; idx
< count
; idx
++) {
594 addr_t pc
= m_process
->ReadPointerFromMemory(
595 frames_addr
+ (ignore
+ idx
) * ptr_size
, error
);
600 return FailExceptionParsing("Failed to get PC list.");
602 ThreadSP
new_thread_sp(new HistoryThread(*m_process
, 0, pcs
));
603 m_process
->GetExtendedThreadList().AddThread(new_thread_sp
);
604 return new_thread_sp
;
607 std::tuple
<FileSpec
, ConstString
>
608 AppleObjCRuntime::GetExceptionThrowLocation() {
609 return std::make_tuple(
610 FileSpec("libobjc.A.dylib"), ConstString("objc_exception_throw"));
613 void AppleObjCRuntime::ReadObjCLibraryIfNeeded(const ModuleList
&module_list
) {
614 if (!HasReadObjCLibrary()) {
615 std::lock_guard
<std::recursive_mutex
> guard(module_list
.GetMutex());
617 size_t num_modules
= module_list
.GetSize();
618 for (size_t i
= 0; i
< num_modules
; i
++) {
619 auto mod
= module_list
.GetModuleAtIndex(i
);
620 if (IsModuleObjCLibrary(mod
)) {
621 ReadObjCLibrary(mod
);
628 void AppleObjCRuntime::ModulesDidLoad(const ModuleList
&module_list
) {
629 ReadObjCLibraryIfNeeded(module_list
);