Coverage Report

Created: 2023-11-11 10:31

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleThreadPlanStepThroughObjCTrampoline.cpp
Line
Count
Source (jump to first uncovered line)
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
9
#include "AppleThreadPlanStepThroughObjCTrampoline.h"
10
11
#include "AppleObjCTrampolineHandler.h"
12
#include "lldb/Expression/DiagnosticManager.h"
13
#include "lldb/Expression/FunctionCaller.h"
14
#include "lldb/Expression/UtilityFunction.h"
15
#include "lldb/Target/ABI.h"
16
#include "lldb/Target/ExecutionContext.h"
17
#include "lldb/Target/Process.h"
18
#include "lldb/Target/Thread.h"
19
#include "lldb/Target/ThreadPlanRunToAddress.h"
20
#include "lldb/Target/ThreadPlanStepOut.h"
21
#include "lldb/Utility/LLDBLog.h"
22
#include "lldb/Utility/Log.h"
23
24
#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
25
26
#include <memory>
27
28
using namespace lldb;
29
using namespace lldb_private;
30
31
// ThreadPlanStepThroughObjCTrampoline constructor
32
AppleThreadPlanStepThroughObjCTrampoline::
33
    AppleThreadPlanStepThroughObjCTrampoline(
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)
37
27
    : ThreadPlan(ThreadPlan::eKindGeneric,
38
27
                 "MacOSX Step through ObjC Trampoline", thread, eVoteNoOpinion,
39
27
                 eVoteNoOpinion),
40
27
      m_trampoline_handler(trampoline_handler),
41
27
      m_args_addr(LLDB_INVALID_ADDRESS), m_input_values(input_values),
42
27
      m_isa_addr(isa_addr), m_sel_addr(sel_addr), m_impl_function(nullptr),
43
27
      m_sel_str_addr(sel_str_addr), m_sel_str(sel_str) {}
44
45
// Destructor
46
AppleThreadPlanStepThroughObjCTrampoline::
47
27
    ~AppleThreadPlanStepThroughObjCTrampoline() = default;
48
49
27
void AppleThreadPlanStepThroughObjCTrampoline::DidPush() {
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
27
  m_process.AddPreResumeAction(PreResumeInitializeFunctionCaller, (void *)this);
54
27
}
55
56
27
bool AppleThreadPlanStepThroughObjCTrampoline::InitializeFunctionCaller() {
57
27
  if (!m_func_sp) {
58
27
    DiagnosticManager diagnostics;
59
27
    m_args_addr =
60
27
        m_trampoline_handler.SetupDispatchFunction(GetThread(), m_input_values);
61
62
27
    if (m_args_addr == LLDB_INVALID_ADDRESS) {
63
0
      return false;
64
0
    }
65
27
    m_impl_function =
66
27
        m_trampoline_handler.GetLookupImplementationFunctionCaller();
67
27
    ExecutionContext exc_ctx;
68
27
    EvaluateExpressionOptions options;
69
27
    options.SetUnwindOnError(true);
70
27
    options.SetIgnoreBreakpoints(true);
71
27
    options.SetStopOthers(false);
72
27
    GetThread().CalculateExecutionContext(exc_ctx);
73
27
    m_func_sp = m_impl_function->GetThreadPlanToCallFunction(
74
27
        exc_ctx, m_args_addr, options, diagnostics);
75
27
    m_func_sp->SetOkayToDiscard(true);
76
27
    PushPlan(m_func_sp);
77
27
  }
78
27
  return true;
79
27
}
80
81
bool AppleThreadPlanStepThroughObjCTrampoline::
82
27
    PreResumeInitializeFunctionCaller(void *void_myself) {
83
27
  AppleThreadPlanStepThroughObjCTrampoline *myself =
84
27
      static_cast<AppleThreadPlanStepThroughObjCTrampoline *>(void_myself);
85
27
  return myself->InitializeFunctionCaller();
86
27
}
87
88
void AppleThreadPlanStepThroughObjCTrampoline::GetDescription(
89
0
    Stream *s, lldb::DescriptionLevel level) {
90
0
  if (level == lldb::eDescriptionLevelBrief)
91
0
    s->Printf("Step through ObjC trampoline");
92
0
  else {
93
0
    s->Printf("Stepping to implementation of ObjC method - obj: 0x%llx, isa: "
94
0
              "0x%" PRIx64 ", sel: 0x%" PRIx64,
95
0
              m_input_values.GetValueAtIndex(0)->GetScalar().ULongLong(),
96
0
              m_isa_addr, m_sel_addr);
97
0
  }
98
0
}
99
100
16
bool AppleThreadPlanStepThroughObjCTrampoline::ValidatePlan(Stream *error) {
101
16
  return true;
102
16
}
103
104
bool AppleThreadPlanStepThroughObjCTrampoline::DoPlanExplainsStop(
105
23
    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
23
  return true;
110
23
}
111
112
27
lldb::StateType AppleThreadPlanStepThroughObjCTrampoline::GetPlanRunState() {
113
27
  return eStateRunning;
114
27
}
115
116
54
bool AppleThreadPlanStepThroughObjCTrampoline::ShouldStop(Event *event_ptr) {
117
  // First stage: we are still handling the "call a function to get the target
118
  // of the dispatch"
119
54
  if (m_func_sp) {
120
27
    if (!m_func_sp->IsPlanComplete()) {
121
0
      return false;
122
27
    } else {
123
27
      if (!m_func_sp->PlanSucceeded()) {
124
0
        SetPlanComplete(false);
125
0
        return true;
126
0
      }
127
27
      m_func_sp.reset();
128
27
    }
129
27
  }
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
54
  Log *log = GetLog(LLDBLog::Step);
134
135
54
  if (!m_run_to_sp) {
136
27
    Value target_addr_value;
137
27
    ExecutionContext exc_ctx;
138
27
    GetThread().CalculateExecutionContext(exc_ctx);
139
27
    m_impl_function->FetchFunctionResults(exc_ctx, m_args_addr,
140
27
                                          target_addr_value);
141
27
    m_impl_function->DeallocateFunctionResults(exc_ctx, m_args_addr);
142
27
    lldb::addr_t target_addr = target_addr_value.GetScalar().ULongLong();
143
144
27
    if (ABISP abi_sp = GetThread().GetProcess()->GetABI()) {
145
27
      target_addr = abi_sp->FixCodeAddress(target_addr);
146
27
    }
147
27
    Address target_so_addr;
148
27
    target_so_addr.SetOpcodeLoadAddress(target_addr, exc_ctx.GetTargetPtr());
149
27
    if (target_addr == 0) {
150
0
      LLDB_LOGF(log, "Got target implementation of 0x0, stopping.");
151
0
      SetPlanComplete();
152
0
      return true;
153
0
    }
154
27
    if (m_trampoline_handler.AddrIsMsgForward(target_addr)) {
155
0
      LLDB_LOGF(log,
156
0
                "Implementation lookup returned msgForward function: 0x%" PRIx64
157
0
                ", stopping.",
158
0
                target_addr);
159
160
0
      SymbolContext sc = GetThread().GetStackFrameAtIndex(0)->GetSymbolContext(
161
0
          eSymbolContextEverything);
162
0
      Status status;
163
0
      const bool abort_other_plans = false;
164
0
      const bool first_insn = true;
165
0
      const uint32_t frame_idx = 0;
166
0
      m_run_to_sp = GetThread().QueueThreadPlanForStepOutNoShouldStop(
167
0
          abort_other_plans, &sc, first_insn, false, eVoteNoOpinion,
168
0
          eVoteNoOpinion, frame_idx, status);
169
0
      if (m_run_to_sp && status.Success())
170
0
        m_run_to_sp->SetPrivate(true);
171
0
      return false;
172
0
    }
173
174
27
    LLDB_LOGF(log, "Running to ObjC method implementation: 0x%" PRIx64,
175
27
              target_addr);
176
177
27
    ObjCLanguageRuntime *objc_runtime =
178
27
        ObjCLanguageRuntime::Get(*GetThread().GetProcess());
179
27
    assert(objc_runtime != nullptr);
180
27
    if (m_sel_str_addr != LLDB_INVALID_ADDRESS) {
181
      // Cache the string -> implementation and free the string in the target.
182
0
      Status dealloc_error =
183
0
          GetThread().GetProcess()->DeallocateMemory(m_sel_str_addr);
184
      // For now just log this:
185
0
      if (dealloc_error.Fail())
186
0
        LLDB_LOG(log, "Failed to deallocate the sel str at {0} - error: {1}",
187
0
                 m_sel_str_addr, dealloc_error);
188
0
      objc_runtime->AddToMethodCache(m_isa_addr, m_sel_str, target_addr);
189
0
      LLDB_LOG(log,
190
0
               "Adding \\{isa-addr={0}, sel-addr={1}\\} = addr={2} to cache.",
191
0
               m_isa_addr, m_sel_str, target_addr);
192
27
    } else {
193
27
      objc_runtime->AddToMethodCache(m_isa_addr, m_sel_addr, target_addr);
194
27
      LLDB_LOGF(log,
195
27
                "Adding {isa-addr=0x%" PRIx64 ", sel-addr=0x%" PRIx64
196
27
                "} = addr=0x%" PRIx64 " to cache.",
197
27
                m_isa_addr, m_sel_addr, target_addr);
198
27
    }
199
200
27
    m_run_to_sp = std::make_shared<ThreadPlanRunToAddress>(
201
27
        GetThread(), target_so_addr, false);
202
27
    PushPlan(m_run_to_sp);
203
27
    return false;
204
27
  } else if (GetThread().IsThreadPlanDone(m_run_to_sp.get())) {
205
    // Third stage, work the run to target plan.
206
27
    SetPlanComplete();
207
27
    return true;
208
27
  }
209
0
  return false;
210
54
}
211
212
// The base class MischiefManaged does some cleanup - so you have to call it in
213
// your MischiefManaged derived class.
214
54
bool AppleThreadPlanStepThroughObjCTrampoline::MischiefManaged() {
215
54
  return IsPlanComplete();
216
54
}
217
218
27
bool AppleThreadPlanStepThroughObjCTrampoline::WillStop() { return true; }
219
220
// Objective-C uses optimized dispatch functions for some common and seldom
221
// overridden methods.  For instance
222
//      [object respondsToSelector:];
223
// will get compiled to:
224
//      objc_opt_respondsToSelector(object);
225
// This checks whether the selector has been overridden, directly calling the
226
// implementation if it hasn't and calling objc_msgSend if it has.
227
//
228
// We need to get into the overridden implementation.  We'll do that by 
229
// setting a breakpoint on objc_msgSend, and doing a "step out".  If we stop
230
// at objc_msgSend, we can step through to the target of the send, and see if
231
// that's a place we want to stop.
232
//
233
// A couple of complexities.  The checking code might call some other method,
234
// so we might see objc_msgSend more than once.  Also, these optimized dispatch
235
// functions might dispatch more than one message at a time (e.g. alloc followed
236
// by init.)  So we can't give up at the first objc_msgSend.
237
// That means among other things that we have to handle the "ShouldStopHere" - 
238
// since we can't just return control to the plan that's controlling us on the
239
// first step.
240
241
AppleThreadPlanStepThroughDirectDispatch ::
242
    AppleThreadPlanStepThroughDirectDispatch(
243
        Thread &thread, AppleObjCTrampolineHandler &handler,
244
        llvm::StringRef dispatch_func_name)
245
10
    : ThreadPlanStepOut(thread, nullptr, true /* first instruction */, false,
246
10
                        eVoteNoOpinion, eVoteNoOpinion,
247
10
                        0 /* Step out of zeroth frame */,
248
10
                        eLazyBoolNo /* Our parent plan will decide this
249
                               when we are done */
250
10
                        ,
251
10
                        true /* Run to branch for inline step out */,
252
10
                        false /* Don't gather the return value */),
253
10
      m_trampoline_handler(handler),
254
10
      m_dispatch_func_name(std::string(dispatch_func_name)),
255
10
      m_at_msg_send(false) {
256
  // Set breakpoints on the dispatch functions:
257
10
  auto bkpt_callback = [&] (lldb::addr_t addr, 
258
10
                            const AppleObjCTrampolineHandler
259
200
                                ::DispatchFunction &dispatch) {
260
200
    m_msgSend_bkpts.push_back(GetTarget().CreateBreakpoint(addr,
261
200
                                                           true /* internal */,
262
200
                                                           false /* hard */));
263
200
    m_msgSend_bkpts.back()->SetThreadID(GetThread().GetID());
264
200
  };
265
10
  handler.ForEachDispatchFunction(bkpt_callback);
266
267
  // We'll set the step-out plan in the DidPush so it gets queued in the right
268
  // order.
269
270
10
  if (GetThread().GetStepInAvoidsNoDebug())
271
10
    GetFlags().Set(ThreadPlanShouldStopHere::eStepInAvoidNoDebug);
272
0
  else
273
0
    GetFlags().Clear(ThreadPlanShouldStopHere::eStepInAvoidNoDebug);
274
  // We only care about step in.  Our parent plan will figure out what to
275
  // do when we've stepped out again.
276
10
  GetFlags().Clear(ThreadPlanShouldStopHere::eStepOutAvoidNoDebug);
277
10
}
278
279
AppleThreadPlanStepThroughDirectDispatch::
280
10
    ~AppleThreadPlanStepThroughDirectDispatch() {
281
200
    for (BreakpointSP bkpt_sp : m_msgSend_bkpts) {
282
200
      GetTarget().RemoveBreakpointByID(bkpt_sp->GetID());
283
200
    }
284
10
}
285
286
void AppleThreadPlanStepThroughDirectDispatch::GetDescription(
287
0
    Stream *s, lldb::DescriptionLevel level) {
288
0
  switch (level) {
289
0
  case lldb::eDescriptionLevelBrief:
290
0
    s->PutCString("Step through ObjC direct dispatch function.");
291
0
    break;
292
0
  default:
293
0
    s->Printf("Step through ObjC direct dispatch '%s'  using breakpoints: ",
294
0
              m_dispatch_func_name.c_str());
295
0
    bool first = true;
296
0
    for (auto bkpt_sp : m_msgSend_bkpts) {
297
0
        if (!first) {
298
0
          s->PutCString(", ");
299
0
        }
300
0
        first = false;
301
0
        s->Printf("%d", bkpt_sp->GetID());
302
0
    }
303
0
    (*s) << ".";  
304
0
    break;
305
0
  }
306
0
}
307
308
bool 
309
16
AppleThreadPlanStepThroughDirectDispatch::DoPlanExplainsStop(Event *event_ptr) {
310
16
  if (ThreadPlanStepOut::DoPlanExplainsStop(event_ptr))
311
5
    return true;
312
313
11
  StopInfoSP stop_info_sp = GetPrivateStopInfo();
314
315
  // Check if the breakpoint is one of ours msgSend dispatch breakpoints.
316
317
11
  StopReason stop_reason = eStopReasonNone;
318
11
  if (stop_info_sp)
319
11
    stop_reason = stop_info_sp->GetStopReason();
320
321
  // See if this is one of our msgSend breakpoints:
322
11
  if (stop_reason == eStopReasonBreakpoint) {
323
11
    ProcessSP process_sp = GetThread().GetProcess();
324
11
    uint64_t break_site_id = stop_info_sp->GetValue();
325
11
    BreakpointSiteSP site_sp 
326
11
        = process_sp->GetBreakpointSiteList().FindByID(break_site_id);
327
    // Some other plan might have deleted the site's last owner before this 
328
    // got to us.  In which case, it wasn't our breakpoint...    
329
11
    if (!site_sp)
330
0
      return false;
331
      
332
11
    for (BreakpointSP break_sp : m_msgSend_bkpts) {
333
11
      if (site_sp->IsBreakpointAtThisSite(break_sp->GetID())) {
334
        // If we aren't the only one with a breakpoint on this site, then we
335
        // should just stop and return control to the user.
336
11
        if (site_sp->GetNumberOfOwners() > 1) {
337
0
          SetPlanComplete(true);
338
0
          return false;
339
0
        }
340
11
        m_at_msg_send = true;
341
11
        return true;
342
11
      }
343
11
    }
344
11
  }
345
  
346
  // We're done here.  If one of our sub-plans explained the stop, they 
347
  // would have already answered true to PlanExplainsStop, and if they were
348
  // done, we'll get called to figure out what to do in ShouldStop...
349
0
  return false;
350
11
}
351
352
bool AppleThreadPlanStepThroughDirectDispatch
353
30
         ::DoWillResume(lldb::StateType resume_state, bool current_plan) {
354
30
  ThreadPlanStepOut::DoWillResume(resume_state, current_plan);
355
30
  m_at_msg_send = false;
356
30
  return true;
357
30
}
358
359
22
bool AppleThreadPlanStepThroughDirectDispatch::ShouldStop(Event *event_ptr) {
360
  // If step out plan finished, that means we didn't find our way into a method
361
  // implementation.  Either we went directly to the default implementation, 
362
  // of the overridden implementation didn't have debug info.  
363
  // So we should mark ourselves as done.
364
22
  const bool step_out_should_stop = ThreadPlanStepOut::ShouldStop(event_ptr);
365
22
  if (step_out_should_stop) {
366
0
    SetPlanComplete(true);
367
0
    return true;
368
0
  }
369
  
370
  // If we have a step through plan, then w're in the process of getting 
371
  // through an ObjC msgSend.  If we arrived at the target function, then 
372
  // check whether we have debug info, and if we do, stop.
373
22
  Log *log = GetLog(LLDBLog::Step);
374
375
22
  if (m_objc_step_through_sp && 
m_objc_step_through_sp->IsPlanComplete()11
) {
376
    // If the plan failed for some reason, we should probably just let the
377
    // step over plan get us out of here...  We don't need to do anything about
378
    // the step through plan, it is done and will get popped when we continue.
379
11
    if (!m_objc_step_through_sp->PlanSucceeded()) {
380
0
      LLDB_LOGF(log, "ObjC Step through plan failed.  Stepping out.");
381
0
    }
382
11
    Status error;
383
11
    if (InvokeShouldStopHereCallback(eFrameCompareYounger, error)) {
384
10
      SetPlanComplete(true);
385
10
      return true;
386
10
    }
387
    // If we didn't want to stop at this msgSend, there might be another so
388
    // we should just continue on with the step out and see if our breakpoint
389
    // triggers again.
390
1
    m_objc_step_through_sp.reset();
391
20
    for (BreakpointSP bkpt_sp : m_msgSend_bkpts) {
392
20
      bkpt_sp->SetEnabled(true);
393
20
    }
394
1
    return false;
395
11
  }
396
397
  // If we hit an msgSend breakpoint, then we should queue the step through
398
  // plan:
399
  
400
11
  if (m_at_msg_send) {
401
11
    LanguageRuntime *objc_runtime 
402
11
      = GetThread().GetProcess()->GetLanguageRuntime(eLanguageTypeObjC);
403
    // There's no way we could have gotten here without an ObjC language 
404
    // runtime.
405
11
    assert(objc_runtime);
406
11
    m_objc_step_through_sp =
407
11
        objc_runtime->GetStepThroughTrampolinePlan(GetThread(), false);
408
    // If we failed to find the target for this dispatch, just keep going and
409
    // let the step out complete.
410
11
    if (!m_objc_step_through_sp) {
411
0
      LLDB_LOG(log, "Couldn't find target for message dispatch, continuing.");
412
0
      return false;
413
0
    }
414
    // Otherwise push the step through plan and continue.
415
11
    GetThread().QueueThreadPlan(m_objc_step_through_sp, false);
416
220
    for (BreakpointSP bkpt_sp : m_msgSend_bkpts) {
417
220
      bkpt_sp->SetEnabled(false);
418
220
    }
419
11
    return false;
420
11
  }
421
0
  return true;  
422
11
}
423
424
22
bool AppleThreadPlanStepThroughDirectDispatch::MischiefManaged() {
425
22
  if (IsPlanComplete())
426
10
    return true;
427
12
  return ThreadPlanStepOut::MischiefManaged();
428
22
}