1 //===-- AppleObjCRuntime.cpp -------------------------------------*- C++
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8 //===----------------------------------------------------------------------===//
10 #include "AppleObjCRuntime.h"
11 #include "AppleObjCTrampolineHandler.h"
13 #include "clang/AST/Type.h"
15 #include "lldb/Breakpoint/BreakpointLocation.h"
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/ModuleList.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Core/Section.h"
20 #include "lldb/Core/ValueObject.h"
21 #include "lldb/Core/ValueObjectConstResult.h"
22 #include "lldb/DataFormatters/FormattersHelpers.h"
23 #include "lldb/Expression/DiagnosticManager.h"
24 #include "lldb/Expression/FunctionCaller.h"
25 #include "lldb/Symbol/ClangASTContext.h"
26 #include "lldb/Symbol/ObjectFile.h"
27 #include "lldb/Target/ExecutionContext.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Target/RegisterContext.h"
30 #include "lldb/Target/StopInfo.h"
31 #include "lldb/Target/Target.h"
32 #include "lldb/Target/Thread.h"
33 #include "lldb/Utility/ConstString.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"
39 #include "Plugins/Process/Utility/HistoryThread.h"
40 #include "Plugins/Language/ObjC/NSString.h"
41 #include "Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h"
46 using namespace lldb_private;
48 char AppleObjCRuntime::ID = 0;
50 AppleObjCRuntime::~AppleObjCRuntime() {}
52 AppleObjCRuntime::AppleObjCRuntime(Process *process)
53 : ObjCLanguageRuntime(process), m_read_objc_library(false),
54 m_objc_trampoline_handler_up(), m_Foundation_major() {
55 ReadObjCLibraryIfNeeded(process->GetTarget().GetImages());
58 bool AppleObjCRuntime::GetObjectDescription(Stream &str, ValueObject &valobj) {
59 CompilerType compiler_type(valobj.GetCompilerType());
61 // ObjC objects can only be pointers (or numbers that actually represents
62 // pointers but haven't been typecast, because reasons..)
63 if (!compiler_type.IsIntegerType(is_signed) && !compiler_type.IsPointerType())
66 // Make the argument list: we pass one arg, the address of our pointer, to
67 // the print function.
70 if (!valobj.ResolveValue(val.GetScalar()))
73 // Value Objects may not have a process in their ExecutionContextRef. But we
74 // need to have one in the ref we pass down to eventually call description.
75 // Get it from the target if it isn't present.
76 ExecutionContext exe_ctx;
77 if (valobj.GetProcessSP()) {
78 exe_ctx = ExecutionContext(valobj.GetExecutionContextRef());
80 exe_ctx.SetContext(valobj.GetTargetSP(), true);
81 if (!exe_ctx.HasProcessScope())
84 return GetObjectDescription(str, val, exe_ctx.GetBestExecutionContextScope());
86 bool AppleObjCRuntime::GetObjectDescription(Stream &strm, Value &value,
87 ExecutionContextScope *exe_scope) {
88 if (!m_read_objc_library)
91 ExecutionContext exe_ctx;
92 exe_scope->CalculateExecutionContext(exe_ctx);
93 Process *process = exe_ctx.GetProcessPtr();
97 // We need other parts of the exe_ctx, but the processes have to match.
98 assert(m_process == process);
100 // Get the function address for the print function.
101 const Address *function_address = GetPrintForDebuggerAddr();
102 if (!function_address)
105 Target *target = exe_ctx.GetTargetPtr();
106 CompilerType compiler_type = value.GetCompilerType();
108 if (!ClangASTContext::IsObjCObjectPointerType(compiler_type)) {
109 strm.Printf("Value doesn't point to an ObjC object.\n");
113 // If it is not a pointer, see if we can make it into a pointer.
114 ClangASTContext *ast_context = target->GetScratchClangASTContext();
115 CompilerType opaque_type = ast_context->GetBasicType(eBasicTypeObjCID);
117 opaque_type = ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
118 // value.SetContext(Value::eContextTypeClangType, opaque_type_ptr);
119 value.SetCompilerType(opaque_type);
122 ValueList arg_value_list;
123 arg_value_list.PushValue(value);
125 // This is the return value:
126 ClangASTContext *ast_context = target->GetScratchClangASTContext();
128 CompilerType return_compiler_type = ast_context->GetCStringType(true);
130 // ret.SetContext(Value::eContextTypeClangType, return_compiler_type);
131 ret.SetCompilerType(return_compiler_type);
133 if (exe_ctx.GetFramePtr() == nullptr) {
134 Thread *thread = exe_ctx.GetThreadPtr();
135 if (thread == nullptr) {
136 exe_ctx.SetThreadSP(process->GetThreadList().GetSelectedThread());
137 thread = exe_ctx.GetThreadPtr();
140 exe_ctx.SetFrameSP(thread->GetSelectedFrame());
144 // Now we're ready to call the function:
146 DiagnosticManager diagnostics;
147 lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS;
149 if (!m_print_object_caller_up) {
151 m_print_object_caller_up.reset(
152 exe_scope->CalculateTarget()->GetFunctionCallerForLanguage(
153 eLanguageTypeObjC, return_compiler_type, *function_address,
154 arg_value_list, "objc-object-description", error));
156 m_print_object_caller_up.reset();
157 strm.Printf("Could not get function runner to call print for debugger "
162 m_print_object_caller_up->InsertFunction(exe_ctx, wrapper_struct_addr,
165 m_print_object_caller_up->WriteFunctionArguments(
166 exe_ctx, wrapper_struct_addr, arg_value_list, diagnostics);
169 EvaluateExpressionOptions options;
170 options.SetUnwindOnError(true);
171 options.SetTryAllThreads(true);
172 options.SetStopOthers(true);
173 options.SetIgnoreBreakpoints(true);
174 options.SetTimeout(process->GetUtilityExpressionTimeout());
175 options.SetIsForUtilityExpr(true);
177 ExpressionResults results = m_print_object_caller_up->ExecuteFunction(
178 exe_ctx, &wrapper_struct_addr, options, diagnostics, ret);
179 if (results != eExpressionCompleted) {
180 strm.Printf("Error evaluating Print Object function: %d.\n", results);
184 addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
188 size_t full_buffer_len = sizeof(buf) - 1;
189 size_t curr_len = full_buffer_len;
190 while (curr_len == full_buffer_len) {
192 curr_len = process->ReadCStringFromMemory(result_ptr + cstr_len, buf,
194 strm.Write(buf, curr_len);
195 cstr_len += curr_len;
200 lldb::ModuleSP AppleObjCRuntime::GetObjCModule() {
201 ModuleSP module_sp(m_objc_module_wp.lock());
205 Process *process = GetProcess();
207 const ModuleList &modules = process->GetTarget().GetImages();
208 for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {
209 module_sp = modules.GetModuleAtIndex(idx);
210 if (AppleObjCRuntime::AppleIsModuleObjCLibrary(module_sp)) {
211 m_objc_module_wp = module_sp;
219 Address *AppleObjCRuntime::GetPrintForDebuggerAddr() {
220 if (!m_PrintForDebugger_addr) {
221 const ModuleList &modules = m_process->GetTarget().GetImages();
223 SymbolContextList contexts;
224 SymbolContext context;
226 if ((!modules.FindSymbolsWithNameAndType(ConstString("_NSPrintForDebugger"),
227 eSymbolTypeCode, contexts)) &&
228 (!modules.FindSymbolsWithNameAndType(ConstString("_CFPrintForDebugger"),
229 eSymbolTypeCode, contexts)))
232 contexts.GetContextAtIndex(0, context);
234 m_PrintForDebugger_addr.reset(new Address(context.symbol->GetAddress()));
237 return m_PrintForDebugger_addr.get();
240 bool AppleObjCRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
241 return in_value.GetCompilerType().IsPossibleDynamicType(
243 false, // do not check C++
247 bool AppleObjCRuntime::GetDynamicTypeAndAddress(
248 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
249 TypeAndOrName &class_type_or_name, Address &address,
250 Value::ValueType &value_type) {
255 AppleObjCRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
256 ValueObject &static_value) {
257 CompilerType static_type(static_value.GetCompilerType());
258 Flags static_type_flags(static_type.GetTypeInfo());
260 TypeAndOrName ret(type_and_or_name);
261 if (type_and_or_name.HasType()) {
262 // The type will always be the type of the dynamic object. If our parent's
263 // type was a pointer, then our type should be a pointer to the type of the
264 // dynamic object. If a reference, then the original type should be
266 CompilerType orig_type = type_and_or_name.GetCompilerType();
267 CompilerType corrected_type = orig_type;
268 if (static_type_flags.AllSet(eTypeIsPointer))
269 corrected_type = orig_type.GetPointerType();
270 ret.SetCompilerType(corrected_type);
272 // If we are here we need to adjust our dynamic type name to include the
273 // correct & or * symbol
274 std::string corrected_name(type_and_or_name.GetName().GetCString());
275 if (static_type_flags.AllSet(eTypeIsPointer))
276 corrected_name.append(" *");
277 // the parent type should be a correctly pointer'ed or referenc'ed type
278 ret.SetCompilerType(static_type);
279 ret.SetName(corrected_name.c_str());
284 bool AppleObjCRuntime::AppleIsModuleObjCLibrary(const ModuleSP &module_sp) {
286 const FileSpec &module_file_spec = module_sp->GetFileSpec();
287 static ConstString ObjCName("libobjc.A.dylib");
289 if (module_file_spec) {
290 if (module_file_spec.GetFilename() == ObjCName)
297 // we use the version of Foundation to make assumptions about the ObjC runtime
299 uint32_t AppleObjCRuntime::GetFoundationVersion() {
300 if (!m_Foundation_major.hasValue()) {
301 const ModuleList &modules = m_process->GetTarget().GetImages();
302 for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {
303 lldb::ModuleSP module_sp = modules.GetModuleAtIndex(idx);
306 if (strcmp(module_sp->GetFileSpec().GetFilename().AsCString(""),
307 "Foundation") == 0) {
308 m_Foundation_major = module_sp->GetVersion().getMajor();
309 return *m_Foundation_major;
312 return LLDB_INVALID_MODULE_VERSION;
314 return m_Foundation_major.getValue();
317 void AppleObjCRuntime::GetValuesForGlobalCFBooleans(lldb::addr_t &cf_true,
318 lldb::addr_t &cf_false) {
319 cf_true = cf_false = LLDB_INVALID_ADDRESS;
322 bool AppleObjCRuntime::IsModuleObjCLibrary(const ModuleSP &module_sp) {
323 return AppleIsModuleObjCLibrary(module_sp);
326 bool AppleObjCRuntime::ReadObjCLibrary(const ModuleSP &module_sp) {
327 // Maybe check here and if we have a handler already, and the UUID of this
328 // module is the same as the one in the current module, then we don't have to
330 m_objc_trampoline_handler_up.reset(
331 new AppleObjCTrampolineHandler(m_process->shared_from_this(), module_sp));
332 if (m_objc_trampoline_handler_up != nullptr) {
333 m_read_objc_library = true;
339 ThreadPlanSP AppleObjCRuntime::GetStepThroughTrampolinePlan(Thread &thread,
341 ThreadPlanSP thread_plan_sp;
342 if (m_objc_trampoline_handler_up)
343 thread_plan_sp = m_objc_trampoline_handler_up->GetStepThroughDispatchPlan(
344 thread, stop_others);
345 return thread_plan_sp;
349 ObjCLanguageRuntime::ObjCRuntimeVersions
350 AppleObjCRuntime::GetObjCVersion(Process *process, ModuleSP &objc_module_sp) {
352 return ObjCRuntimeVersions::eObjC_VersionUnknown;
354 Target &target = process->GetTarget();
355 if (target.GetArchitecture().GetTriple().getVendor() !=
356 llvm::Triple::VendorType::Apple)
357 return ObjCRuntimeVersions::eObjC_VersionUnknown;
359 const ModuleList &target_modules = target.GetImages();
360 std::lock_guard<std::recursive_mutex> gaurd(target_modules.GetMutex());
362 size_t num_images = target_modules.GetSize();
363 for (size_t i = 0; i < num_images; i++) {
364 ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i);
365 // One tricky bit here is that we might get called as part of the initial
366 // module loading, but before all the pre-run libraries get winnowed from
367 // the module list. So there might actually be an old and incorrect ObjC
368 // library sitting around in the list, and we don't want to look at that.
369 // That's why we call IsLoadedInTarget.
371 if (AppleIsModuleObjCLibrary(module_sp) &&
372 module_sp->IsLoadedInTarget(&target)) {
373 objc_module_sp = module_sp;
374 ObjectFile *ofile = module_sp->GetObjectFile();
376 return ObjCRuntimeVersions::eObjC_VersionUnknown;
378 SectionList *sections = module_sp->GetSectionList();
380 return ObjCRuntimeVersions::eObjC_VersionUnknown;
381 SectionSP v1_telltale_section_sp =
382 sections->FindSectionByName(ConstString("__OBJC"));
383 if (v1_telltale_section_sp) {
384 return ObjCRuntimeVersions::eAppleObjC_V1;
386 return ObjCRuntimeVersions::eAppleObjC_V2;
390 return ObjCRuntimeVersions::eObjC_VersionUnknown;
393 void AppleObjCRuntime::SetExceptionBreakpoints() {
394 const bool catch_bp = false;
395 const bool throw_bp = true;
396 const bool is_internal = true;
398 if (!m_objc_exception_bp_sp) {
399 m_objc_exception_bp_sp = LanguageRuntime::CreateExceptionBreakpoint(
400 m_process->GetTarget(), GetLanguageType(), catch_bp, throw_bp,
402 if (m_objc_exception_bp_sp)
403 m_objc_exception_bp_sp->SetBreakpointKind("ObjC exception");
405 m_objc_exception_bp_sp->SetEnabled(true);
408 void AppleObjCRuntime::ClearExceptionBreakpoints() {
412 if (m_objc_exception_bp_sp.get()) {
413 m_objc_exception_bp_sp->SetEnabled(false);
417 bool AppleObjCRuntime::ExceptionBreakpointsAreSet() {
418 return m_objc_exception_bp_sp && m_objc_exception_bp_sp->IsEnabled();
421 bool AppleObjCRuntime::ExceptionBreakpointsExplainStop(
422 lldb::StopInfoSP stop_reason) {
426 if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint)
429 uint64_t break_site_id = stop_reason->GetValue();
430 return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint(
431 break_site_id, m_objc_exception_bp_sp->GetID());
434 bool AppleObjCRuntime::CalculateHasNewLiteralsAndIndexing() {
438 Target &target(m_process->GetTarget());
440 static ConstString s_method_signature(
441 "-[NSDictionary objectForKeyedSubscript:]");
442 static ConstString s_arclite_method_signature(
443 "__arclite_objectForKeyedSubscript");
445 SymbolContextList sc_list;
447 return target.GetImages().FindSymbolsWithNameAndType(
448 s_method_signature, eSymbolTypeCode, sc_list) ||
449 target.GetImages().FindSymbolsWithNameAndType(
450 s_arclite_method_signature, eSymbolTypeCode, sc_list);
453 lldb::SearchFilterSP AppleObjCRuntime::CreateExceptionSearchFilter() {
454 Target &target = m_process->GetTarget();
456 FileSpecList filter_modules;
457 if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) {
458 filter_modules.Append(std::get<0>(GetExceptionThrowLocation()));
460 return target.GetSearchFilterForModuleList(&filter_modules);
463 ValueObjectSP AppleObjCRuntime::GetExceptionObjectForThread(
464 ThreadSP thread_sp) {
465 auto *cpp_runtime = m_process->GetLanguageRuntime(eLanguageTypeC_plus_plus);
466 if (!cpp_runtime) return ValueObjectSP();
467 auto cpp_exception = cpp_runtime->GetExceptionObjectForThread(thread_sp);
468 if (!cpp_exception) return ValueObjectSP();
470 auto descriptor = GetClassDescriptor(*cpp_exception);
471 if (!descriptor || !descriptor->IsValid()) return ValueObjectSP();
474 ConstString class_name(descriptor->GetClassName());
475 if (class_name == "NSException")
476 return cpp_exception;
477 descriptor = descriptor->GetSuperclass();
480 return ValueObjectSP();
483 ThreadSP AppleObjCRuntime::GetBacktraceThreadFromException(
484 lldb::ValueObjectSP exception_sp) {
485 ValueObjectSP reserved_dict =
486 exception_sp->GetChildMemberWithName(ConstString("reserved"), true);
487 if (!reserved_dict) return ThreadSP();
489 reserved_dict = reserved_dict->GetSyntheticValue();
490 if (!reserved_dict) return ThreadSP();
492 CompilerType objc_id =
493 exception_sp->GetTargetSP()->GetScratchClangASTContext()->GetBasicType(
494 lldb::eBasicTypeObjCID);
495 ValueObjectSP return_addresses;
497 auto objc_object_from_address = [&exception_sp, &objc_id](uint64_t addr,
500 value.SetCompilerType(objc_id);
501 auto object = ValueObjectConstResult::Create(
502 exception_sp->GetTargetSP().get(), value, ConstString(name));
503 object = object->GetDynamicValue(eDynamicDontRunTarget);
507 for (size_t idx = 0; idx < reserved_dict->GetNumChildren(); idx++) {
508 ValueObjectSP dict_entry = reserved_dict->GetChildAtIndex(idx, true);
511 data.SetAddressByteSize(dict_entry->GetProcessSP()->GetAddressByteSize());
513 dict_entry->GetData(data, error);
514 if (error.Fail()) return ThreadSP();
516 lldb::offset_t data_offset = 0;
517 auto dict_entry_key = data.GetPointer(&data_offset);
518 auto dict_entry_value = data.GetPointer(&data_offset);
520 auto key_nsstring = objc_object_from_address(dict_entry_key, "key");
521 StreamString key_summary;
522 if (lldb_private::formatters::NSStringSummaryProvider(
523 *key_nsstring, key_summary, TypeSummaryOptions()) &&
524 !key_summary.Empty()) {
525 if (key_summary.GetString() == "\"callStackReturnAddresses\"") {
526 return_addresses = objc_object_from_address(dict_entry_value,
527 "callStackReturnAddresses");
533 if (!return_addresses) return ThreadSP();
535 return_addresses->GetChildMemberWithName(ConstString("_frames"), true);
536 addr_t frames_addr = frames_value->GetValueAsUnsigned(0);
538 return_addresses->GetChildMemberWithName(ConstString("_cnt"), true);
539 size_t count = count_value->GetValueAsUnsigned(0);
541 return_addresses->GetChildMemberWithName(ConstString("_ignore"), true);
542 size_t ignore = ignore_value->GetValueAsUnsigned(0);
544 size_t ptr_size = m_process->GetAddressByteSize();
545 std::vector<lldb::addr_t> pcs;
546 for (size_t idx = 0; idx < count; idx++) {
548 addr_t pc = m_process->ReadPointerFromMemory(
549 frames_addr + (ignore + idx) * ptr_size, error);
553 if (pcs.empty()) return ThreadSP();
555 ThreadSP new_thread_sp(new HistoryThread(*m_process, 0, pcs));
556 m_process->GetExtendedThreadList().AddThread(new_thread_sp);
557 return new_thread_sp;
560 std::tuple<FileSpec, ConstString>
561 AppleObjCRuntime::GetExceptionThrowLocation() {
562 return std::make_tuple(
563 FileSpec("libobjc.A.dylib"), ConstString("objc_exception_throw"));
566 void AppleObjCRuntime::ReadObjCLibraryIfNeeded(const ModuleList &module_list) {
567 if (!HasReadObjCLibrary()) {
568 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
570 size_t num_modules = module_list.GetSize();
571 for (size_t i = 0; i < num_modules; i++) {
572 auto mod = module_list.GetModuleAtIndex(i);
573 if (IsModuleObjCLibrary(mod)) {
574 ReadObjCLibrary(mod);
581 void AppleObjCRuntime::ModulesDidLoad(const ModuleList &module_list) {
582 ReadObjCLibraryIfNeeded(module_list);