Path: blob/main/contrib/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleThreadPlanStepThroughObjCTrampoline.cpp
39688 views
//===-- AppleThreadPlanStepThroughObjCTrampoline.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 "AppleThreadPlanStepThroughObjCTrampoline.h"910#include "AppleObjCTrampolineHandler.h"11#include "lldb/Expression/DiagnosticManager.h"12#include "lldb/Expression/FunctionCaller.h"13#include "lldb/Expression/UtilityFunction.h"14#include "lldb/Target/ABI.h"15#include "lldb/Target/ExecutionContext.h"16#include "lldb/Target/Process.h"17#include "lldb/Target/Thread.h"18#include "lldb/Target/ThreadPlanRunToAddress.h"19#include "lldb/Target/ThreadPlanStepOut.h"20#include "lldb/Utility/LLDBLog.h"21#include "lldb/Utility/Log.h"2223#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"2425#include <memory>2627using namespace lldb;28using namespace lldb_private;2930// ThreadPlanStepThroughObjCTrampoline constructor31AppleThreadPlanStepThroughObjCTrampoline::32AppleThreadPlanStepThroughObjCTrampoline(33Thread &thread, AppleObjCTrampolineHandler &trampoline_handler,34ValueList &input_values, lldb::addr_t isa_addr, lldb::addr_t sel_addr,35lldb::addr_t sel_str_addr, llvm::StringRef sel_str)36: ThreadPlan(ThreadPlan::eKindGeneric,37"MacOSX Step through ObjC Trampoline", thread, eVoteNoOpinion,38eVoteNoOpinion),39m_trampoline_handler(trampoline_handler),40m_args_addr(LLDB_INVALID_ADDRESS), m_input_values(input_values),41m_isa_addr(isa_addr), m_sel_addr(sel_addr), m_impl_function(nullptr),42m_sel_str_addr(sel_str_addr), m_sel_str(sel_str) {}4344// Destructor45AppleThreadPlanStepThroughObjCTrampoline::46~AppleThreadPlanStepThroughObjCTrampoline() = default;4748void AppleThreadPlanStepThroughObjCTrampoline::DidPush() {49// Setting up the memory space for the called function text might require50// allocations, i.e. a nested function call. This needs to be done as a51// PreResumeAction.52m_process.AddPreResumeAction(PreResumeInitializeFunctionCaller, (void *)this);53}5455bool AppleThreadPlanStepThroughObjCTrampoline::InitializeFunctionCaller() {56if (!m_func_sp) {57DiagnosticManager diagnostics;58m_args_addr =59m_trampoline_handler.SetupDispatchFunction(GetThread(), m_input_values);6061if (m_args_addr == LLDB_INVALID_ADDRESS) {62return false;63}64m_impl_function =65m_trampoline_handler.GetLookupImplementationFunctionCaller();66ExecutionContext exc_ctx;67EvaluateExpressionOptions options;68options.SetUnwindOnError(true);69options.SetIgnoreBreakpoints(true);70options.SetStopOthers(false);71GetThread().CalculateExecutionContext(exc_ctx);72m_func_sp = m_impl_function->GetThreadPlanToCallFunction(73exc_ctx, m_args_addr, options, diagnostics);74m_func_sp->SetOkayToDiscard(true);75PushPlan(m_func_sp);76}77return true;78}7980bool AppleThreadPlanStepThroughObjCTrampoline::81PreResumeInitializeFunctionCaller(void *void_myself) {82AppleThreadPlanStepThroughObjCTrampoline *myself =83static_cast<AppleThreadPlanStepThroughObjCTrampoline *>(void_myself);84return myself->InitializeFunctionCaller();85}8687void AppleThreadPlanStepThroughObjCTrampoline::GetDescription(88Stream *s, lldb::DescriptionLevel level) {89if (level == lldb::eDescriptionLevelBrief)90s->Printf("Step through ObjC trampoline");91else {92s->Printf("Stepping to implementation of ObjC method - obj: 0x%llx, isa: "93"0x%" PRIx64 ", sel: 0x%" PRIx64,94m_input_values.GetValueAtIndex(0)->GetScalar().ULongLong(),95m_isa_addr, m_sel_addr);96}97}9899bool AppleThreadPlanStepThroughObjCTrampoline::ValidatePlan(Stream *error) {100return true;101}102103bool AppleThreadPlanStepThroughObjCTrampoline::DoPlanExplainsStop(104Event *event_ptr) {105// If we get asked to explain the stop it will be because something went106// wrong (like the implementation for selector function crashed... We're107// going to figure out what to do about that, so we do explain the stop.108return true;109}110111lldb::StateType AppleThreadPlanStepThroughObjCTrampoline::GetPlanRunState() {112return eStateRunning;113}114115bool AppleThreadPlanStepThroughObjCTrampoline::ShouldStop(Event *event_ptr) {116// First stage: we are still handling the "call a function to get the target117// of the dispatch"118if (m_func_sp) {119if (!m_func_sp->IsPlanComplete()) {120return false;121} else {122if (!m_func_sp->PlanSucceeded()) {123SetPlanComplete(false);124return true;125}126m_func_sp.reset();127}128}129130// Second stage, if all went well with the function calling, get the131// implementation function address, and queue up a "run to that address" plan.132Log *log = GetLog(LLDBLog::Step);133134if (!m_run_to_sp) {135Value target_addr_value;136ExecutionContext exc_ctx;137GetThread().CalculateExecutionContext(exc_ctx);138m_impl_function->FetchFunctionResults(exc_ctx, m_args_addr,139target_addr_value);140m_impl_function->DeallocateFunctionResults(exc_ctx, m_args_addr);141lldb::addr_t target_addr = target_addr_value.GetScalar().ULongLong();142143if (ABISP abi_sp = GetThread().GetProcess()->GetABI()) {144target_addr = abi_sp->FixCodeAddress(target_addr);145}146Address target_so_addr;147target_so_addr.SetOpcodeLoadAddress(target_addr, exc_ctx.GetTargetPtr());148if (target_addr == 0) {149LLDB_LOGF(log, "Got target implementation of 0x0, stopping.");150SetPlanComplete();151return true;152}153if (m_trampoline_handler.AddrIsMsgForward(target_addr)) {154LLDB_LOGF(log,155"Implementation lookup returned msgForward function: 0x%" PRIx64156", stopping.",157target_addr);158159SymbolContext sc = GetThread().GetStackFrameAtIndex(0)->GetSymbolContext(160eSymbolContextEverything);161Status status;162const bool abort_other_plans = false;163const bool first_insn = true;164const uint32_t frame_idx = 0;165m_run_to_sp = GetThread().QueueThreadPlanForStepOutNoShouldStop(166abort_other_plans, &sc, first_insn, false, eVoteNoOpinion,167eVoteNoOpinion, frame_idx, status);168if (m_run_to_sp && status.Success())169m_run_to_sp->SetPrivate(true);170return false;171}172173LLDB_LOGF(log, "Running to ObjC method implementation: 0x%" PRIx64,174target_addr);175176ObjCLanguageRuntime *objc_runtime =177ObjCLanguageRuntime::Get(*GetThread().GetProcess());178assert(objc_runtime != nullptr);179if (m_sel_str_addr != LLDB_INVALID_ADDRESS) {180// Cache the string -> implementation and free the string in the target.181Status dealloc_error =182GetThread().GetProcess()->DeallocateMemory(m_sel_str_addr);183// For now just log this:184if (dealloc_error.Fail())185LLDB_LOG(log, "Failed to deallocate the sel str at {0} - error: {1}",186m_sel_str_addr, dealloc_error);187objc_runtime->AddToMethodCache(m_isa_addr, m_sel_str, target_addr);188LLDB_LOG(log,189"Adding \\{isa-addr={0}, sel-addr={1}\\} = addr={2} to cache.",190m_isa_addr, m_sel_str, target_addr);191} else {192objc_runtime->AddToMethodCache(m_isa_addr, m_sel_addr, target_addr);193LLDB_LOGF(log,194"Adding {isa-addr=0x%" PRIx64 ", sel-addr=0x%" PRIx64195"} = addr=0x%" PRIx64 " to cache.",196m_isa_addr, m_sel_addr, target_addr);197}198199m_run_to_sp = std::make_shared<ThreadPlanRunToAddress>(200GetThread(), target_so_addr, false);201PushPlan(m_run_to_sp);202return false;203} else if (GetThread().IsThreadPlanDone(m_run_to_sp.get())) {204// Third stage, work the run to target plan.205SetPlanComplete();206return true;207}208return false;209}210211// The base class MischiefManaged does some cleanup - so you have to call it in212// your MischiefManaged derived class.213bool AppleThreadPlanStepThroughObjCTrampoline::MischiefManaged() {214return IsPlanComplete();215}216217bool AppleThreadPlanStepThroughObjCTrampoline::WillStop() { return true; }218219// Objective-C uses optimized dispatch functions for some common and seldom220// overridden methods. For instance221// [object respondsToSelector:];222// will get compiled to:223// objc_opt_respondsToSelector(object);224// This checks whether the selector has been overridden, directly calling the225// implementation if it hasn't and calling objc_msgSend if it has.226//227// We need to get into the overridden implementation. We'll do that by228// setting a breakpoint on objc_msgSend, and doing a "step out". If we stop229// at objc_msgSend, we can step through to the target of the send, and see if230// that's a place we want to stop.231//232// A couple of complexities. The checking code might call some other method,233// so we might see objc_msgSend more than once. Also, these optimized dispatch234// functions might dispatch more than one message at a time (e.g. alloc followed235// by init.) So we can't give up at the first objc_msgSend.236// That means among other things that we have to handle the "ShouldStopHere" -237// since we can't just return control to the plan that's controlling us on the238// first step.239240AppleThreadPlanStepThroughDirectDispatch ::241AppleThreadPlanStepThroughDirectDispatch(242Thread &thread, AppleObjCTrampolineHandler &handler,243llvm::StringRef dispatch_func_name)244: ThreadPlanStepOut(thread, nullptr, true /* first instruction */, false,245eVoteNoOpinion, eVoteNoOpinion,2460 /* Step out of zeroth frame */,247eLazyBoolNo /* Our parent plan will decide this248when we are done */249,250true /* Run to branch for inline step out */,251false /* Don't gather the return value */),252m_trampoline_handler(handler),253m_dispatch_func_name(std::string(dispatch_func_name)),254m_at_msg_send(false) {255// Set breakpoints on the dispatch functions:256auto bkpt_callback = [&] (lldb::addr_t addr,257const AppleObjCTrampolineHandler258::DispatchFunction &dispatch) {259m_msgSend_bkpts.push_back(GetTarget().CreateBreakpoint(addr,260true /* internal */,261false /* hard */));262m_msgSend_bkpts.back()->SetThreadID(GetThread().GetID());263};264handler.ForEachDispatchFunction(bkpt_callback);265266// We'll set the step-out plan in the DidPush so it gets queued in the right267// order.268269if (GetThread().GetStepInAvoidsNoDebug())270GetFlags().Set(ThreadPlanShouldStopHere::eStepInAvoidNoDebug);271else272GetFlags().Clear(ThreadPlanShouldStopHere::eStepInAvoidNoDebug);273// We only care about step in. Our parent plan will figure out what to274// do when we've stepped out again.275GetFlags().Clear(ThreadPlanShouldStopHere::eStepOutAvoidNoDebug);276}277278AppleThreadPlanStepThroughDirectDispatch::279~AppleThreadPlanStepThroughDirectDispatch() {280for (BreakpointSP bkpt_sp : m_msgSend_bkpts) {281GetTarget().RemoveBreakpointByID(bkpt_sp->GetID());282}283}284285void AppleThreadPlanStepThroughDirectDispatch::GetDescription(286Stream *s, lldb::DescriptionLevel level) {287switch (level) {288case lldb::eDescriptionLevelBrief:289s->PutCString("Step through ObjC direct dispatch function.");290break;291default:292s->Printf("Step through ObjC direct dispatch '%s' using breakpoints: ",293m_dispatch_func_name.c_str());294bool first = true;295for (auto bkpt_sp : m_msgSend_bkpts) {296if (!first) {297s->PutCString(", ");298}299first = false;300s->Printf("%d", bkpt_sp->GetID());301}302(*s) << ".";303break;304}305}306307bool308AppleThreadPlanStepThroughDirectDispatch::DoPlanExplainsStop(Event *event_ptr) {309if (ThreadPlanStepOut::DoPlanExplainsStop(event_ptr))310return true;311312StopInfoSP stop_info_sp = GetPrivateStopInfo();313314// Check if the breakpoint is one of ours msgSend dispatch breakpoints.315316StopReason stop_reason = eStopReasonNone;317if (stop_info_sp)318stop_reason = stop_info_sp->GetStopReason();319320// See if this is one of our msgSend breakpoints:321if (stop_reason == eStopReasonBreakpoint) {322ProcessSP process_sp = GetThread().GetProcess();323uint64_t break_site_id = stop_info_sp->GetValue();324BreakpointSiteSP site_sp325= process_sp->GetBreakpointSiteList().FindByID(break_site_id);326// Some other plan might have deleted the site's last owner before this327// got to us. In which case, it wasn't our breakpoint...328if (!site_sp)329return false;330331for (BreakpointSP break_sp : m_msgSend_bkpts) {332if (site_sp->IsBreakpointAtThisSite(break_sp->GetID())) {333// If we aren't the only one with a breakpoint on this site, then we334// should just stop and return control to the user.335if (site_sp->GetNumberOfConstituents() > 1) {336SetPlanComplete(true);337return false;338}339m_at_msg_send = true;340return true;341}342}343}344345// We're done here. If one of our sub-plans explained the stop, they346// would have already answered true to PlanExplainsStop, and if they were347// done, we'll get called to figure out what to do in ShouldStop...348return false;349}350351bool AppleThreadPlanStepThroughDirectDispatch352::DoWillResume(lldb::StateType resume_state, bool current_plan) {353ThreadPlanStepOut::DoWillResume(resume_state, current_plan);354m_at_msg_send = false;355return true;356}357358bool AppleThreadPlanStepThroughDirectDispatch::ShouldStop(Event *event_ptr) {359// If step out plan finished, that means we didn't find our way into a method360// implementation. Either we went directly to the default implementation,361// of the overridden implementation didn't have debug info.362// So we should mark ourselves as done.363const bool step_out_should_stop = ThreadPlanStepOut::ShouldStop(event_ptr);364if (step_out_should_stop) {365SetPlanComplete(true);366return true;367}368369// If we have a step through plan, then w're in the process of getting370// through an ObjC msgSend. If we arrived at the target function, then371// check whether we have debug info, and if we do, stop.372Log *log = GetLog(LLDBLog::Step);373374if (m_objc_step_through_sp && m_objc_step_through_sp->IsPlanComplete()) {375// If the plan failed for some reason, we should probably just let the376// step over plan get us out of here... We don't need to do anything about377// the step through plan, it is done and will get popped when we continue.378if (!m_objc_step_through_sp->PlanSucceeded()) {379LLDB_LOGF(log, "ObjC Step through plan failed. Stepping out.");380}381Status error;382if (InvokeShouldStopHereCallback(eFrameCompareYounger, error)) {383SetPlanComplete(true);384return true;385}386// If we didn't want to stop at this msgSend, there might be another so387// we should just continue on with the step out and see if our breakpoint388// triggers again.389m_objc_step_through_sp.reset();390for (BreakpointSP bkpt_sp : m_msgSend_bkpts) {391bkpt_sp->SetEnabled(true);392}393return false;394}395396// If we hit an msgSend breakpoint, then we should queue the step through397// plan:398399if (m_at_msg_send) {400LanguageRuntime *objc_runtime401= GetThread().GetProcess()->GetLanguageRuntime(eLanguageTypeObjC);402// There's no way we could have gotten here without an ObjC language403// runtime.404assert(objc_runtime);405m_objc_step_through_sp =406objc_runtime->GetStepThroughTrampolinePlan(GetThread(), false);407// If we failed to find the target for this dispatch, just keep going and408// let the step out complete.409if (!m_objc_step_through_sp) {410LLDB_LOG(log, "Couldn't find target for message dispatch, continuing.");411return false;412}413// Otherwise push the step through plan and continue.414GetThread().QueueThreadPlan(m_objc_step_through_sp, false);415for (BreakpointSP bkpt_sp : m_msgSend_bkpts) {416bkpt_sp->SetEnabled(false);417}418return false;419}420return true;421}422423bool AppleThreadPlanStepThroughDirectDispatch::MischiefManaged() {424if (IsPlanComplete())425return true;426return ThreadPlanStepOut::MischiefManaged();427}428429430