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