1 //===-- AppleObjCRuntime.cpp -------------------------------------*- C++
4 // The LLVM Compiler Infrastructure
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
9 //===----------------------------------------------------------------------===//
11 #include "AppleObjCRuntime.h"
12 #include "AppleObjCTrampolineHandler.h"
14 #include "clang/AST/Type.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/Core/ValueObject.h"
22 #include "lldb/Core/ValueObjectConstResult.h"
23 #include "lldb/DataFormatters/FormattersHelpers.h"
24 #include "lldb/Expression/DiagnosticManager.h"
25 #include "lldb/Expression/FunctionCaller.h"
26 #include "lldb/Symbol/ClangASTContext.h"
27 #include "lldb/Symbol/ObjectFile.h"
28 #include "lldb/Target/CPPLanguageRuntime.h"
29 #include "lldb/Target/ExecutionContext.h"
30 #include "lldb/Target/Process.h"
31 #include "lldb/Target/RegisterContext.h"
32 #include "lldb/Target/StopInfo.h"
33 #include "lldb/Target/Target.h"
34 #include "lldb/Target/Thread.h"
35 #include "lldb/Utility/ConstString.h"
36 #include "lldb/Utility/Log.h"
37 #include "lldb/Utility/Scalar.h"
38 #include "lldb/Utility/Status.h"
39 #include "lldb/Utility/StreamString.h"
41 #include "Plugins/Process/Utility/HistoryThread.h"
42 #include "Plugins/Language/ObjC/NSString.h"
47 using namespace lldb_private;
49 static constexpr std::chrono::seconds g_po_function_timeout(15);
51 AppleObjCRuntime::~AppleObjCRuntime() {}
53 AppleObjCRuntime::AppleObjCRuntime(Process *process)
54 : ObjCLanguageRuntime(process), m_read_objc_library(false),
55 m_objc_trampoline_handler_ap(), m_Foundation_major() {
56 ReadObjCLibraryIfNeeded(process->GetTarget().GetImages());
59 bool AppleObjCRuntime::GetObjectDescription(Stream &str, ValueObject &valobj) {
60 CompilerType compiler_type(valobj.GetCompilerType());
62 // ObjC objects can only be pointers (or numbers that actually represents
63 // pointers but haven't been typecast, because reasons..)
64 if (!compiler_type.IsIntegerType(is_signed) && !compiler_type.IsPointerType())
67 // Make the argument list: we pass one arg, the address of our pointer, to
68 // the print function.
71 if (!valobj.ResolveValue(val.GetScalar()))
74 // Value Objects may not have a process in their ExecutionContextRef. But we
75 // need to have one in the ref we pass down to eventually call description.
76 // Get it from the target if it isn't present.
77 ExecutionContext exe_ctx;
78 if (valobj.GetProcessSP()) {
79 exe_ctx = ExecutionContext(valobj.GetExecutionContextRef());
81 exe_ctx.SetContext(valobj.GetTargetSP(), true);
82 if (!exe_ctx.HasProcessScope())
85 return GetObjectDescription(str, val, exe_ctx.GetBestExecutionContextScope());
87 bool AppleObjCRuntime::GetObjectDescription(Stream &strm, Value &value,
88 ExecutionContextScope *exe_scope) {
89 if (!m_read_objc_library)
92 ExecutionContext exe_ctx;
93 exe_scope->CalculateExecutionContext(exe_ctx);
94 Process *process = exe_ctx.GetProcessPtr();
98 // We need other parts of the exe_ctx, but the processes have to match.
99 assert(m_process == process);
101 // Get the function address for the print function.
102 const Address *function_address = GetPrintForDebuggerAddr();
103 if (!function_address)
106 Target *target = exe_ctx.GetTargetPtr();
107 CompilerType compiler_type = value.GetCompilerType();
109 if (!ClangASTContext::IsObjCObjectPointerType(compiler_type)) {
110 strm.Printf("Value doesn't point to an ObjC object.\n");
114 // If it is not a pointer, see if we can make it into a pointer.
115 ClangASTContext *ast_context = target->GetScratchClangASTContext();
116 CompilerType opaque_type = ast_context->GetBasicType(eBasicTypeObjCID);
118 opaque_type = ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
119 // value.SetContext(Value::eContextTypeClangType, opaque_type_ptr);
120 value.SetCompilerType(opaque_type);
123 ValueList arg_value_list;
124 arg_value_list.PushValue(value);
126 // This is the return value:
127 ClangASTContext *ast_context = target->GetScratchClangASTContext();
129 CompilerType return_compiler_type = ast_context->GetCStringType(true);
131 // ret.SetContext(Value::eContextTypeClangType, return_compiler_type);
132 ret.SetCompilerType(return_compiler_type);
134 if (exe_ctx.GetFramePtr() == NULL) {
135 Thread *thread = exe_ctx.GetThreadPtr();
136 if (thread == NULL) {
137 exe_ctx.SetThreadSP(process->GetThreadList().GetSelectedThread());
138 thread = exe_ctx.GetThreadPtr();
141 exe_ctx.SetFrameSP(thread->GetSelectedFrame());
145 // Now we're ready to call the function:
147 DiagnosticManager diagnostics;
148 lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS;
150 if (!m_print_object_caller_up) {
152 m_print_object_caller_up.reset(
153 exe_scope->CalculateTarget()->GetFunctionCallerForLanguage(
154 eLanguageTypeObjC, return_compiler_type, *function_address,
155 arg_value_list, "objc-object-description", error));
157 m_print_object_caller_up.reset();
158 strm.Printf("Could not get function runner to call print for debugger "
163 m_print_object_caller_up->InsertFunction(exe_ctx, wrapper_struct_addr,
166 m_print_object_caller_up->WriteFunctionArguments(
167 exe_ctx, wrapper_struct_addr, arg_value_list, diagnostics);
170 EvaluateExpressionOptions options;
171 options.SetUnwindOnError(true);
172 options.SetTryAllThreads(true);
173 options.SetStopOthers(true);
174 options.SetIgnoreBreakpoints(true);
175 options.SetTimeout(g_po_function_timeout);
176 options.SetIsForUtilityExpr(true);
178 ExpressionResults results = m_print_object_caller_up->ExecuteFunction(
179 exe_ctx, &wrapper_struct_addr, options, diagnostics, ret);
180 if (results != eExpressionCompleted) {
181 strm.Printf("Error evaluating Print Object function: %d.\n", results);
185 addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
189 size_t full_buffer_len = sizeof(buf) - 1;
190 size_t curr_len = full_buffer_len;
191 while (curr_len == full_buffer_len) {
193 curr_len = process->ReadCStringFromMemory(result_ptr + cstr_len, buf,
195 strm.Write(buf, curr_len);
196 cstr_len += curr_len;
201 lldb::ModuleSP AppleObjCRuntime::GetObjCModule() {
202 ModuleSP module_sp(m_objc_module_wp.lock());
206 Process *process = GetProcess();
208 const ModuleList &modules = process->GetTarget().GetImages();
209 for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {
210 module_sp = modules.GetModuleAtIndex(idx);
211 if (AppleObjCRuntime::AppleIsModuleObjCLibrary(module_sp)) {
212 m_objc_module_wp = module_sp;
220 Address *AppleObjCRuntime::GetPrintForDebuggerAddr() {
221 if (!m_PrintForDebugger_addr.get()) {
222 const ModuleList &modules = m_process->GetTarget().GetImages();
224 SymbolContextList contexts;
225 SymbolContext context;
227 if ((!modules.FindSymbolsWithNameAndType(ConstString("_NSPrintForDebugger"),
228 eSymbolTypeCode, contexts)) &&
229 (!modules.FindSymbolsWithNameAndType(ConstString("_CFPrintForDebugger"),
230 eSymbolTypeCode, contexts)))
233 contexts.GetContextAtIndex(0, context);
235 m_PrintForDebugger_addr.reset(new Address(context.symbol->GetAddress()));
238 return m_PrintForDebugger_addr.get();
241 bool AppleObjCRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
242 return in_value.GetCompilerType().IsPossibleDynamicType(
244 false, // do not check C++
248 bool AppleObjCRuntime::GetDynamicTypeAndAddress(
249 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
250 TypeAndOrName &class_type_or_name, Address &address,
251 Value::ValueType &value_type) {
256 AppleObjCRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
257 ValueObject &static_value) {
258 CompilerType static_type(static_value.GetCompilerType());
259 Flags static_type_flags(static_type.GetTypeInfo());
261 TypeAndOrName ret(type_and_or_name);
262 if (type_and_or_name.HasType()) {
263 // The type will always be the type of the dynamic object. If our parent's
264 // type was a pointer, then our type should be a pointer to the type of the
265 // dynamic object. If a reference, then the original type should be
267 CompilerType orig_type = type_and_or_name.GetCompilerType();
268 CompilerType corrected_type = orig_type;
269 if (static_type_flags.AllSet(eTypeIsPointer))
270 corrected_type = orig_type.GetPointerType();
271 ret.SetCompilerType(corrected_type);
273 // If we are here we need to adjust our dynamic type name to include the
274 // correct & or * symbol
275 std::string corrected_name(type_and_or_name.GetName().GetCString());
276 if (static_type_flags.AllSet(eTypeIsPointer))
277 corrected_name.append(" *");
278 // the parent type should be a correctly pointer'ed or referenc'ed type
279 ret.SetCompilerType(static_type);
280 ret.SetName(corrected_name.c_str());
285 bool AppleObjCRuntime::AppleIsModuleObjCLibrary(const ModuleSP &module_sp) {
287 const FileSpec &module_file_spec = module_sp->GetFileSpec();
288 static ConstString ObjCName("libobjc.A.dylib");
290 if (module_file_spec) {
291 if (module_file_spec.GetFilename() == ObjCName)
298 // we use the version of Foundation to make assumptions about the ObjC runtime
300 uint32_t AppleObjCRuntime::GetFoundationVersion() {
301 if (!m_Foundation_major.hasValue()) {
302 const ModuleList &modules = m_process->GetTarget().GetImages();
303 for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {
304 lldb::ModuleSP module_sp = modules.GetModuleAtIndex(idx);
307 if (strcmp(module_sp->GetFileSpec().GetFilename().AsCString(""),
308 "Foundation") == 0) {
309 m_Foundation_major = module_sp->GetVersion().getMajor();
310 return *m_Foundation_major;
313 return LLDB_INVALID_MODULE_VERSION;
315 return m_Foundation_major.getValue();
318 void AppleObjCRuntime::GetValuesForGlobalCFBooleans(lldb::addr_t &cf_true,
319 lldb::addr_t &cf_false) {
320 cf_true = cf_false = LLDB_INVALID_ADDRESS;
323 bool AppleObjCRuntime::IsModuleObjCLibrary(const ModuleSP &module_sp) {
324 return AppleIsModuleObjCLibrary(module_sp);
327 bool AppleObjCRuntime::ReadObjCLibrary(const ModuleSP &module_sp) {
328 // Maybe check here and if we have a handler already, and the UUID of this
329 // module is the same as the one in the current module, then we don't have to
331 m_objc_trampoline_handler_ap.reset(
332 new AppleObjCTrampolineHandler(m_process->shared_from_this(), module_sp));
333 if (m_objc_trampoline_handler_ap.get() != NULL) {
334 m_read_objc_library = true;
340 ThreadPlanSP AppleObjCRuntime::GetStepThroughTrampolinePlan(Thread &thread,
342 ThreadPlanSP thread_plan_sp;
343 if (m_objc_trampoline_handler_ap.get())
344 thread_plan_sp = m_objc_trampoline_handler_ap->GetStepThroughDispatchPlan(
345 thread, stop_others);
346 return thread_plan_sp;
349 //------------------------------------------------------------------
351 //------------------------------------------------------------------
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 return target.GetImages().FindSymbolsWithNameAndType(
451 s_method_signature, eSymbolTypeCode, sc_list) ||
452 target.GetImages().FindSymbolsWithNameAndType(
453 s_arclite_method_signature, eSymbolTypeCode, sc_list);
456 lldb::SearchFilterSP AppleObjCRuntime::CreateExceptionSearchFilter() {
457 Target &target = m_process->GetTarget();
459 if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) {
460 FileSpecList filter_modules;
461 filter_modules.Append(std::get<0>(GetExceptionThrowLocation()));
462 return target.GetSearchFilterForModuleList(&filter_modules);
464 return LanguageRuntime::CreateExceptionSearchFilter();
468 ValueObjectSP AppleObjCRuntime::GetExceptionObjectForThread(
469 ThreadSP thread_sp) {
470 auto cpp_runtime = m_process->GetCPPLanguageRuntime();
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.get());
476 if (!descriptor || !descriptor->IsValid()) return ValueObjectSP();
479 ConstString class_name(descriptor->GetClassName());
480 if (class_name == ConstString("NSException")) return cpp_exception;
481 descriptor = descriptor->GetSuperclass();
484 return ValueObjectSP();
487 ThreadSP AppleObjCRuntime::GetBacktraceThreadFromException(
488 lldb::ValueObjectSP exception_sp) {
489 ValueObjectSP reserved_dict =
490 exception_sp->GetChildMemberWithName(ConstString("reserved"), true);
491 if (!reserved_dict) return ThreadSP();
493 reserved_dict = reserved_dict->GetSyntheticValue();
494 if (!reserved_dict) return ThreadSP();
496 CompilerType objc_id =
497 exception_sp->GetTargetSP()->GetScratchClangASTContext()->GetBasicType(
498 lldb::eBasicTypeObjCID);
499 ValueObjectSP return_addresses;
501 auto objc_object_from_address = [&exception_sp, &objc_id](uint64_t addr,
504 value.SetCompilerType(objc_id);
505 auto object = ValueObjectConstResult::Create(
506 exception_sp->GetTargetSP().get(), value, ConstString(name));
507 object = object->GetDynamicValue(eDynamicDontRunTarget);
511 for (size_t idx = 0; idx < reserved_dict->GetNumChildren(); idx++) {
512 ValueObjectSP dict_entry = reserved_dict->GetChildAtIndex(idx, true);
515 data.SetAddressByteSize(dict_entry->GetProcessSP()->GetAddressByteSize());
517 dict_entry->GetData(data, error);
518 if (error.Fail()) return ThreadSP();
520 lldb::offset_t data_offset = 0;
521 auto dict_entry_key = data.GetPointer(&data_offset);
522 auto dict_entry_value = data.GetPointer(&data_offset);
524 auto key_nsstring = objc_object_from_address(dict_entry_key, "key");
525 StreamString key_summary;
526 if (lldb_private::formatters::NSStringSummaryProvider(
527 *key_nsstring, key_summary, TypeSummaryOptions()) &&
528 !key_summary.Empty()) {
529 if (key_summary.GetString() == "\"callStackReturnAddresses\"") {
530 return_addresses = objc_object_from_address(dict_entry_value,
531 "callStackReturnAddresses");
537 if (!return_addresses) return ThreadSP();
539 return_addresses->GetChildMemberWithName(ConstString("_frames"), true);
540 addr_t frames_addr = frames_value->GetValueAsUnsigned(0);
542 return_addresses->GetChildMemberWithName(ConstString("_cnt"), true);
543 size_t count = count_value->GetValueAsUnsigned(0);
545 return_addresses->GetChildMemberWithName(ConstString("_ignore"), true);
546 size_t ignore = ignore_value->GetValueAsUnsigned(0);
548 size_t ptr_size = m_process->GetAddressByteSize();
549 std::vector<lldb::addr_t> pcs;
550 for (size_t idx = 0; idx < count; idx++) {
552 addr_t pc = m_process->ReadPointerFromMemory(
553 frames_addr + (ignore + idx) * ptr_size, error);
557 if (pcs.empty()) return ThreadSP();
559 ThreadSP new_thread_sp(new HistoryThread(*m_process, 0, pcs, 0, false));
560 m_process->GetExtendedThreadList().AddThread(new_thread_sp);
561 return new_thread_sp;
564 std::tuple<FileSpec, ConstString>
565 AppleObjCRuntime::GetExceptionThrowLocation() {
566 return std::make_tuple(
567 FileSpec("libobjc.A.dylib"), ConstString("objc_exception_throw"));
570 void AppleObjCRuntime::ReadObjCLibraryIfNeeded(const ModuleList &module_list) {
571 if (!HasReadObjCLibrary()) {
572 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
574 size_t num_modules = module_list.GetSize();
575 for (size_t i = 0; i < num_modules; i++) {
576 auto mod = module_list.GetModuleAtIndex(i);
577 if (IsModuleObjCLibrary(mod)) {
578 ReadObjCLibrary(mod);
585 void AppleObjCRuntime::ModulesDidLoad(const ModuleList &module_list) {
586 ReadObjCLibraryIfNeeded(module_list);