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 modules.FindSymbolsWithNameAndType(ConstString("_NSPrintForDebugger"),
227 eSymbolTypeCode, contexts);
228 if (contexts.IsEmpty()) {
229 modules.FindSymbolsWithNameAndType(ConstString("_CFPrintForDebugger"),
230 eSymbolTypeCode, contexts);
231 if (contexts.IsEmpty())
235 contexts.GetContextAtIndex(0, context);
237 m_PrintForDebugger_addr.reset(new Address(context.symbol->GetAddress()));
240 return m_PrintForDebugger_addr.get();
243 bool AppleObjCRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
244 return in_value.GetCompilerType().IsPossibleDynamicType(
246 false, // do not check C++
250 bool AppleObjCRuntime::GetDynamicTypeAndAddress(
251 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
252 TypeAndOrName &class_type_or_name, Address &address,
253 Value::ValueType &value_type) {
258 AppleObjCRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
259 ValueObject &static_value) {
260 CompilerType static_type(static_value.GetCompilerType());
261 Flags static_type_flags(static_type.GetTypeInfo());
263 TypeAndOrName ret(type_and_or_name);
264 if (type_and_or_name.HasType()) {
265 // The type will always be the type of the dynamic object. If our parent's
266 // type was a pointer, then our type should be a pointer to the type of the
267 // dynamic object. If a reference, then the original type should be
269 CompilerType orig_type = type_and_or_name.GetCompilerType();
270 CompilerType corrected_type = orig_type;
271 if (static_type_flags.AllSet(eTypeIsPointer))
272 corrected_type = orig_type.GetPointerType();
273 ret.SetCompilerType(corrected_type);
275 // If we are here we need to adjust our dynamic type name to include the
276 // correct & or * symbol
277 std::string corrected_name(type_and_or_name.GetName().GetCString());
278 if (static_type_flags.AllSet(eTypeIsPointer))
279 corrected_name.append(" *");
280 // the parent type should be a correctly pointer'ed or referenc'ed type
281 ret.SetCompilerType(static_type);
282 ret.SetName(corrected_name.c_str());
287 bool AppleObjCRuntime::AppleIsModuleObjCLibrary(const ModuleSP &module_sp) {
289 const FileSpec &module_file_spec = module_sp->GetFileSpec();
290 static ConstString ObjCName("libobjc.A.dylib");
292 if (module_file_spec) {
293 if (module_file_spec.GetFilename() == ObjCName)
300 // we use the version of Foundation to make assumptions about the ObjC runtime
302 uint32_t AppleObjCRuntime::GetFoundationVersion() {
303 if (!m_Foundation_major.hasValue()) {
304 const ModuleList &modules = m_process->GetTarget().GetImages();
305 for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {
306 lldb::ModuleSP module_sp = modules.GetModuleAtIndex(idx);
309 if (strcmp(module_sp->GetFileSpec().GetFilename().AsCString(""),
310 "Foundation") == 0) {
311 m_Foundation_major = module_sp->GetVersion().getMajor();
312 return *m_Foundation_major;
315 return LLDB_INVALID_MODULE_VERSION;
317 return m_Foundation_major.getValue();
320 void AppleObjCRuntime::GetValuesForGlobalCFBooleans(lldb::addr_t &cf_true,
321 lldb::addr_t &cf_false) {
322 cf_true = cf_false = LLDB_INVALID_ADDRESS;
325 bool AppleObjCRuntime::IsModuleObjCLibrary(const ModuleSP &module_sp) {
326 return AppleIsModuleObjCLibrary(module_sp);
329 bool AppleObjCRuntime::ReadObjCLibrary(const ModuleSP &module_sp) {
330 // Maybe check here and if we have a handler already, and the UUID of this
331 // module is the same as the one in the current module, then we don't have to
333 m_objc_trampoline_handler_up.reset(
334 new AppleObjCTrampolineHandler(m_process->shared_from_this(), module_sp));
335 if (m_objc_trampoline_handler_up != nullptr) {
336 m_read_objc_library = true;
342 ThreadPlanSP AppleObjCRuntime::GetStepThroughTrampolinePlan(Thread &thread,
344 ThreadPlanSP thread_plan_sp;
345 if (m_objc_trampoline_handler_up)
346 thread_plan_sp = m_objc_trampoline_handler_up->GetStepThroughDispatchPlan(
347 thread, stop_others);
348 return thread_plan_sp;
352 ObjCLanguageRuntime::ObjCRuntimeVersions
353 AppleObjCRuntime::GetObjCVersion(Process *process, ModuleSP &objc_module_sp) {
355 return ObjCRuntimeVersions::eObjC_VersionUnknown;
357 Target &target = process->GetTarget();
358 if (target.GetArchitecture().GetTriple().getVendor() !=
359 llvm::Triple::VendorType::Apple)
360 return ObjCRuntimeVersions::eObjC_VersionUnknown;
362 const ModuleList &target_modules = target.GetImages();
363 std::lock_guard<std::recursive_mutex> gaurd(target_modules.GetMutex());
365 size_t num_images = target_modules.GetSize();
366 for (size_t i = 0; i < num_images; i++) {
367 ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i);
368 // One tricky bit here is that we might get called as part of the initial
369 // module loading, but before all the pre-run libraries get winnowed from
370 // the module list. So there might actually be an old and incorrect ObjC
371 // library sitting around in the list, and we don't want to look at that.
372 // That's why we call IsLoadedInTarget.
374 if (AppleIsModuleObjCLibrary(module_sp) &&
375 module_sp->IsLoadedInTarget(&target)) {
376 objc_module_sp = module_sp;
377 ObjectFile *ofile = module_sp->GetObjectFile();
379 return ObjCRuntimeVersions::eObjC_VersionUnknown;
381 SectionList *sections = module_sp->GetSectionList();
383 return ObjCRuntimeVersions::eObjC_VersionUnknown;
384 SectionSP v1_telltale_section_sp =
385 sections->FindSectionByName(ConstString("__OBJC"));
386 if (v1_telltale_section_sp) {
387 return ObjCRuntimeVersions::eAppleObjC_V1;
389 return ObjCRuntimeVersions::eAppleObjC_V2;
393 return ObjCRuntimeVersions::eObjC_VersionUnknown;
396 void AppleObjCRuntime::SetExceptionBreakpoints() {
397 const bool catch_bp = false;
398 const bool throw_bp = true;
399 const bool is_internal = true;
401 if (!m_objc_exception_bp_sp) {
402 m_objc_exception_bp_sp = LanguageRuntime::CreateExceptionBreakpoint(
403 m_process->GetTarget(), GetLanguageType(), catch_bp, throw_bp,
405 if (m_objc_exception_bp_sp)
406 m_objc_exception_bp_sp->SetBreakpointKind("ObjC exception");
408 m_objc_exception_bp_sp->SetEnabled(true);
411 void AppleObjCRuntime::ClearExceptionBreakpoints() {
415 if (m_objc_exception_bp_sp.get()) {
416 m_objc_exception_bp_sp->SetEnabled(false);
420 bool AppleObjCRuntime::ExceptionBreakpointsAreSet() {
421 return m_objc_exception_bp_sp && m_objc_exception_bp_sp->IsEnabled();
424 bool AppleObjCRuntime::ExceptionBreakpointsExplainStop(
425 lldb::StopInfoSP stop_reason) {
429 if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint)
432 uint64_t break_site_id = stop_reason->GetValue();
433 return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint(
434 break_site_id, m_objc_exception_bp_sp->GetID());
437 bool AppleObjCRuntime::CalculateHasNewLiteralsAndIndexing() {
441 Target &target(m_process->GetTarget());
443 static ConstString s_method_signature(
444 "-[NSDictionary objectForKeyedSubscript:]");
445 static ConstString s_arclite_method_signature(
446 "__arclite_objectForKeyedSubscript");
448 SymbolContextList sc_list;
450 target.GetImages().FindSymbolsWithNameAndType(s_method_signature,
451 eSymbolTypeCode, sc_list);
452 if (sc_list.IsEmpty())
453 target.GetImages().FindSymbolsWithNameAndType(s_arclite_method_signature,
454 eSymbolTypeCode, sc_list);
455 return !sc_list.IsEmpty();
458 lldb::SearchFilterSP AppleObjCRuntime::CreateExceptionSearchFilter() {
459 Target &target = m_process->GetTarget();
461 FileSpecList filter_modules;
462 if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) {
463 filter_modules.Append(std::get<0>(GetExceptionThrowLocation()));
465 return target.GetSearchFilterForModuleList(&filter_modules);
468 ValueObjectSP AppleObjCRuntime::GetExceptionObjectForThread(
469 ThreadSP thread_sp) {
470 auto *cpp_runtime = m_process->GetLanguageRuntime(eLanguageTypeC_plus_plus);
471 if (!cpp_runtime) return ValueObjectSP();
472 auto cpp_exception = cpp_runtime->GetExceptionObjectForThread(thread_sp);
473 if (!cpp_exception) return ValueObjectSP();
475 auto descriptor = GetClassDescriptor(*cpp_exception);
476 if (!descriptor || !descriptor->IsValid()) return ValueObjectSP();
479 ConstString class_name(descriptor->GetClassName());
480 if (class_name == "NSException")
481 return cpp_exception;
482 descriptor = descriptor->GetSuperclass();
485 return ValueObjectSP();
488 ThreadSP AppleObjCRuntime::GetBacktraceThreadFromException(
489 lldb::ValueObjectSP exception_sp) {
490 ValueObjectSP reserved_dict =
491 exception_sp->GetChildMemberWithName(ConstString("reserved"), true);
492 if (!reserved_dict) return ThreadSP();
494 reserved_dict = reserved_dict->GetSyntheticValue();
495 if (!reserved_dict) return ThreadSP();
497 CompilerType objc_id =
498 exception_sp->GetTargetSP()->GetScratchClangASTContext()->GetBasicType(
499 lldb::eBasicTypeObjCID);
500 ValueObjectSP return_addresses;
502 auto objc_object_from_address = [&exception_sp, &objc_id](uint64_t addr,
505 value.SetCompilerType(objc_id);
506 auto object = ValueObjectConstResult::Create(
507 exception_sp->GetTargetSP().get(), value, ConstString(name));
508 object = object->GetDynamicValue(eDynamicDontRunTarget);
512 for (size_t idx = 0; idx < reserved_dict->GetNumChildren(); idx++) {
513 ValueObjectSP dict_entry = reserved_dict->GetChildAtIndex(idx, true);
516 data.SetAddressByteSize(dict_entry->GetProcessSP()->GetAddressByteSize());
518 dict_entry->GetData(data, error);
519 if (error.Fail()) return ThreadSP();
521 lldb::offset_t data_offset = 0;
522 auto dict_entry_key = data.GetPointer(&data_offset);
523 auto dict_entry_value = data.GetPointer(&data_offset);
525 auto key_nsstring = objc_object_from_address(dict_entry_key, "key");
526 StreamString key_summary;
527 if (lldb_private::formatters::NSStringSummaryProvider(
528 *key_nsstring, key_summary, TypeSummaryOptions()) &&
529 !key_summary.Empty()) {
530 if (key_summary.GetString() == "\"callStackReturnAddresses\"") {
531 return_addresses = objc_object_from_address(dict_entry_value,
532 "callStackReturnAddresses");
538 if (!return_addresses) return ThreadSP();
540 return_addresses->GetChildMemberWithName(ConstString("_frames"), true);
541 addr_t frames_addr = frames_value->GetValueAsUnsigned(0);
543 return_addresses->GetChildMemberWithName(ConstString("_cnt"), true);
544 size_t count = count_value->GetValueAsUnsigned(0);
546 return_addresses->GetChildMemberWithName(ConstString("_ignore"), true);
547 size_t ignore = ignore_value->GetValueAsUnsigned(0);
549 size_t ptr_size = m_process->GetAddressByteSize();
550 std::vector<lldb::addr_t> pcs;
551 for (size_t idx = 0; idx < count; idx++) {
553 addr_t pc = m_process->ReadPointerFromMemory(
554 frames_addr + (ignore + idx) * ptr_size, error);
558 if (pcs.empty()) return ThreadSP();
560 ThreadSP new_thread_sp(new HistoryThread(*m_process, 0, pcs));
561 m_process->GetExtendedThreadList().AddThread(new_thread_sp);
562 return new_thread_sp;
565 std::tuple<FileSpec, ConstString>
566 AppleObjCRuntime::GetExceptionThrowLocation() {
567 return std::make_tuple(
568 FileSpec("libobjc.A.dylib"), ConstString("objc_exception_throw"));
571 void AppleObjCRuntime::ReadObjCLibraryIfNeeded(const ModuleList &module_list) {
572 if (!HasReadObjCLibrary()) {
573 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
575 size_t num_modules = module_list.GetSize();
576 for (size_t i = 0; i < num_modules; i++) {
577 auto mod = module_list.GetModuleAtIndex(i);
578 if (IsModuleObjCLibrary(mod)) {
579 ReadObjCLibrary(mod);
586 void AppleObjCRuntime::ModulesDidLoad(const ModuleList &module_list) {
587 ReadObjCLibraryIfNeeded(module_list);