LLDB mainline
AppleThreadPlanStepThroughObjCTrampoline.cpp
Go to the documentation of this file.
1//===-- AppleThreadPlanStepThroughObjCTrampoline.cpp-----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
15#include "lldb/Target/ABI.h"
17#include "lldb/Target/Process.h"
18#include "lldb/Target/Thread.h"
22#include "lldb/Utility/Log.h"
23
25
26#include <memory>
27
28using namespace lldb;
29using namespace lldb_private;
30
31// ThreadPlanStepThroughObjCTrampoline constructor
34 Thread &thread, AppleObjCTrampolineHandler &trampoline_handler,
35 ValueList &input_values, lldb::addr_t isa_addr, lldb::addr_t sel_addr,
36 lldb::addr_t sel_str_addr, llvm::StringRef sel_str)
38 "MacOSX Step through ObjC Trampoline", thread, eVoteNoOpinion,
40 m_trampoline_handler(trampoline_handler),
42 m_isa_addr(isa_addr), m_sel_addr(sel_addr), m_impl_function(nullptr),
43 m_sel_str_addr(sel_str_addr), m_sel_str(sel_str) {}
44
45// Destructor
48
50 // Setting up the memory space for the called function text might require
51 // allocations, i.e. a nested function call. This needs to be done as a
52 // PreResumeAction.
53 m_process.AddPreResumeAction(PreResumeInitializeFunctionCaller, (void *)this);
54}
55
57 if (!m_func_sp) {
58 DiagnosticManager diagnostics;
60 m_trampoline_handler.SetupDispatchFunction(GetThread(), m_input_values);
61
63 return false;
64 }
66 m_trampoline_handler.GetLookupImplementationFunctionCaller();
67 ExecutionContext exc_ctx;
69 options.SetUnwindOnError(true);
70 options.SetIgnoreBreakpoints(true);
71 options.SetStopOthers(false);
73 m_func_sp = m_impl_function->GetThreadPlanToCallFunction(
74 exc_ctx, m_args_addr, options, diagnostics);
75 m_func_sp->SetOkayToDiscard(true);
77 }
78 return true;
79}
80
87
91 s->Printf("Step through ObjC trampoline");
92 else {
93 s->Printf("Stepping to implementation of ObjC method - obj: 0x%llx, isa: "
94 "0x%" PRIx64 ", sel: 0x%" PRIx64,
95 m_input_values.GetValueAtIndex(0)->GetScalar().ULongLong(),
97 }
98}
99
103
105 Event *event_ptr) {
106 // If we get asked to explain the stop it will be because something went
107 // wrong (like the implementation for selector function crashed... We're
108 // going to figure out what to do about that, so we do explain the stop.
109 return true;
110}
111
115
117 // First stage: we are still handling the "call a function to get the target
118 // of the dispatch"
119 if (m_func_sp) {
120 if (!m_func_sp->IsPlanComplete()) {
121 return false;
122 } else {
123 if (!m_func_sp->PlanSucceeded()) {
124 SetPlanComplete(false);
125 return true;
126 }
127 m_func_sp.reset();
128 }
129 }
130
131 // Second stage, if all went well with the function calling, get the
132 // implementation function address, and queue up a "run to that address" plan.
133 Log *log = GetLog(LLDBLog::Step);
134
135 if (!m_run_to_sp) {
136 Value target_addr_value;
137 ExecutionContext exc_ctx;
139 m_impl_function->FetchFunctionResults(exc_ctx, m_args_addr,
140 target_addr_value);
141 m_impl_function->DeallocateFunctionResults(exc_ctx, m_args_addr);
142 lldb::addr_t target_addr = target_addr_value.GetScalar().ULongLong();
143
144 if (ABISP abi_sp = GetThread().GetProcess()->GetABI()) {
145 target_addr = abi_sp->FixCodeAddress(target_addr);
146 }
147 Address target_so_addr;
148 target_so_addr.SetOpcodeLoadAddress(target_addr, exc_ctx.GetTargetPtr());
149 if (target_addr == 0) {
150 LLDB_LOGF(log, "Got target implementation of 0x0, stopping.");
152 return true;
153 }
154 if (m_trampoline_handler.AddrIsMsgForward(target_addr)) {
155 LLDB_LOGF(log,
156 "Implementation lookup returned msgForward function: 0x%" PRIx64
157 ", stopping.",
158 target_addr);
159
160 SymbolContext sc = GetThread().GetStackFrameAtIndex(0)->GetSymbolContext(
161 eSymbolContextEverything);
162 Status status;
163 const bool abort_other_plans = false;
164 const bool first_insn = true;
165 const uint32_t frame_idx = 0;
167 abort_other_plans, &sc, first_insn, false, eVoteNoOpinion,
168 eVoteNoOpinion, frame_idx, status);
169 if (m_run_to_sp && status.Success())
170 m_run_to_sp->SetPrivate(true);
171 return false;
172 }
173
174 LLDB_LOGF(log, "Running to ObjC method implementation: 0x%" PRIx64,
175 target_addr);
176
177 ObjCLanguageRuntime *objc_runtime =
178 ObjCLanguageRuntime::Get(*GetThread().GetProcess());
179 assert(objc_runtime != nullptr);
181 // Cache the string -> implementation and free the string in the target.
182 Status dealloc_error =
183 GetThread().GetProcess()->DeallocateMemory(m_sel_str_addr);
184 // For now just log this:
185 if (dealloc_error.Fail())
186 LLDB_LOG(log, "Failed to deallocate the sel str at {0} - error: {1}",
187 m_sel_str_addr, dealloc_error);
188 objc_runtime->AddToMethodCache(m_isa_addr, m_sel_str, target_addr);
189 LLDB_LOG(log, "Adding {{isa-addr={}, sel-addr={}}} = addr={} to cache.",
190 m_isa_addr, m_sel_str, target_addr);
191 } else {
192 objc_runtime->AddToMethodCache(m_isa_addr, m_sel_addr, target_addr);
193 LLDB_LOGF(log,
194 "Adding {isa-addr=0x%" PRIx64 ", sel-addr=0x%" PRIx64
195 "} = addr=0x%" PRIx64 " to cache.",
196 m_isa_addr, m_sel_addr, target_addr);
197 }
198
199 m_run_to_sp = std::make_shared<ThreadPlanRunToAddress>(
200 GetThread(), target_so_addr, false);
202 return false;
203 } else if (GetThread().IsThreadPlanDone(m_run_to_sp.get())) {
204 // Third stage, work the run to target plan.
206 return true;
207 }
208 return false;
209}
210
211// The base class MischiefManaged does some cleanup - so you have to call it in
212// your MischiefManaged derived class.
216
218
219// Objective-C uses optimized dispatch functions for some common and seldom
220// overridden methods. For instance
221// [object respondsToSelector:];
222// will get compiled to:
223// objc_opt_respondsToSelector(object);
224// This checks whether the selector has been overridden, directly calling the
225// 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 by
228// setting a breakpoint on objc_msgSend, and doing a "step out". If we stop
229// at objc_msgSend, we can step through to the target of the send, and see if
230// 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 dispatch
234// functions might dispatch more than one message at a time (e.g. alloc followed
235// 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 the
238// first step.
239
240AppleThreadPlanStepThroughDirectDispatch ::
241 AppleThreadPlanStepThroughDirectDispatch(
242 Thread &thread, AppleObjCTrampolineHandler &handler)
243 : ThreadPlanStepOut(thread, nullptr, true /* first instruction */, false,
245 0 /* Step out of zeroth frame */,
246 eLazyBoolNo /* Our parent plan will decide this
247 when we are done */
248 ,
249 true /* Run to branch for inline step out */,
250 false /* Don't gather the return value */),
251 m_trampoline_handler(handler), m_at_msg_send(false) {
252 // Set breakpoints on the dispatch functions:
253 auto bkpt_callback = [&] (lldb::addr_t addr,
254 const AppleObjCTrampolineHandler
255 ::DispatchFunction &dispatch) {
256 m_msgSend_bkpts.push_back(GetTarget().CreateBreakpoint(addr,
257 true /* internal */,
258 false /* hard */));
259 m_msgSend_bkpts.back()->SetThreadID(GetThread().GetID());
260 };
261 handler.ForEachDispatchFunction(bkpt_callback);
262
263 // We'll set the step-out plan in the DidPush so it gets queued in the right
264 // order.
265
266 if (GetThread().GetStepInAvoidsNoDebug())
268 else
270 // We only care about step in. Our parent plan will figure out what to
271 // do when we've stepped out again.
273}
274
281
283 Stream *s, lldb::DescriptionLevel level) {
284 switch (level) {
286 s->PutCString("Step through ObjC direct dispatch function.");
287 break;
288 default:
289 s->Printf("Step through ObjC direct dispatch using breakpoints: ");
290 bool first = true;
291 for (auto bkpt_sp : m_msgSend_bkpts) {
292 if (!first) {
293 s->PutCString(", ");
294 }
295 first = false;
296 s->Printf("%d", bkpt_sp->GetID());
297 }
298 (*s) << ".";
299 break;
300 }
301}
302
303bool
306 return true;
307
308 StopInfoSP stop_info_sp = GetPrivateStopInfo();
309
310 // Check if the breakpoint is one of ours msgSend dispatch breakpoints.
311
312 StopReason stop_reason = eStopReasonNone;
313 if (stop_info_sp)
314 stop_reason = stop_info_sp->GetStopReason();
315
316 // See if this is one of our msgSend breakpoints:
317 if (stop_reason == eStopReasonBreakpoint) {
318 ProcessSP process_sp = GetThread().GetProcess();
319 uint64_t break_site_id = stop_info_sp->GetValue();
320 BreakpointSiteSP site_sp
321 = process_sp->GetBreakpointSiteList().FindByID(break_site_id);
322 // Some other plan might have deleted the site's last owner before this
323 // got to us. In which case, it wasn't our breakpoint...
324 if (!site_sp)
325 return false;
326
327 for (BreakpointSP break_sp : m_msgSend_bkpts) {
328 if (site_sp->IsBreakpointAtThisSite(break_sp->GetID())) {
329 // If we aren't the only one with a breakpoint on this site, then we
330 // should just stop and return control to the user.
331 if (site_sp->GetNumberOfConstituents() > 1) {
332 SetPlanComplete(true);
333 return false;
334 }
335 m_at_msg_send = true;
336 return true;
337 }
338 }
339 }
340
341 // We're done here. If one of our sub-plans explained the stop, they
342 // would have already answered true to PlanExplainsStop, and if they were
343 // done, we'll get called to figure out what to do in ShouldStop...
344 return false;
345}
346
347bool AppleThreadPlanStepThroughDirectDispatch
348 ::DoWillResume(lldb::StateType resume_state, bool current_plan) {
349 ThreadPlanStepOut::DoWillResume(resume_state, current_plan);
350 m_at_msg_send = false;
351 return true;
352}
353
355 // If step out plan finished, that means we didn't find our way into a method
356 // implementation. Either we went directly to the default implementation,
357 // of the overridden implementation didn't have debug info.
358 // So we should mark ourselves as done.
359 const bool step_out_should_stop = ThreadPlanStepOut::ShouldStop(event_ptr);
360 if (step_out_should_stop) {
361 SetPlanComplete(true);
362 return true;
363 }
364
365 // If we have a step through plan, then w're in the process of getting
366 // through an ObjC msgSend. If we arrived at the target function, then
367 // check whether we have debug info, and if we do, stop.
368 Log *log = GetLog(LLDBLog::Step);
369
370 if (m_objc_step_through_sp && m_objc_step_through_sp->IsPlanComplete()) {
371 // If the plan failed for some reason, we should probably just let the
372 // step over plan get us out of here... We don't need to do anything about
373 // the step through plan, it is done and will get popped when we continue.
374 if (!m_objc_step_through_sp->PlanSucceeded()) {
375 LLDB_LOGF(log, "ObjC Step through plan failed. Stepping out.");
376 }
379 SetPlanComplete(true);
380 return true;
381 }
382 // If we didn't want to stop at this msgSend, there might be another so
383 // we should just continue on with the step out and see if our breakpoint
384 // triggers again.
386 for (BreakpointSP bkpt_sp : m_msgSend_bkpts) {
387 bkpt_sp->SetEnabled(true);
388 }
389 return false;
390 }
391
392 // If we hit an msgSend breakpoint, then we should queue the step through
393 // plan:
394
395 if (m_at_msg_send) {
396 LanguageRuntime *objc_runtime
397 = GetThread().GetProcess()->GetLanguageRuntime(eLanguageTypeObjC);
398 // There's no way we could have gotten here without an ObjC language
399 // runtime.
400 assert(objc_runtime);
402 objc_runtime->GetStepThroughTrampolinePlan(GetThread(), false);
403 // If we failed to find the target for this dispatch, just keep going and
404 // let the step out complete.
406 LLDB_LOG(log, "Couldn't find target for message dispatch, continuing.");
407 return false;
408 }
409 // Otherwise push the step through plan and continue.
411 for (BreakpointSP bkpt_sp : m_msgSend_bkpts) {
412 bkpt_sp->SetEnabled(false);
413 }
414 return false;
415 }
416 return true;
417}
418
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:364
#define LLDB_LOGF(log,...)
Definition Log.h:378
A section + offset based address class.
Definition Address.h:62
bool SetOpcodeLoadAddress(lldb::addr_t load_addr, Target *target, AddressClass addr_class=AddressClass::eInvalid, bool allow_section_end=false)
Definition Address.cpp:369
void ForEachDispatchFunction(std::function< void(lldb::addr_t, const DispatchFunction &)>)
void GetDescription(Stream *s, lldb::DescriptionLevel level) override
Print a description of this thread to the stream s.
std::vector< lldb::BreakpointSP > m_msgSend_bkpts
When we hit an objc_msgSend, we'll use this plan to get to its target.
lldb::addr_t m_sel_addr
isa_addr and sel_addr are the keys we will use to cache the implementation.
ValueList m_input_values
Stores the address for our step through function result structure.
AppleThreadPlanStepThroughObjCTrampoline(Thread &thread, AppleObjCTrampolineHandler &trampoline_handler, ValueList &values, lldb::addr_t isa_addr, lldb::addr_t sel_addr, lldb::addr_t sel_str_addr, llvm::StringRef sel_str)
void GetDescription(Stream *s, lldb::DescriptionLevel level) override
Print a description of this thread to the stream s.
bool ValidatePlan(Stream *error) override
Returns whether this plan could be successfully created.
lldb::addr_t m_sel_str_addr
This is a pointer to a impl function that is owned by the client that pushes this plan.
std::string m_sel_str
If this is not LLDB_INVALID_ADDRESS then it is the address we wrote the selector string to.
void SetUnwindOnError(bool unwind=false)
Definition Target.h:395
void SetStopOthers(bool stop_others=true)
Definition Target.h:432
void SetIgnoreBreakpoints(bool ignore=false)
Definition Target.h:399
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
Target * GetTargetPtr() const
Returns a pointer to the target object.
ValueType Clear(ValueType mask=~static_cast< ValueType >(0))
Clear one or more flags.
Definition Flags.h:61
virtual lldb::ThreadPlanSP GetStepThroughTrampolinePlan(Thread &thread, bool stop_others)=0
static ObjCLanguageRuntime * Get(Process &process)
void AddToMethodCache(lldb::addr_t class_addr, lldb::addr_t sel, lldb::addr_t impl_addr)
unsigned long long ULongLong(unsigned long long fail_value=0) const
Definition Scalar.cpp:365
An error handling class.
Definition Status.h:118
bool Fail() const
Test for error condition.
Definition Status.cpp:293
bool Success() const
Test for success condition.
Definition Status.cpp:303
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
Defines a symbol context baton that can be handed other debug core functions.
bool RemoveBreakpointByID(lldb::break_id_t break_id)
Definition Target.cpp:1176
bool InvokeShouldStopHereCallback(lldb::FrameComparison operation, Status &status)
bool DoWillResume(lldb::StateType resume_state, bool current_plan) override
ThreadPlanStepOut(Thread &thread, SymbolContext *addr_context, bool first_insn, bool stop_others, Vote report_stop_vote, Vote report_run_vote, uint32_t frame_idx, LazyBool step_out_avoids_code_without_debug_info, bool continue_to_next_branch=false, bool gather_return_value=true)
Creates a thread plan to step out from frame_idx, skipping parent frames if they are artificial or hi...
bool DoPlanExplainsStop(Event *event_ptr) override
bool ShouldStop(Event *event_ptr) override
ThreadPlan(ThreadPlanKind kind, const char *name, Thread &thread, Vote report_stop_vote, Vote report_run_vote)
void PushPlan(lldb::ThreadPlanSP &thread_plan_sp)
Definition ThreadPlan.h:529
void SetPlanComplete(bool success=true)
Thread & GetThread()
Returns the Thread that is using this thread plan.
lldb::StopInfoSP GetPrivateStopInfo()
Definition ThreadPlan.h:544
virtual lldb::StackFrameSP GetStackFrameAtIndex(uint32_t idx)
Definition Thread.h:434
Status QueueThreadPlan(lldb::ThreadPlanSP &plan_sp, bool abort_other_plans)
Queues a generic thread plan.
Definition Thread.cpp:1221
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition Thread.cpp:1465
lldb::ProcessSP GetProcess() const
Definition Thread.h:161
virtual lldb::ThreadPlanSP QueueThreadPlanForStepOutNoShouldStop(bool abort_other_plans, SymbolContext *addr_context, bool first_insn, bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote, uint32_t frame_idx, Status &status, bool continue_to_next_branch=false)
Queue the plan used to step out of the function at the current PC of a thread.
Definition Thread.cpp:1385
const Scalar & GetScalar() const
See comment on m_scalar to understand what GetScalar returns.
Definition Value.h:113
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:327
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::BreakpointSite > BreakpointSiteSP
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
@ eDescriptionLevelBrief
@ eFrameCompareYounger
StateType
Process and Thread States.
@ eStateRunning
Process or thread is running and can't be examined.
@ eLanguageTypeObjC
Objective-C.
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
uint64_t addr_t
Definition lldb-types.h:80
StopReason
Thread stop reasons.
@ eStopReasonBreakpoint
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47