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/Scalar.h"
21 #include "lldb/Core/Section.h"
22 #include "lldb/Core/ValueObject.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/Status.h"
36 #include "lldb/Utility/StreamString.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
57 // pointers but haven't been typecast, because reasons..)
58 if (!compiler_type.IsIntegerType(is_signed) && !compiler_type.IsPointerType())
61 // Make the argument list: we pass one arg, the address of our pointer, to
62 // the print function.
65 if (!valobj.ResolveValue(val.GetScalar()))
68 // Value Objects may not have a process in their ExecutionContextRef. But we
69 // need to have one in the ref we pass down to eventually call description.
70 // Get it from the target if it isn't present.
71 ExecutionContext exe_ctx;
72 if (valobj.GetProcessSP()) {
73 exe_ctx = ExecutionContext(valobj.GetExecutionContextRef());
75 exe_ctx.SetContext(valobj.GetTargetSP(), true);
76 if (!exe_ctx.HasProcessScope())
79 return GetObjectDescription(str, val, exe_ctx.GetBestExecutionContextScope());
81 bool AppleObjCRuntime::GetObjectDescription(Stream &strm, Value &value,
82 ExecutionContextScope *exe_scope) {
83 if (!m_read_objc_library)
86 ExecutionContext exe_ctx;
87 exe_scope->CalculateExecutionContext(exe_ctx);
88 Process *process = exe_ctx.GetProcessPtr();
92 // We need other parts of the exe_ctx, but the processes have to match.
93 assert(m_process == process);
95 // Get the function address for the print function.
96 const Address *function_address = GetPrintForDebuggerAddr();
97 if (!function_address)
100 Target *target = exe_ctx.GetTargetPtr();
101 CompilerType compiler_type = value.GetCompilerType();
103 if (!ClangASTContext::IsObjCObjectPointerType(compiler_type)) {
104 strm.Printf("Value doesn't point to an ObjC object.\n");
108 // If it is not a pointer, see if we can make it into a pointer.
109 ClangASTContext *ast_context = target->GetScratchClangASTContext();
110 CompilerType opaque_type = ast_context->GetBasicType(eBasicTypeObjCID);
112 opaque_type = ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
113 // value.SetContext(Value::eContextTypeClangType, opaque_type_ptr);
114 value.SetCompilerType(opaque_type);
117 ValueList arg_value_list;
118 arg_value_list.PushValue(value);
120 // This is the return value:
121 ClangASTContext *ast_context = target->GetScratchClangASTContext();
123 CompilerType return_compiler_type = ast_context->GetCStringType(true);
125 // ret.SetContext(Value::eContextTypeClangType, return_compiler_type);
126 ret.SetCompilerType(return_compiler_type);
128 if (exe_ctx.GetFramePtr() == NULL) {
129 Thread *thread = exe_ctx.GetThreadPtr();
130 if (thread == NULL) {
131 exe_ctx.SetThreadSP(process->GetThreadList().GetSelectedThread());
132 thread = exe_ctx.GetThreadPtr();
135 exe_ctx.SetFrameSP(thread->GetSelectedFrame());
139 // Now we're ready to call the function:
141 DiagnosticManager diagnostics;
142 lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS;
144 if (!m_print_object_caller_up) {
146 m_print_object_caller_up.reset(
147 exe_scope->CalculateTarget()->GetFunctionCallerForLanguage(
148 eLanguageTypeObjC, return_compiler_type, *function_address,
149 arg_value_list, "objc-object-description", error));
151 m_print_object_caller_up.reset();
152 strm.Printf("Could not get function runner to call print for debugger "
157 m_print_object_caller_up->InsertFunction(exe_ctx, wrapper_struct_addr,
160 m_print_object_caller_up->WriteFunctionArguments(
161 exe_ctx, wrapper_struct_addr, arg_value_list, diagnostics);
164 EvaluateExpressionOptions options;
165 options.SetUnwindOnError(true);
166 options.SetTryAllThreads(true);
167 options.SetStopOthers(true);
168 options.SetIgnoreBreakpoints(true);
169 options.SetTimeout(g_po_function_timeout);
171 ExpressionResults results = m_print_object_caller_up->ExecuteFunction(
172 exe_ctx, &wrapper_struct_addr, options, diagnostics, ret);
173 if (results != eExpressionCompleted) {
174 strm.Printf("Error evaluating Print Object function: %d.\n", results);
178 addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
182 size_t full_buffer_len = sizeof(buf) - 1;
183 size_t curr_len = full_buffer_len;
184 while (curr_len == full_buffer_len) {
186 curr_len = process->ReadCStringFromMemory(result_ptr + cstr_len, buf,
188 strm.Write(buf, curr_len);
189 cstr_len += curr_len;
194 lldb::ModuleSP AppleObjCRuntime::GetObjCModule() {
195 ModuleSP module_sp(m_objc_module_wp.lock());
199 Process *process = GetProcess();
201 const ModuleList &modules = process->GetTarget().GetImages();
202 for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {
203 module_sp = modules.GetModuleAtIndex(idx);
204 if (AppleObjCRuntime::AppleIsModuleObjCLibrary(module_sp)) {
205 m_objc_module_wp = module_sp;
213 Address *AppleObjCRuntime::GetPrintForDebuggerAddr() {
214 if (!m_PrintForDebugger_addr.get()) {
215 const ModuleList &modules = m_process->GetTarget().GetImages();
217 SymbolContextList contexts;
218 SymbolContext context;
220 if ((!modules.FindSymbolsWithNameAndType(ConstString("_NSPrintForDebugger"),
221 eSymbolTypeCode, contexts)) &&
222 (!modules.FindSymbolsWithNameAndType(ConstString("_CFPrintForDebugger"),
223 eSymbolTypeCode, contexts)))
226 contexts.GetContextAtIndex(0, context);
228 m_PrintForDebugger_addr.reset(new Address(context.symbol->GetAddress()));
231 return m_PrintForDebugger_addr.get();
234 bool AppleObjCRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
235 return in_value.GetCompilerType().IsPossibleDynamicType(
237 false, // do not check C++
241 bool AppleObjCRuntime::GetDynamicTypeAndAddress(
242 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
243 TypeAndOrName &class_type_or_name, Address &address,
244 Value::ValueType &value_type) {
249 AppleObjCRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
250 ValueObject &static_value) {
251 CompilerType static_type(static_value.GetCompilerType());
252 Flags static_type_flags(static_type.GetTypeInfo());
254 TypeAndOrName ret(type_and_or_name);
255 if (type_and_or_name.HasType()) {
256 // The type will always be the type of the dynamic object. If our parent's
257 // type was a pointer, then our type should be a pointer to the type of the
258 // dynamic object. If a reference, then the original type should be
260 CompilerType orig_type = type_and_or_name.GetCompilerType();
261 CompilerType corrected_type = orig_type;
262 if (static_type_flags.AllSet(eTypeIsPointer))
263 corrected_type = orig_type.GetPointerType();
264 ret.SetCompilerType(corrected_type);
266 // If we are here we need to adjust our dynamic type name to include the
267 // correct & or * symbol
268 std::string corrected_name(type_and_or_name.GetName().GetCString());
269 if (static_type_flags.AllSet(eTypeIsPointer))
270 corrected_name.append(" *");
271 // the parent type should be a correctly pointer'ed or referenc'ed type
272 ret.SetCompilerType(static_type);
273 ret.SetName(corrected_name.c_str());
278 bool AppleObjCRuntime::AppleIsModuleObjCLibrary(const ModuleSP &module_sp) {
280 const FileSpec &module_file_spec = module_sp->GetFileSpec();
281 static ConstString ObjCName("libobjc.A.dylib");
283 if (module_file_spec) {
284 if (module_file_spec.GetFilename() == ObjCName)
291 // we use the version of Foundation to make assumptions about the ObjC runtime
293 uint32_t AppleObjCRuntime::GetFoundationVersion() {
294 if (!m_Foundation_major.hasValue()) {
295 const ModuleList &modules = m_process->GetTarget().GetImages();
296 for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {
297 lldb::ModuleSP module_sp = modules.GetModuleAtIndex(idx);
300 if (strcmp(module_sp->GetFileSpec().GetFilename().AsCString(""),
301 "Foundation") == 0) {
302 m_Foundation_major = module_sp->GetVersion().getMajor();
303 return *m_Foundation_major;
306 return LLDB_INVALID_MODULE_VERSION;
308 return m_Foundation_major.getValue();
311 void AppleObjCRuntime::GetValuesForGlobalCFBooleans(lldb::addr_t &cf_true,
312 lldb::addr_t &cf_false) {
313 cf_true = cf_false = LLDB_INVALID_ADDRESS;
316 bool AppleObjCRuntime::IsModuleObjCLibrary(const ModuleSP &module_sp) {
317 return AppleIsModuleObjCLibrary(module_sp);
320 bool AppleObjCRuntime::ReadObjCLibrary(const ModuleSP &module_sp) {
321 // Maybe check here and if we have a handler already, and the UUID of this
322 // module is the same as the one in the current module, then we don't have to
324 m_objc_trampoline_handler_ap.reset(
325 new AppleObjCTrampolineHandler(m_process->shared_from_this(), module_sp));
326 if (m_objc_trampoline_handler_ap.get() != NULL) {
327 m_read_objc_library = true;
333 ThreadPlanSP AppleObjCRuntime::GetStepThroughTrampolinePlan(Thread &thread,
335 ThreadPlanSP thread_plan_sp;
336 if (m_objc_trampoline_handler_ap.get())
337 thread_plan_sp = m_objc_trampoline_handler_ap->GetStepThroughDispatchPlan(
338 thread, stop_others);
339 return thread_plan_sp;
342 //------------------------------------------------------------------
344 //------------------------------------------------------------------
345 ObjCLanguageRuntime::ObjCRuntimeVersions
346 AppleObjCRuntime::GetObjCVersion(Process *process, ModuleSP &objc_module_sp) {
348 return ObjCRuntimeVersions::eObjC_VersionUnknown;
350 Target &target = process->GetTarget();
351 if (target.GetArchitecture().GetTriple().getVendor() !=
352 llvm::Triple::VendorType::Apple)
353 return ObjCRuntimeVersions::eObjC_VersionUnknown;
355 const ModuleList &target_modules = target.GetImages();
356 std::lock_guard<std::recursive_mutex> gaurd(target_modules.GetMutex());
358 size_t num_images = target_modules.GetSize();
359 for (size_t i = 0; i < num_images; i++) {
360 ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i);
361 // One tricky bit here is that we might get called as part of the initial
362 // module loading, but before all the pre-run libraries get winnowed from
363 // the module list. So there might actually be an old and incorrect ObjC
364 // library sitting around in the list, and we don't want to look at that.
365 // That's why we call IsLoadedInTarget.
367 if (AppleIsModuleObjCLibrary(module_sp) &&
368 module_sp->IsLoadedInTarget(&target)) {
369 objc_module_sp = module_sp;
370 ObjectFile *ofile = module_sp->GetObjectFile();
372 return ObjCRuntimeVersions::eObjC_VersionUnknown;
374 SectionList *sections = module_sp->GetSectionList();
376 return ObjCRuntimeVersions::eObjC_VersionUnknown;
377 SectionSP v1_telltale_section_sp =
378 sections->FindSectionByName(ConstString("__OBJC"));
379 if (v1_telltale_section_sp) {
380 return ObjCRuntimeVersions::eAppleObjC_V1;
382 return ObjCRuntimeVersions::eAppleObjC_V2;
386 return ObjCRuntimeVersions::eObjC_VersionUnknown;
389 void AppleObjCRuntime::SetExceptionBreakpoints() {
390 const bool catch_bp = false;
391 const bool throw_bp = true;
392 const bool is_internal = true;
394 if (!m_objc_exception_bp_sp) {
395 m_objc_exception_bp_sp = LanguageRuntime::CreateExceptionBreakpoint(
396 m_process->GetTarget(), GetLanguageType(), catch_bp, throw_bp,
398 if (m_objc_exception_bp_sp)
399 m_objc_exception_bp_sp->SetBreakpointKind("ObjC exception");
401 m_objc_exception_bp_sp->SetEnabled(true);
404 void AppleObjCRuntime::ClearExceptionBreakpoints() {
408 if (m_objc_exception_bp_sp.get()) {
409 m_objc_exception_bp_sp->SetEnabled(false);
413 bool AppleObjCRuntime::ExceptionBreakpointsAreSet() {
414 return m_objc_exception_bp_sp && m_objc_exception_bp_sp->IsEnabled();
417 bool AppleObjCRuntime::ExceptionBreakpointsExplainStop(
418 lldb::StopInfoSP stop_reason) {
422 if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint)
425 uint64_t break_site_id = stop_reason->GetValue();
426 return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint(
427 break_site_id, m_objc_exception_bp_sp->GetID());
430 bool AppleObjCRuntime::CalculateHasNewLiteralsAndIndexing() {
434 Target &target(m_process->GetTarget());
436 static ConstString s_method_signature(
437 "-[NSDictionary objectForKeyedSubscript:]");
438 static ConstString s_arclite_method_signature(
439 "__arclite_objectForKeyedSubscript");
441 SymbolContextList sc_list;
443 if (target.GetImages().FindSymbolsWithNameAndType(s_method_signature,
444 eSymbolTypeCode, sc_list) ||
445 target.GetImages().FindSymbolsWithNameAndType(s_arclite_method_signature,
446 eSymbolTypeCode, sc_list))
452 lldb::SearchFilterSP AppleObjCRuntime::CreateExceptionSearchFilter() {
453 Target &target = m_process->GetTarget();
455 if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) {
456 FileSpecList filter_modules;
457 filter_modules.Append(FileSpec("libobjc.A.dylib", false));
458 return target.GetSearchFilterForModuleList(&filter_modules);
460 return LanguageRuntime::CreateExceptionSearchFilter();
464 void AppleObjCRuntime::ReadObjCLibraryIfNeeded(const ModuleList &module_list) {
465 if (!HasReadObjCLibrary()) {
466 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
468 size_t num_modules = module_list.GetSize();
469 for (size_t i = 0; i < num_modules; i++) {
470 auto mod = module_list.GetModuleAtIndex(i);
471 if (IsModuleObjCLibrary(mod)) {
472 ReadObjCLibrary(mod);
479 void AppleObjCRuntime::ModulesDidLoad(const ModuleList &module_list) {
480 ReadObjCLibraryIfNeeded(module_list);