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/ConstString.h"
18 #include "lldb/Core/Error.h"
19 #include "lldb/Core/Log.h"
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/ModuleList.h"
22 #include "lldb/Core/PluginManager.h"
23 #include "lldb/Core/Scalar.h"
24 #include "lldb/Core/Section.h"
25 #include "lldb/Core/StreamString.h"
26 #include "lldb/Core/ValueObject.h"
27 #include "lldb/Expression/DiagnosticManager.h"
28 #include "lldb/Expression/FunctionCaller.h"
29 #include "lldb/Symbol/ClangASTContext.h"
30 #include "lldb/Symbol/ObjectFile.h"
31 #include "lldb/Target/ExecutionContext.h"
32 #include "lldb/Target/Process.h"
33 #include "lldb/Target/RegisterContext.h"
34 #include "lldb/Target/StopInfo.h"
35 #include "lldb/Target/Target.h"
36 #include "lldb/Target/Thread.h"
41 using namespace lldb_private;
43 static constexpr std::chrono::seconds g_po_function_timeout(15);
45 AppleObjCRuntime::~AppleObjCRuntime() {}
47 AppleObjCRuntime::AppleObjCRuntime(Process *process)
48 : ObjCLanguageRuntime(process), m_read_objc_library(false),
49 m_objc_trampoline_handler_ap(), m_Foundation_major() {
50 ReadObjCLibraryIfNeeded(process->GetTarget().GetImages());
53 bool AppleObjCRuntime::GetObjectDescription(Stream &str, ValueObject &valobj) {
54 CompilerType compiler_type(valobj.GetCompilerType());
56 // ObjC objects can only be pointers (or numbers that actually represents
58 // but haven't been typecast, because reasons..)
59 if (!compiler_type.IsIntegerType(is_signed) && !compiler_type.IsPointerType())
62 // Make the argument list: we pass one arg, the address of our pointer, to the
66 if (!valobj.ResolveValue(val.GetScalar()))
69 // Value Objects may not have a process in their ExecutionContextRef. But we
71 // in the ref we pass down to eventually call description. Get it from the
74 ExecutionContext exe_ctx;
75 if (valobj.GetProcessSP()) {
76 exe_ctx = ExecutionContext(valobj.GetExecutionContextRef());
78 exe_ctx.SetContext(valobj.GetTargetSP(), true);
79 if (!exe_ctx.HasProcessScope())
82 return GetObjectDescription(str, val, exe_ctx.GetBestExecutionContextScope());
84 bool AppleObjCRuntime::GetObjectDescription(Stream &strm, Value &value,
85 ExecutionContextScope *exe_scope) {
86 if (!m_read_objc_library)
89 ExecutionContext exe_ctx;
90 exe_scope->CalculateExecutionContext(exe_ctx);
91 Process *process = exe_ctx.GetProcessPtr();
95 // We need other parts of the exe_ctx, but the processes have to match.
96 assert(m_process == process);
98 // Get the function address for the print function.
99 const Address *function_address = GetPrintForDebuggerAddr();
100 if (!function_address)
103 Target *target = exe_ctx.GetTargetPtr();
104 CompilerType compiler_type = value.GetCompilerType();
106 if (!ClangASTContext::IsObjCObjectPointerType(compiler_type)) {
107 strm.Printf("Value doesn't point to an ObjC object.\n");
111 // If it is not a pointer, see if we can make it into a pointer.
112 ClangASTContext *ast_context = target->GetScratchClangASTContext();
113 CompilerType opaque_type = ast_context->GetBasicType(eBasicTypeObjCID);
115 opaque_type = ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
116 // value.SetContext(Value::eContextTypeClangType, opaque_type_ptr);
117 value.SetCompilerType(opaque_type);
120 ValueList arg_value_list;
121 arg_value_list.PushValue(value);
123 // This is the return value:
124 ClangASTContext *ast_context = target->GetScratchClangASTContext();
126 CompilerType return_compiler_type = ast_context->GetCStringType(true);
128 // ret.SetContext(Value::eContextTypeClangType, return_compiler_type);
129 ret.SetCompilerType(return_compiler_type);
131 if (exe_ctx.GetFramePtr() == NULL) {
132 Thread *thread = exe_ctx.GetThreadPtr();
133 if (thread == NULL) {
134 exe_ctx.SetThreadSP(process->GetThreadList().GetSelectedThread());
135 thread = exe_ctx.GetThreadPtr();
138 exe_ctx.SetFrameSP(thread->GetSelectedFrame());
142 // Now we're ready to call the function:
144 DiagnosticManager diagnostics;
145 lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS;
147 if (!m_print_object_caller_up) {
149 m_print_object_caller_up.reset(
150 exe_scope->CalculateTarget()->GetFunctionCallerForLanguage(
151 eLanguageTypeObjC, return_compiler_type, *function_address,
152 arg_value_list, "objc-object-description", error));
154 m_print_object_caller_up.reset();
155 strm.Printf("Could not get function runner to call print for debugger "
160 m_print_object_caller_up->InsertFunction(exe_ctx, wrapper_struct_addr,
163 m_print_object_caller_up->WriteFunctionArguments(
164 exe_ctx, wrapper_struct_addr, arg_value_list, diagnostics);
167 EvaluateExpressionOptions options;
168 options.SetUnwindOnError(true);
169 options.SetTryAllThreads(true);
170 options.SetStopOthers(true);
171 options.SetIgnoreBreakpoints(true);
172 options.SetTimeout(g_po_function_timeout);
174 ExpressionResults results = m_print_object_caller_up->ExecuteFunction(
175 exe_ctx, &wrapper_struct_addr, options, diagnostics, ret);
176 if (results != eExpressionCompleted) {
177 strm.Printf("Error evaluating Print Object function: %d.\n", results);
181 addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
185 size_t full_buffer_len = sizeof(buf) - 1;
186 size_t curr_len = full_buffer_len;
187 while (curr_len == full_buffer_len) {
189 curr_len = process->ReadCStringFromMemory(result_ptr + cstr_len, buf,
191 strm.Write(buf, curr_len);
192 cstr_len += curr_len;
197 lldb::ModuleSP AppleObjCRuntime::GetObjCModule() {
198 ModuleSP module_sp(m_objc_module_wp.lock());
202 Process *process = GetProcess();
204 const ModuleList &modules = process->GetTarget().GetImages();
205 for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {
206 module_sp = modules.GetModuleAtIndex(idx);
207 if (AppleObjCRuntime::AppleIsModuleObjCLibrary(module_sp)) {
208 m_objc_module_wp = module_sp;
216 Address *AppleObjCRuntime::GetPrintForDebuggerAddr() {
217 if (!m_PrintForDebugger_addr.get()) {
218 const ModuleList &modules = m_process->GetTarget().GetImages();
220 SymbolContextList contexts;
221 SymbolContext context;
223 if ((!modules.FindSymbolsWithNameAndType(ConstString("_NSPrintForDebugger"),
224 eSymbolTypeCode, contexts)) &&
225 (!modules.FindSymbolsWithNameAndType(ConstString("_CFPrintForDebugger"),
226 eSymbolTypeCode, contexts)))
229 contexts.GetContextAtIndex(0, context);
231 m_PrintForDebugger_addr.reset(new Address(context.symbol->GetAddress()));
234 return m_PrintForDebugger_addr.get();
237 bool AppleObjCRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
238 return in_value.GetCompilerType().IsPossibleDynamicType(
240 false, // do not check C++
244 bool AppleObjCRuntime::GetDynamicTypeAndAddress(
245 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
246 TypeAndOrName &class_type_or_name, Address &address,
247 Value::ValueType &value_type) {
252 AppleObjCRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
253 ValueObject &static_value) {
254 CompilerType static_type(static_value.GetCompilerType());
255 Flags static_type_flags(static_type.GetTypeInfo());
257 TypeAndOrName ret(type_and_or_name);
258 if (type_and_or_name.HasType()) {
259 // The type will always be the type of the dynamic object. If our parent's
260 // type was a pointer,
261 // then our type should be a pointer to the type of the dynamic object. If
262 // a reference, then the original type
264 CompilerType orig_type = type_and_or_name.GetCompilerType();
265 CompilerType corrected_type = orig_type;
266 if (static_type_flags.AllSet(eTypeIsPointer))
267 corrected_type = orig_type.GetPointerType();
268 ret.SetCompilerType(corrected_type);
270 // If we are here we need to adjust our dynamic type name to include the
271 // correct & or * symbol
272 std::string corrected_name(type_and_or_name.GetName().GetCString());
273 if (static_type_flags.AllSet(eTypeIsPointer))
274 corrected_name.append(" *");
275 // the parent type should be a correctly pointer'ed or referenc'ed type
276 ret.SetCompilerType(static_type);
277 ret.SetName(corrected_name.c_str());
282 bool AppleObjCRuntime::AppleIsModuleObjCLibrary(const ModuleSP &module_sp) {
284 const FileSpec &module_file_spec = module_sp->GetFileSpec();
285 static ConstString ObjCName("libobjc.A.dylib");
287 if (module_file_spec) {
288 if (module_file_spec.GetFilename() == ObjCName)
295 // we use the version of Foundation to make assumptions about the ObjC runtime
297 uint32_t AppleObjCRuntime::GetFoundationVersion() {
298 if (!m_Foundation_major.hasValue()) {
299 const ModuleList &modules = m_process->GetTarget().GetImages();
300 uint32_t major = UINT32_MAX;
301 for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {
302 lldb::ModuleSP module_sp = modules.GetModuleAtIndex(idx);
305 if (strcmp(module_sp->GetFileSpec().GetFilename().AsCString(""),
306 "Foundation") == 0) {
307 module_sp->GetVersion(&major, 1);
308 m_Foundation_major = 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
329 // current module, then we don't have to reread it?
330 m_objc_trampoline_handler_ap.reset(
331 new AppleObjCTrampolineHandler(m_process->shared_from_this(), module_sp));
332 if (m_objc_trampoline_handler_ap.get() != NULL) {
333 m_read_objc_library = true;
339 ThreadPlanSP AppleObjCRuntime::GetStepThroughTrampolinePlan(Thread &thread,
341 ThreadPlanSP thread_plan_sp;
342 if (m_objc_trampoline_handler_ap.get())
343 thread_plan_sp = m_objc_trampoline_handler_ap->GetStepThroughDispatchPlan(
344 thread, stop_others);
345 return thread_plan_sp;
348 //------------------------------------------------------------------
350 //------------------------------------------------------------------
351 ObjCLanguageRuntime::ObjCRuntimeVersions
352 AppleObjCRuntime::GetObjCVersion(Process *process, ModuleSP &objc_module_sp) {
354 return ObjCRuntimeVersions::eObjC_VersionUnknown;
356 Target &target = process->GetTarget();
357 if (target.GetArchitecture().GetTriple().getVendor() !=
358 llvm::Triple::VendorType::Apple)
359 return ObjCRuntimeVersions::eObjC_VersionUnknown;
361 const ModuleList &target_modules = target.GetImages();
362 std::lock_guard<std::recursive_mutex> gaurd(target_modules.GetMutex());
364 size_t num_images = target_modules.GetSize();
365 for (size_t i = 0; i < num_images; i++) {
366 ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i);
367 // One tricky bit here is that we might get called as part of the initial
368 // module loading, but
369 // before all the pre-run libraries get winnowed from the module list. So
370 // there might actually
371 // be an old and incorrect ObjC library sitting around in the list, and we
372 // don't want to look at that.
373 // That's why we call IsLoadedInTarget.
375 if (AppleIsModuleObjCLibrary(module_sp) &&
376 module_sp->IsLoadedInTarget(&target)) {
377 objc_module_sp = module_sp;
378 ObjectFile *ofile = module_sp->GetObjectFile();
380 return ObjCRuntimeVersions::eObjC_VersionUnknown;
382 SectionList *sections = module_sp->GetSectionList();
384 return ObjCRuntimeVersions::eObjC_VersionUnknown;
385 SectionSP v1_telltale_section_sp =
386 sections->FindSectionByName(ConstString("__OBJC"));
387 if (v1_telltale_section_sp) {
388 return ObjCRuntimeVersions::eAppleObjC_V1;
390 return ObjCRuntimeVersions::eAppleObjC_V2;
394 return ObjCRuntimeVersions::eObjC_VersionUnknown;
397 void AppleObjCRuntime::SetExceptionBreakpoints() {
398 const bool catch_bp = false;
399 const bool throw_bp = true;
400 const bool is_internal = true;
402 if (!m_objc_exception_bp_sp) {
403 m_objc_exception_bp_sp = LanguageRuntime::CreateExceptionBreakpoint(
404 m_process->GetTarget(), GetLanguageType(), catch_bp, throw_bp,
406 if (m_objc_exception_bp_sp)
407 m_objc_exception_bp_sp->SetBreakpointKind("ObjC exception");
409 m_objc_exception_bp_sp->SetEnabled(true);
412 void AppleObjCRuntime::ClearExceptionBreakpoints() {
416 if (m_objc_exception_bp_sp.get()) {
417 m_objc_exception_bp_sp->SetEnabled(false);
421 bool AppleObjCRuntime::ExceptionBreakpointsAreSet() {
422 return m_objc_exception_bp_sp && m_objc_exception_bp_sp->IsEnabled();
425 bool AppleObjCRuntime::ExceptionBreakpointsExplainStop(
426 lldb::StopInfoSP stop_reason) {
430 if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint)
433 uint64_t break_site_id = stop_reason->GetValue();
434 return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint(
435 break_site_id, m_objc_exception_bp_sp->GetID());
438 bool AppleObjCRuntime::CalculateHasNewLiteralsAndIndexing() {
442 Target &target(m_process->GetTarget());
444 static ConstString s_method_signature(
445 "-[NSDictionary objectForKeyedSubscript:]");
446 static ConstString s_arclite_method_signature(
447 "__arclite_objectForKeyedSubscript");
449 SymbolContextList sc_list;
451 if (target.GetImages().FindSymbolsWithNameAndType(s_method_signature,
452 eSymbolTypeCode, sc_list) ||
453 target.GetImages().FindSymbolsWithNameAndType(s_arclite_method_signature,
454 eSymbolTypeCode, sc_list))
460 lldb::SearchFilterSP AppleObjCRuntime::CreateExceptionSearchFilter() {
461 Target &target = m_process->GetTarget();
463 if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) {
464 FileSpecList filter_modules;
465 filter_modules.Append(FileSpec("libobjc.A.dylib", false));
466 return target.GetSearchFilterForModuleList(&filter_modules);
468 return LanguageRuntime::CreateExceptionSearchFilter();
472 void AppleObjCRuntime::ReadObjCLibraryIfNeeded(const ModuleList &module_list) {
473 if (!HasReadObjCLibrary()) {
474 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
476 size_t num_modules = module_list.GetSize();
477 for (size_t i = 0; i < num_modules; i++) {
478 auto mod = module_list.GetModuleAtIndex(i);
479 if (IsModuleObjCLibrary(mod)) {
480 ReadObjCLibrary(mod);
487 void AppleObjCRuntime::ModulesDidLoad(const ModuleList &module_list) {
488 ReadObjCLibraryIfNeeded(module_list);