Path: blob/main/contrib/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.cpp
39690 views
//===-- AppleObjCRuntime.cpp ----------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "AppleObjCRuntime.h"9#include "AppleObjCRuntimeV1.h"10#include "AppleObjCRuntimeV2.h"11#include "AppleObjCTrampolineHandler.h"12#include "Plugins/Language/ObjC/NSString.h"13#include "Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h"14#include "Plugins/Process/Utility/HistoryThread.h"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/ObjectFile.h"26#include "lldb/Target/ExecutionContext.h"27#include "lldb/Target/Process.h"28#include "lldb/Target/RegisterContext.h"29#include "lldb/Target/StopInfo.h"30#include "lldb/Target/Target.h"31#include "lldb/Target/Thread.h"32#include "lldb/Utility/ConstString.h"33#include "lldb/Utility/ErrorMessages.h"34#include "lldb/Utility/LLDBLog.h"35#include "lldb/Utility/Log.h"36#include "lldb/Utility/Scalar.h"37#include "lldb/Utility/Status.h"38#include "lldb/Utility/StreamString.h"39#include "clang/AST/Type.h"4041#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"4243#include <vector>4445using namespace lldb;46using namespace lldb_private;4748LLDB_PLUGIN_DEFINE(AppleObjCRuntime)4950char AppleObjCRuntime::ID = 0;5152AppleObjCRuntime::~AppleObjCRuntime() = default;5354AppleObjCRuntime::AppleObjCRuntime(Process *process)55: ObjCLanguageRuntime(process), m_read_objc_library(false),56m_objc_trampoline_handler_up(), m_Foundation_major() {57ReadObjCLibraryIfNeeded(process->GetTarget().GetImages());58}5960void AppleObjCRuntime::Initialize() {61AppleObjCRuntimeV2::Initialize();62AppleObjCRuntimeV1::Initialize();63}6465void AppleObjCRuntime::Terminate() {66AppleObjCRuntimeV2::Terminate();67AppleObjCRuntimeV1::Terminate();68}6970llvm::Error AppleObjCRuntime::GetObjectDescription(Stream &str,71ValueObject &valobj) {72CompilerType compiler_type(valobj.GetCompilerType());73bool is_signed;74// ObjC objects can only be pointers (or numbers that actually represents75// pointers but haven't been typecast, because reasons..)76if (!compiler_type.IsIntegerType(is_signed) && !compiler_type.IsPointerType())77return llvm::createStringError("not a pointer type");7879// Make the argument list: we pass one arg, the address of our pointer, to80// the print function.81Value val;8283if (!valobj.ResolveValue(val.GetScalar()))84return llvm::createStringError("pointer value could not be resolved");8586// Value Objects may not have a process in their ExecutionContextRef. But we87// need to have one in the ref we pass down to eventually call description.88// Get it from the target if it isn't present.89ExecutionContext exe_ctx;90if (valobj.GetProcessSP()) {91exe_ctx = ExecutionContext(valobj.GetExecutionContextRef());92} else {93exe_ctx.SetContext(valobj.GetTargetSP(), true);94if (!exe_ctx.HasProcessScope())95return llvm::createStringError("no process");96}97return GetObjectDescription(str, val, exe_ctx.GetBestExecutionContextScope());98}99100llvm::Error101AppleObjCRuntime::GetObjectDescription(Stream &strm, Value &value,102ExecutionContextScope *exe_scope) {103if (!m_read_objc_library)104return llvm::createStringError("Objective-C runtime not loaded");105106ExecutionContext exe_ctx;107exe_scope->CalculateExecutionContext(exe_ctx);108Process *process = exe_ctx.GetProcessPtr();109if (!process)110return llvm::createStringError("no process");111112// We need other parts of the exe_ctx, but the processes have to match.113assert(m_process == process);114115// Get the function address for the print function.116const Address *function_address = GetPrintForDebuggerAddr();117if (!function_address)118return llvm::createStringError("no print function");119120Target *target = exe_ctx.GetTargetPtr();121CompilerType compiler_type = value.GetCompilerType();122if (compiler_type) {123if (!TypeSystemClang::IsObjCObjectPointerType(compiler_type))124return llvm::createStringError(125"Value doesn't point to an ObjC object.\n");126} else {127// If it is not a pointer, see if we can make it into a pointer.128TypeSystemClangSP scratch_ts_sp =129ScratchTypeSystemClang::GetForTarget(*target);130if (!scratch_ts_sp)131return llvm::createStringError("no scratch type system");132133CompilerType opaque_type = scratch_ts_sp->GetBasicType(eBasicTypeObjCID);134if (!opaque_type)135opaque_type =136scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();137// value.SetContext(Value::eContextTypeClangType, opaque_type_ptr);138value.SetCompilerType(opaque_type);139}140141ValueList arg_value_list;142arg_value_list.PushValue(value);143144// This is the return value:145TypeSystemClangSP scratch_ts_sp =146ScratchTypeSystemClang::GetForTarget(*target);147if (!scratch_ts_sp)148return llvm::createStringError("no scratch type system");149150CompilerType return_compiler_type = scratch_ts_sp->GetCStringType(true);151Value ret;152// ret.SetContext(Value::eContextTypeClangType, return_compiler_type);153ret.SetCompilerType(return_compiler_type);154155if (!exe_ctx.GetFramePtr()) {156Thread *thread = exe_ctx.GetThreadPtr();157if (thread == nullptr) {158exe_ctx.SetThreadSP(process->GetThreadList().GetSelectedThread());159thread = exe_ctx.GetThreadPtr();160}161if (thread) {162exe_ctx.SetFrameSP(thread->GetSelectedFrame(DoNoSelectMostRelevantFrame));163}164}165166// Now we're ready to call the function:167168DiagnosticManager diagnostics;169lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS;170171if (!m_print_object_caller_up) {172Status error;173m_print_object_caller_up.reset(174exe_scope->CalculateTarget()->GetFunctionCallerForLanguage(175eLanguageTypeObjC, return_compiler_type, *function_address,176arg_value_list, "objc-object-description", error));177if (error.Fail()) {178m_print_object_caller_up.reset();179return llvm::createStringError(180llvm::Twine(181"could not get function runner to call print for debugger "182"function: ") +183error.AsCString());184}185m_print_object_caller_up->InsertFunction(exe_ctx, wrapper_struct_addr,186diagnostics);187} else {188m_print_object_caller_up->WriteFunctionArguments(189exe_ctx, wrapper_struct_addr, arg_value_list, diagnostics);190}191192EvaluateExpressionOptions options;193options.SetUnwindOnError(true);194options.SetTryAllThreads(true);195options.SetStopOthers(true);196options.SetIgnoreBreakpoints(true);197options.SetTimeout(process->GetUtilityExpressionTimeout());198options.SetIsForUtilityExpr(true);199200ExpressionResults results = m_print_object_caller_up->ExecuteFunction(201exe_ctx, &wrapper_struct_addr, options, diagnostics, ret);202if (results != eExpressionCompleted)203return llvm::createStringError(204"could not evaluate print object function: " + toString(results));205206addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);207208char buf[512];209size_t cstr_len = 0;210size_t full_buffer_len = sizeof(buf) - 1;211size_t curr_len = full_buffer_len;212while (curr_len == full_buffer_len) {213Status error;214curr_len = process->ReadCStringFromMemory(result_ptr + cstr_len, buf,215sizeof(buf), error);216strm.Write(buf, curr_len);217cstr_len += curr_len;218}219if (cstr_len > 0)220return llvm::Error::success();221return llvm::createStringError("empty object description");222}223224lldb::ModuleSP AppleObjCRuntime::GetObjCModule() {225ModuleSP module_sp(m_objc_module_wp.lock());226if (module_sp)227return module_sp;228229Process *process = GetProcess();230if (process) {231const ModuleList &modules = process->GetTarget().GetImages();232for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {233module_sp = modules.GetModuleAtIndex(idx);234if (AppleObjCRuntime::AppleIsModuleObjCLibrary(module_sp)) {235m_objc_module_wp = module_sp;236return module_sp;237}238}239}240return ModuleSP();241}242243Address *AppleObjCRuntime::GetPrintForDebuggerAddr() {244if (!m_PrintForDebugger_addr) {245const ModuleList &modules = m_process->GetTarget().GetImages();246247SymbolContextList contexts;248SymbolContext context;249250modules.FindSymbolsWithNameAndType(ConstString("_NSPrintForDebugger"),251eSymbolTypeCode, contexts);252if (contexts.IsEmpty()) {253modules.FindSymbolsWithNameAndType(ConstString("_CFPrintForDebugger"),254eSymbolTypeCode, contexts);255if (contexts.IsEmpty())256return nullptr;257}258259contexts.GetContextAtIndex(0, context);260261m_PrintForDebugger_addr =262std::make_unique<Address>(context.symbol->GetAddress());263}264265return m_PrintForDebugger_addr.get();266}267268bool AppleObjCRuntime::CouldHaveDynamicValue(ValueObject &in_value) {269return in_value.GetCompilerType().IsPossibleDynamicType(270nullptr,271false, // do not check C++272true); // check ObjC273}274275bool AppleObjCRuntime::GetDynamicTypeAndAddress(276ValueObject &in_value, lldb::DynamicValueType use_dynamic,277TypeAndOrName &class_type_or_name, Address &address,278Value::ValueType &value_type) {279return false;280}281282TypeAndOrName283AppleObjCRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,284ValueObject &static_value) {285CompilerType static_type(static_value.GetCompilerType());286Flags static_type_flags(static_type.GetTypeInfo());287288TypeAndOrName ret(type_and_or_name);289if (type_and_or_name.HasType()) {290// The type will always be the type of the dynamic object. If our parent's291// type was a pointer, then our type should be a pointer to the type of the292// dynamic object. If a reference, then the original type should be293// okay...294CompilerType orig_type = type_and_or_name.GetCompilerType();295CompilerType corrected_type = orig_type;296if (static_type_flags.AllSet(eTypeIsPointer))297corrected_type = orig_type.GetPointerType();298ret.SetCompilerType(corrected_type);299} else {300// If we are here we need to adjust our dynamic type name to include the301// correct & or * symbol302std::string corrected_name(type_and_or_name.GetName().GetCString());303if (static_type_flags.AllSet(eTypeIsPointer))304corrected_name.append(" *");305// the parent type should be a correctly pointer'ed or referenc'ed type306ret.SetCompilerType(static_type);307ret.SetName(corrected_name.c_str());308}309return ret;310}311312bool AppleObjCRuntime::AppleIsModuleObjCLibrary(const ModuleSP &module_sp) {313if (module_sp) {314const FileSpec &module_file_spec = module_sp->GetFileSpec();315static ConstString ObjCName("libobjc.A.dylib");316317if (module_file_spec) {318if (module_file_spec.GetFilename() == ObjCName)319return true;320}321}322return false;323}324325// we use the version of Foundation to make assumptions about the ObjC runtime326// on a target327uint32_t AppleObjCRuntime::GetFoundationVersion() {328if (!m_Foundation_major) {329const ModuleList &modules = m_process->GetTarget().GetImages();330for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {331lldb::ModuleSP module_sp = modules.GetModuleAtIndex(idx);332if (!module_sp)333continue;334if (strcmp(module_sp->GetFileSpec().GetFilename().AsCString(""),335"Foundation") == 0) {336m_Foundation_major = module_sp->GetVersion().getMajor();337return *m_Foundation_major;338}339}340return LLDB_INVALID_MODULE_VERSION;341} else342return *m_Foundation_major;343}344345void AppleObjCRuntime::GetValuesForGlobalCFBooleans(lldb::addr_t &cf_true,346lldb::addr_t &cf_false) {347cf_true = cf_false = LLDB_INVALID_ADDRESS;348}349350bool AppleObjCRuntime::IsModuleObjCLibrary(const ModuleSP &module_sp) {351return AppleIsModuleObjCLibrary(module_sp);352}353354bool AppleObjCRuntime::ReadObjCLibrary(const ModuleSP &module_sp) {355// Maybe check here and if we have a handler already, and the UUID of this356// module is the same as the one in the current module, then we don't have to357// reread it?358m_objc_trampoline_handler_up = std::make_unique<AppleObjCTrampolineHandler>(359m_process->shared_from_this(), module_sp);360if (m_objc_trampoline_handler_up != nullptr) {361m_read_objc_library = true;362return true;363} else364return false;365}366367ThreadPlanSP AppleObjCRuntime::GetStepThroughTrampolinePlan(Thread &thread,368bool stop_others) {369ThreadPlanSP thread_plan_sp;370if (m_objc_trampoline_handler_up)371thread_plan_sp = m_objc_trampoline_handler_up->GetStepThroughDispatchPlan(372thread, stop_others);373return thread_plan_sp;374}375376// Static Functions377ObjCLanguageRuntime::ObjCRuntimeVersions378AppleObjCRuntime::GetObjCVersion(Process *process, ModuleSP &objc_module_sp) {379if (!process)380return ObjCRuntimeVersions::eObjC_VersionUnknown;381382Target &target = process->GetTarget();383if (target.GetArchitecture().GetTriple().getVendor() !=384llvm::Triple::VendorType::Apple)385return ObjCRuntimeVersions::eObjC_VersionUnknown;386387for (ModuleSP module_sp : target.GetImages().Modules()) {388// One tricky bit here is that we might get called as part of the initial389// module loading, but before all the pre-run libraries get winnowed from390// the module list. So there might actually be an old and incorrect ObjC391// library sitting around in the list, and we don't want to look at that.392// That's why we call IsLoadedInTarget.393394if (AppleIsModuleObjCLibrary(module_sp) &&395module_sp->IsLoadedInTarget(&target)) {396objc_module_sp = module_sp;397ObjectFile *ofile = module_sp->GetObjectFile();398if (!ofile)399return ObjCRuntimeVersions::eObjC_VersionUnknown;400401SectionList *sections = module_sp->GetSectionList();402if (!sections)403return ObjCRuntimeVersions::eObjC_VersionUnknown;404SectionSP v1_telltale_section_sp =405sections->FindSectionByName(ConstString("__OBJC"));406if (v1_telltale_section_sp) {407return ObjCRuntimeVersions::eAppleObjC_V1;408}409return ObjCRuntimeVersions::eAppleObjC_V2;410}411}412413return ObjCRuntimeVersions::eObjC_VersionUnknown;414}415416void AppleObjCRuntime::SetExceptionBreakpoints() {417const bool catch_bp = false;418const bool throw_bp = true;419const bool is_internal = true;420421if (!m_objc_exception_bp_sp) {422m_objc_exception_bp_sp = LanguageRuntime::CreateExceptionBreakpoint(423m_process->GetTarget(), GetLanguageType(), catch_bp, throw_bp,424is_internal);425if (m_objc_exception_bp_sp)426m_objc_exception_bp_sp->SetBreakpointKind("ObjC exception");427} else428m_objc_exception_bp_sp->SetEnabled(true);429}430431void AppleObjCRuntime::ClearExceptionBreakpoints() {432if (!m_process)433return;434435if (m_objc_exception_bp_sp.get()) {436m_objc_exception_bp_sp->SetEnabled(false);437}438}439440bool AppleObjCRuntime::ExceptionBreakpointsAreSet() {441return m_objc_exception_bp_sp && m_objc_exception_bp_sp->IsEnabled();442}443444bool AppleObjCRuntime::ExceptionBreakpointsExplainStop(445lldb::StopInfoSP stop_reason) {446if (!m_process)447return false;448449if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint)450return false;451452uint64_t break_site_id = stop_reason->GetValue();453return m_process->GetBreakpointSiteList().StopPointSiteContainsBreakpoint(454break_site_id, m_objc_exception_bp_sp->GetID());455}456457bool AppleObjCRuntime::CalculateHasNewLiteralsAndIndexing() {458if (!m_process)459return false;460461Target &target(m_process->GetTarget());462463static ConstString s_method_signature(464"-[NSDictionary objectForKeyedSubscript:]");465static ConstString s_arclite_method_signature(466"__arclite_objectForKeyedSubscript");467468SymbolContextList sc_list;469470target.GetImages().FindSymbolsWithNameAndType(s_method_signature,471eSymbolTypeCode, sc_list);472if (sc_list.IsEmpty())473target.GetImages().FindSymbolsWithNameAndType(s_arclite_method_signature,474eSymbolTypeCode, sc_list);475return !sc_list.IsEmpty();476}477478lldb::SearchFilterSP AppleObjCRuntime::CreateExceptionSearchFilter() {479Target &target = m_process->GetTarget();480481FileSpecList filter_modules;482if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) {483filter_modules.Append(std::get<0>(GetExceptionThrowLocation()));484}485return target.GetSearchFilterForModuleList(&filter_modules);486}487488ValueObjectSP AppleObjCRuntime::GetExceptionObjectForThread(489ThreadSP thread_sp) {490auto *cpp_runtime = m_process->GetLanguageRuntime(eLanguageTypeC_plus_plus);491if (!cpp_runtime) return ValueObjectSP();492auto cpp_exception = cpp_runtime->GetExceptionObjectForThread(thread_sp);493if (!cpp_exception) return ValueObjectSP();494495auto descriptor = GetClassDescriptor(*cpp_exception);496if (!descriptor || !descriptor->IsValid()) return ValueObjectSP();497498while (descriptor) {499ConstString class_name(descriptor->GetClassName());500if (class_name == "NSException")501return cpp_exception;502descriptor = descriptor->GetSuperclass();503}504505return ValueObjectSP();506}507508/// Utility method for error handling in GetBacktraceThreadFromException.509/// \param msg The message to add to the log.510/// \return An invalid ThreadSP to be returned from511/// GetBacktraceThreadFromException.512[[nodiscard]]513static ThreadSP FailExceptionParsing(llvm::StringRef msg) {514Log *log = GetLog(LLDBLog::Language);515LLDB_LOG(log, "Failed getting backtrace from exception: {0}", msg);516return ThreadSP();517}518519ThreadSP AppleObjCRuntime::GetBacktraceThreadFromException(520lldb::ValueObjectSP exception_sp) {521ValueObjectSP reserved_dict =522exception_sp->GetChildMemberWithName("reserved");523if (!reserved_dict)524return FailExceptionParsing("Failed to get 'reserved' member.");525526reserved_dict = reserved_dict->GetSyntheticValue();527if (!reserved_dict)528return FailExceptionParsing("Failed to get synthetic value.");529530TypeSystemClangSP scratch_ts_sp =531ScratchTypeSystemClang::GetForTarget(*exception_sp->GetTargetSP());532if (!scratch_ts_sp)533return FailExceptionParsing("Failed to get scratch AST.");534CompilerType objc_id = scratch_ts_sp->GetBasicType(lldb::eBasicTypeObjCID);535ValueObjectSP return_addresses;536537auto objc_object_from_address = [&exception_sp, &objc_id](uint64_t addr,538const char *name) {539Value value(addr);540value.SetCompilerType(objc_id);541auto object = ValueObjectConstResult::Create(542exception_sp->GetTargetSP().get(), value, ConstString(name));543object = object->GetDynamicValue(eDynamicDontRunTarget);544return object;545};546547for (size_t idx = 0; idx < reserved_dict->GetNumChildrenIgnoringErrors();548idx++) {549ValueObjectSP dict_entry = reserved_dict->GetChildAtIndex(idx);550551DataExtractor data;552data.SetAddressByteSize(dict_entry->GetProcessSP()->GetAddressByteSize());553Status error;554dict_entry->GetData(data, error);555if (error.Fail()) return ThreadSP();556557lldb::offset_t data_offset = 0;558auto dict_entry_key = data.GetAddress(&data_offset);559auto dict_entry_value = data.GetAddress(&data_offset);560561auto key_nsstring = objc_object_from_address(dict_entry_key, "key");562StreamString key_summary;563if (lldb_private::formatters::NSStringSummaryProvider(564*key_nsstring, key_summary, TypeSummaryOptions()) &&565!key_summary.Empty()) {566if (key_summary.GetString() == "\"callStackReturnAddresses\"") {567return_addresses = objc_object_from_address(dict_entry_value,568"callStackReturnAddresses");569break;570}571}572}573574if (!return_addresses)575return FailExceptionParsing("Failed to get return addresses.");576auto frames_value = return_addresses->GetChildMemberWithName("_frames");577if (!frames_value)578return FailExceptionParsing("Failed to get frames_value.");579addr_t frames_addr = frames_value->GetValueAsUnsigned(0);580auto count_value = return_addresses->GetChildMemberWithName("_cnt");581if (!count_value)582return FailExceptionParsing("Failed to get count_value.");583size_t count = count_value->GetValueAsUnsigned(0);584auto ignore_value = return_addresses->GetChildMemberWithName("_ignore");585if (!ignore_value)586return FailExceptionParsing("Failed to get ignore_value.");587size_t ignore = ignore_value->GetValueAsUnsigned(0);588589size_t ptr_size = m_process->GetAddressByteSize();590std::vector<lldb::addr_t> pcs;591for (size_t idx = 0; idx < count; idx++) {592Status error;593addr_t pc = m_process->ReadPointerFromMemory(594frames_addr + (ignore + idx) * ptr_size, error);595pcs.push_back(pc);596}597598if (pcs.empty())599return FailExceptionParsing("Failed to get PC list.");600601ThreadSP new_thread_sp(new HistoryThread(*m_process, 0, pcs));602m_process->GetExtendedThreadList().AddThread(new_thread_sp);603return new_thread_sp;604}605606std::tuple<FileSpec, ConstString>607AppleObjCRuntime::GetExceptionThrowLocation() {608return std::make_tuple(609FileSpec("libobjc.A.dylib"), ConstString("objc_exception_throw"));610}611612void AppleObjCRuntime::ReadObjCLibraryIfNeeded(const ModuleList &module_list) {613if (!HasReadObjCLibrary()) {614std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());615616size_t num_modules = module_list.GetSize();617for (size_t i = 0; i < num_modules; i++) {618auto mod = module_list.GetModuleAtIndex(i);619if (IsModuleObjCLibrary(mod)) {620ReadObjCLibrary(mod);621break;622}623}624}625}626627void AppleObjCRuntime::ModulesDidLoad(const ModuleList &module_list) {628ReadObjCLibraryIfNeeded(module_list);629}630631632