1//===-- AppleObjCRuntime.cpp -------------------------------------*- C++ 2//-*-===// 3// 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 7// 8//===----------------------------------------------------------------------===// 9 10#include "AppleObjCRuntime.h" 11#include "AppleObjCTrampolineHandler.h" 12 13#include "clang/AST/Type.h" 14 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" 38 39#include "Plugins/Process/Utility/HistoryThread.h" 40#include "Plugins/Language/ObjC/NSString.h" 41#include "Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h" 42 43#include <vector> 44 45using namespace lldb; 46using namespace lldb_private; 47 48char AppleObjCRuntime::ID = 0; 49 50AppleObjCRuntime::~AppleObjCRuntime() {} 51 52AppleObjCRuntime::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()); 56} 57 58bool AppleObjCRuntime::GetObjectDescription(Stream &str, ValueObject &valobj) { 59 CompilerType compiler_type(valobj.GetCompilerType()); 60 bool is_signed; 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()) 64 return false; 65 66 // Make the argument list: we pass one arg, the address of our pointer, to 67 // the print function. 68 Value val; 69 70 if (!valobj.ResolveValue(val.GetScalar())) 71 return false; 72 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()); 79 } else { 80 exe_ctx.SetContext(valobj.GetTargetSP(), true); 81 if (!exe_ctx.HasProcessScope()) 82 return false; 83 } 84 return GetObjectDescription(str, val, exe_ctx.GetBestExecutionContextScope()); 85} 86bool AppleObjCRuntime::GetObjectDescription(Stream &strm, Value &value, 87 ExecutionContextScope *exe_scope) { 88 if (!m_read_objc_library) 89 return false; 90 91 ExecutionContext exe_ctx; 92 exe_scope->CalculateExecutionContext(exe_ctx); 93 Process *process = exe_ctx.GetProcessPtr(); 94 if (!process) 95 return false; 96 97 // We need other parts of the exe_ctx, but the processes have to match. 98 assert(m_process == process); 99 100 // Get the function address for the print function. 101 const Address *function_address = GetPrintForDebuggerAddr(); 102 if (!function_address) 103 return false; 104 105 Target *target = exe_ctx.GetTargetPtr(); 106 CompilerType compiler_type = value.GetCompilerType(); 107 if (compiler_type) { 108 if (!ClangASTContext::IsObjCObjectPointerType(compiler_type)) { 109 strm.Printf("Value doesn't point to an ObjC object.\n"); 110 return false; 111 } 112 } else { 113 // If it is not a pointer, see if we can make it into a pointer. 114 ClangASTContext *ast_context = ClangASTContext::GetScratch(*target); 115 if (!ast_context) 116 return false; 117 118 CompilerType opaque_type = ast_context->GetBasicType(eBasicTypeObjCID); 119 if (!opaque_type) 120 opaque_type = ast_context->GetBasicType(eBasicTypeVoid).GetPointerType(); 121 // value.SetContext(Value::eContextTypeClangType, opaque_type_ptr); 122 value.SetCompilerType(opaque_type); 123 } 124 125 ValueList arg_value_list; 126 arg_value_list.PushValue(value); 127 128 // This is the return value: 129 ClangASTContext *ast_context = ClangASTContext::GetScratch(*target); 130 if (!ast_context) 131 return false; 132 133 CompilerType return_compiler_type = ast_context->GetCStringType(true); 134 Value ret; 135 // ret.SetContext(Value::eContextTypeClangType, return_compiler_type); 136 ret.SetCompilerType(return_compiler_type); 137 138 if (exe_ctx.GetFramePtr() == nullptr) { 139 Thread *thread = exe_ctx.GetThreadPtr(); 140 if (thread == nullptr) { 141 exe_ctx.SetThreadSP(process->GetThreadList().GetSelectedThread()); 142 thread = exe_ctx.GetThreadPtr(); 143 } 144 if (thread) { 145 exe_ctx.SetFrameSP(thread->GetSelectedFrame()); 146 } 147 } 148 149 // Now we're ready to call the function: 150 151 DiagnosticManager diagnostics; 152 lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS; 153 154 if (!m_print_object_caller_up) { 155 Status error; 156 m_print_object_caller_up.reset( 157 exe_scope->CalculateTarget()->GetFunctionCallerForLanguage( 158 eLanguageTypeObjC, return_compiler_type, *function_address, 159 arg_value_list, "objc-object-description", error)); 160 if (error.Fail()) { 161 m_print_object_caller_up.reset(); 162 strm.Printf("Could not get function runner to call print for debugger " 163 "function: %s.", 164 error.AsCString()); 165 return false; 166 } 167 m_print_object_caller_up->InsertFunction(exe_ctx, wrapper_struct_addr, 168 diagnostics); 169 } else { 170 m_print_object_caller_up->WriteFunctionArguments( 171 exe_ctx, wrapper_struct_addr, arg_value_list, diagnostics); 172 } 173 174 EvaluateExpressionOptions options; 175 options.SetUnwindOnError(true); 176 options.SetTryAllThreads(true); 177 options.SetStopOthers(true); 178 options.SetIgnoreBreakpoints(true); 179 options.SetTimeout(process->GetUtilityExpressionTimeout()); 180 options.SetIsForUtilityExpr(true); 181 182 ExpressionResults results = m_print_object_caller_up->ExecuteFunction( 183 exe_ctx, &wrapper_struct_addr, options, diagnostics, ret); 184 if (results != eExpressionCompleted) { 185 strm.Printf("Error evaluating Print Object function: %d.\n", results); 186 return false; 187 } 188 189 addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS); 190 191 char buf[512]; 192 size_t cstr_len = 0; 193 size_t full_buffer_len = sizeof(buf) - 1; 194 size_t curr_len = full_buffer_len; 195 while (curr_len == full_buffer_len) { 196 Status error; 197 curr_len = process->ReadCStringFromMemory(result_ptr + cstr_len, buf, 198 sizeof(buf), error); 199 strm.Write(buf, curr_len); 200 cstr_len += curr_len; 201 } 202 return cstr_len > 0; 203} 204 205lldb::ModuleSP AppleObjCRuntime::GetObjCModule() { 206 ModuleSP module_sp(m_objc_module_wp.lock()); 207 if (module_sp) 208 return module_sp; 209 210 Process *process = GetProcess(); 211 if (process) { 212 const ModuleList &modules = process->GetTarget().GetImages(); 213 for (uint32_t idx = 0; idx < modules.GetSize(); idx++) { 214 module_sp = modules.GetModuleAtIndex(idx); 215 if (AppleObjCRuntime::AppleIsModuleObjCLibrary(module_sp)) { 216 m_objc_module_wp = module_sp; 217 return module_sp; 218 } 219 } 220 } 221 return ModuleSP(); 222} 223 224Address *AppleObjCRuntime::GetPrintForDebuggerAddr() { 225 if (!m_PrintForDebugger_addr) { 226 const ModuleList &modules = m_process->GetTarget().GetImages(); 227 228 SymbolContextList contexts; 229 SymbolContext context; 230 231 modules.FindSymbolsWithNameAndType(ConstString("_NSPrintForDebugger"), 232 eSymbolTypeCode, contexts); 233 if (contexts.IsEmpty()) { 234 modules.FindSymbolsWithNameAndType(ConstString("_CFPrintForDebugger"), 235 eSymbolTypeCode, contexts); 236 if (contexts.IsEmpty()) 237 return nullptr; 238 } 239 240 contexts.GetContextAtIndex(0, context); 241 242 m_PrintForDebugger_addr.reset(new Address(context.symbol->GetAddress())); 243 } 244 245 return m_PrintForDebugger_addr.get(); 246} 247 248bool AppleObjCRuntime::CouldHaveDynamicValue(ValueObject &in_value) { 249 return in_value.GetCompilerType().IsPossibleDynamicType( 250 nullptr, 251 false, // do not check C++ 252 true); // check ObjC 253} 254 255bool AppleObjCRuntime::GetDynamicTypeAndAddress( 256 ValueObject &in_value, lldb::DynamicValueType use_dynamic, 257 TypeAndOrName &class_type_or_name, Address &address, 258 Value::ValueType &value_type) { 259 return false; 260} 261 262TypeAndOrName 263AppleObjCRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name, 264 ValueObject &static_value) { 265 CompilerType static_type(static_value.GetCompilerType()); 266 Flags static_type_flags(static_type.GetTypeInfo()); 267 268 TypeAndOrName ret(type_and_or_name); 269 if (type_and_or_name.HasType()) { 270 // The type will always be the type of the dynamic object. If our parent's 271 // type was a pointer, then our type should be a pointer to the type of the 272 // dynamic object. If a reference, then the original type should be 273 // okay... 274 CompilerType orig_type = type_and_or_name.GetCompilerType(); 275 CompilerType corrected_type = orig_type; 276 if (static_type_flags.AllSet(eTypeIsPointer)) 277 corrected_type = orig_type.GetPointerType(); 278 ret.SetCompilerType(corrected_type); 279 } else { 280 // If we are here we need to adjust our dynamic type name to include the 281 // correct & or * symbol 282 std::string corrected_name(type_and_or_name.GetName().GetCString()); 283 if (static_type_flags.AllSet(eTypeIsPointer)) 284 corrected_name.append(" *"); 285 // the parent type should be a correctly pointer'ed or referenc'ed type 286 ret.SetCompilerType(static_type); 287 ret.SetName(corrected_name.c_str()); 288 } 289 return ret; 290} 291 292bool AppleObjCRuntime::AppleIsModuleObjCLibrary(const ModuleSP &module_sp) { 293 if (module_sp) { 294 const FileSpec &module_file_spec = module_sp->GetFileSpec(); 295 static ConstString ObjCName("libobjc.A.dylib"); 296 297 if (module_file_spec) { 298 if (module_file_spec.GetFilename() == ObjCName) 299 return true; 300 } 301 } 302 return false; 303} 304 305// we use the version of Foundation to make assumptions about the ObjC runtime 306// on a target 307uint32_t AppleObjCRuntime::GetFoundationVersion() { 308 if (!m_Foundation_major.hasValue()) { 309 const ModuleList &modules = m_process->GetTarget().GetImages(); 310 for (uint32_t idx = 0; idx < modules.GetSize(); idx++) { 311 lldb::ModuleSP module_sp = modules.GetModuleAtIndex(idx); 312 if (!module_sp) 313 continue; 314 if (strcmp(module_sp->GetFileSpec().GetFilename().AsCString(""), 315 "Foundation") == 0) { 316 m_Foundation_major = module_sp->GetVersion().getMajor(); 317 return *m_Foundation_major; 318 } 319 } 320 return LLDB_INVALID_MODULE_VERSION; 321 } else 322 return m_Foundation_major.getValue(); 323} 324 325void AppleObjCRuntime::GetValuesForGlobalCFBooleans(lldb::addr_t &cf_true, 326 lldb::addr_t &cf_false) { 327 cf_true = cf_false = LLDB_INVALID_ADDRESS; 328} 329 330bool AppleObjCRuntime::IsModuleObjCLibrary(const ModuleSP &module_sp) { 331 return AppleIsModuleObjCLibrary(module_sp); 332} 333 334bool AppleObjCRuntime::ReadObjCLibrary(const ModuleSP &module_sp) { 335 // Maybe check here and if we have a handler already, and the UUID of this 336 // module is the same as the one in the current module, then we don't have to 337 // reread it? 338 m_objc_trampoline_handler_up.reset( 339 new AppleObjCTrampolineHandler(m_process->shared_from_this(), module_sp)); 340 if (m_objc_trampoline_handler_up != nullptr) { 341 m_read_objc_library = true; 342 return true; 343 } else 344 return false; 345} 346 347ThreadPlanSP AppleObjCRuntime::GetStepThroughTrampolinePlan(Thread &thread, 348 bool stop_others) { 349 ThreadPlanSP thread_plan_sp; 350 if (m_objc_trampoline_handler_up) 351 thread_plan_sp = m_objc_trampoline_handler_up->GetStepThroughDispatchPlan( 352 thread, stop_others); 353 return thread_plan_sp; 354} 355 356// Static Functions 357ObjCLanguageRuntime::ObjCRuntimeVersions 358AppleObjCRuntime::GetObjCVersion(Process *process, ModuleSP &objc_module_sp) { 359 if (!process) 360 return ObjCRuntimeVersions::eObjC_VersionUnknown; 361 362 Target &target = process->GetTarget(); 363 if (target.GetArchitecture().GetTriple().getVendor() != 364 llvm::Triple::VendorType::Apple) 365 return ObjCRuntimeVersions::eObjC_VersionUnknown; 366 367 const ModuleList &target_modules = target.GetImages(); 368 std::lock_guard<std::recursive_mutex> gaurd(target_modules.GetMutex()); 369 370 size_t num_images = target_modules.GetSize(); 371 for (size_t i = 0; i < num_images; i++) { 372 ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i); 373 // One tricky bit here is that we might get called as part of the initial 374 // module loading, but before all the pre-run libraries get winnowed from 375 // the module list. So there might actually be an old and incorrect ObjC 376 // library sitting around in the list, and we don't want to look at that. 377 // That's why we call IsLoadedInTarget. 378 379 if (AppleIsModuleObjCLibrary(module_sp) && 380 module_sp->IsLoadedInTarget(&target)) { 381 objc_module_sp = module_sp; 382 ObjectFile *ofile = module_sp->GetObjectFile(); 383 if (!ofile) 384 return ObjCRuntimeVersions::eObjC_VersionUnknown; 385 386 SectionList *sections = module_sp->GetSectionList(); 387 if (!sections) 388 return ObjCRuntimeVersions::eObjC_VersionUnknown; 389 SectionSP v1_telltale_section_sp = 390 sections->FindSectionByName(ConstString("__OBJC")); 391 if (v1_telltale_section_sp) { 392 return ObjCRuntimeVersions::eAppleObjC_V1; 393 } 394 return ObjCRuntimeVersions::eAppleObjC_V2; 395 } 396 } 397 398 return ObjCRuntimeVersions::eObjC_VersionUnknown; 399} 400 401void AppleObjCRuntime::SetExceptionBreakpoints() { 402 const bool catch_bp = false; 403 const bool throw_bp = true; 404 const bool is_internal = true; 405 406 if (!m_objc_exception_bp_sp) { 407 m_objc_exception_bp_sp = LanguageRuntime::CreateExceptionBreakpoint( 408 m_process->GetTarget(), GetLanguageType(), catch_bp, throw_bp, 409 is_internal); 410 if (m_objc_exception_bp_sp) 411 m_objc_exception_bp_sp->SetBreakpointKind("ObjC exception"); 412 } else 413 m_objc_exception_bp_sp->SetEnabled(true); 414} 415 416void AppleObjCRuntime::ClearExceptionBreakpoints() { 417 if (!m_process) 418 return; 419 420 if (m_objc_exception_bp_sp.get()) { 421 m_objc_exception_bp_sp->SetEnabled(false); 422 } 423} 424 425bool AppleObjCRuntime::ExceptionBreakpointsAreSet() { 426 return m_objc_exception_bp_sp && m_objc_exception_bp_sp->IsEnabled(); 427} 428 429bool AppleObjCRuntime::ExceptionBreakpointsExplainStop( 430 lldb::StopInfoSP stop_reason) { 431 if (!m_process) 432 return false; 433 434 if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint) 435 return false; 436 437 uint64_t break_site_id = stop_reason->GetValue(); 438 return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint( 439 break_site_id, m_objc_exception_bp_sp->GetID()); 440} 441 442bool AppleObjCRuntime::CalculateHasNewLiteralsAndIndexing() { 443 if (!m_process) 444 return false; 445 446 Target &target(m_process->GetTarget()); 447 448 static ConstString s_method_signature( 449 "-[NSDictionary objectForKeyedSubscript:]"); 450 static ConstString s_arclite_method_signature( 451 "__arclite_objectForKeyedSubscript"); 452 453 SymbolContextList sc_list; 454 455 target.GetImages().FindSymbolsWithNameAndType(s_method_signature, 456 eSymbolTypeCode, sc_list); 457 if (sc_list.IsEmpty()) 458 target.GetImages().FindSymbolsWithNameAndType(s_arclite_method_signature, 459 eSymbolTypeCode, sc_list); 460 return !sc_list.IsEmpty(); 461} 462 463lldb::SearchFilterSP AppleObjCRuntime::CreateExceptionSearchFilter() { 464 Target &target = m_process->GetTarget(); 465 466 FileSpecList filter_modules; 467 if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) { 468 filter_modules.Append(std::get<0>(GetExceptionThrowLocation())); 469 } 470 return target.GetSearchFilterForModuleList(&filter_modules); 471} 472 473ValueObjectSP AppleObjCRuntime::GetExceptionObjectForThread( 474 ThreadSP thread_sp) { 475 auto *cpp_runtime = m_process->GetLanguageRuntime(eLanguageTypeC_plus_plus); 476 if (!cpp_runtime) return ValueObjectSP(); 477 auto cpp_exception = cpp_runtime->GetExceptionObjectForThread(thread_sp); 478 if (!cpp_exception) return ValueObjectSP(); 479 480 auto descriptor = GetClassDescriptor(*cpp_exception); 481 if (!descriptor || !descriptor->IsValid()) return ValueObjectSP(); 482 483 while (descriptor) { 484 ConstString class_name(descriptor->GetClassName()); 485 if (class_name == "NSException") 486 return cpp_exception; 487 descriptor = descriptor->GetSuperclass(); 488 } 489 490 return ValueObjectSP(); 491} 492 493ThreadSP AppleObjCRuntime::GetBacktraceThreadFromException( 494 lldb::ValueObjectSP exception_sp) { 495 ValueObjectSP reserved_dict = 496 exception_sp->GetChildMemberWithName(ConstString("reserved"), true); 497 if (!reserved_dict) return ThreadSP(); 498 499 reserved_dict = reserved_dict->GetSyntheticValue(); 500 if (!reserved_dict) return ThreadSP(); 501 502 ClangASTContext *clang_ast_context = 503 ClangASTContext::GetScratch(*exception_sp->GetTargetSP()); 504 if (!clang_ast_context) 505 return ThreadSP(); 506 CompilerType objc_id = 507 clang_ast_context->GetBasicType(lldb::eBasicTypeObjCID); 508 ValueObjectSP return_addresses; 509 510 auto objc_object_from_address = [&exception_sp, &objc_id](uint64_t addr, 511 const char *name) { 512 Value value(addr); 513 value.SetCompilerType(objc_id); 514 auto object = ValueObjectConstResult::Create( 515 exception_sp->GetTargetSP().get(), value, ConstString(name)); 516 object = object->GetDynamicValue(eDynamicDontRunTarget); 517 return object; 518 }; 519 520 for (size_t idx = 0; idx < reserved_dict->GetNumChildren(); idx++) { 521 ValueObjectSP dict_entry = reserved_dict->GetChildAtIndex(idx, true); 522 523 DataExtractor data; 524 data.SetAddressByteSize(dict_entry->GetProcessSP()->GetAddressByteSize()); 525 Status error; 526 dict_entry->GetData(data, error); 527 if (error.Fail()) return ThreadSP(); 528 529 lldb::offset_t data_offset = 0; 530 auto dict_entry_key = data.GetPointer(&data_offset); 531 auto dict_entry_value = data.GetPointer(&data_offset); 532 533 auto key_nsstring = objc_object_from_address(dict_entry_key, "key"); 534 StreamString key_summary; 535 if (lldb_private::formatters::NSStringSummaryProvider( 536 *key_nsstring, key_summary, TypeSummaryOptions()) && 537 !key_summary.Empty()) { 538 if (key_summary.GetString() == "\"callStackReturnAddresses\"") { 539 return_addresses = objc_object_from_address(dict_entry_value, 540 "callStackReturnAddresses"); 541 break; 542 } 543 } 544 } 545 546 if (!return_addresses) return ThreadSP(); 547 auto frames_value = 548 return_addresses->GetChildMemberWithName(ConstString("_frames"), true); 549 addr_t frames_addr = frames_value->GetValueAsUnsigned(0); 550 auto count_value = 551 return_addresses->GetChildMemberWithName(ConstString("_cnt"), true); 552 size_t count = count_value->GetValueAsUnsigned(0); 553 auto ignore_value = 554 return_addresses->GetChildMemberWithName(ConstString("_ignore"), true); 555 size_t ignore = ignore_value->GetValueAsUnsigned(0); 556 557 size_t ptr_size = m_process->GetAddressByteSize(); 558 std::vector<lldb::addr_t> pcs; 559 for (size_t idx = 0; idx < count; idx++) { 560 Status error; 561 addr_t pc = m_process->ReadPointerFromMemory( 562 frames_addr + (ignore + idx) * ptr_size, error); 563 pcs.push_back(pc); 564 } 565 566 if (pcs.empty()) return ThreadSP(); 567 568 ThreadSP new_thread_sp(new HistoryThread(*m_process, 0, pcs)); 569 m_process->GetExtendedThreadList().AddThread(new_thread_sp); 570 return new_thread_sp; 571} 572 573std::tuple<FileSpec, ConstString> 574AppleObjCRuntime::GetExceptionThrowLocation() { 575 return std::make_tuple( 576 FileSpec("libobjc.A.dylib"), ConstString("objc_exception_throw")); 577} 578 579void AppleObjCRuntime::ReadObjCLibraryIfNeeded(const ModuleList &module_list) { 580 if (!HasReadObjCLibrary()) { 581 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex()); 582 583 size_t num_modules = module_list.GetSize(); 584 for (size_t i = 0; i < num_modules; i++) { 585 auto mod = module_list.GetModuleAtIndex(i); 586 if (IsModuleObjCLibrary(mod)) { 587 ReadObjCLibrary(mod); 588 break; 589 } 590 } 591 } 592} 593 594void AppleObjCRuntime::ModulesDidLoad(const ModuleList &module_list) { 595 ReadObjCLibraryIfNeeded(module_list); 596} 597