LLDB  mainline
ThreadPlanCallFunction.cpp
Go to the documentation of this file.
1 //===-- ThreadPlanCallFunction.cpp ------------------------------*- C++ -*-===//
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 
12 #include "lldb/Core/Address.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Symbol/ObjectFile.h"
16 #include "lldb/Target/ABI.h"
18 #include "lldb/Target/Process.h"
20 #include "lldb/Target/StopInfo.h"
21 #include "lldb/Target/Target.h"
22 #include "lldb/Target/Thread.h"
24 #include "lldb/Utility/Log.h"
25 #include "lldb/Utility/Stream.h"
26 
27 #include <memory>
28 
29 using namespace lldb;
30 using namespace lldb_private;
31 
32 // ThreadPlanCallFunction: Plan to call a single function
33 bool ThreadPlanCallFunction::ConstructorSetup(
34  Thread &thread, ABI *&abi, lldb::addr_t &start_load_addr,
35  lldb::addr_t &function_load_addr) {
36  SetIsMasterPlan(true);
37  SetOkayToDiscard(false);
38  SetPrivate(true);
39 
40  ProcessSP process_sp(thread.GetProcess());
41  if (!process_sp)
42  return false;
43 
44  abi = process_sp->GetABI().get();
45 
46  if (!abi)
47  return false;
48 
50 
51  SetBreakpoints();
52 
53  m_function_sp = thread.GetRegisterContext()->GetSP() - abi->GetRedZoneSize();
54  // If we can't read memory at the point of the process where we are planning
55  // to put our function, we're not going to get any further...
56  Status error;
57  process_sp->ReadUnsignedIntegerFromMemory(m_function_sp, 4, 0, error);
58  if (!error.Success()) {
59  m_constructor_errors.Printf(
60  "Trying to put the stack in unreadable memory at: 0x%" PRIx64 ".",
61  m_function_sp);
62  if (log)
63  log->Printf("ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
64  m_constructor_errors.GetData());
65  return false;
66  }
67 
68  Module *exe_module = GetTarget().GetExecutableModulePointer();
69 
70  if (exe_module == nullptr) {
71  m_constructor_errors.Printf(
72  "Can't execute code without an executable module.");
73  if (log)
74  log->Printf("ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
75  m_constructor_errors.GetData());
76  return false;
77  } else {
78  ObjectFile *objectFile = exe_module->GetObjectFile();
79  if (!objectFile) {
80  m_constructor_errors.Printf(
81  "Could not find object file for module \"%s\".",
82  exe_module->GetFileSpec().GetFilename().AsCString());
83 
84  if (log)
85  log->Printf("ThreadPlanCallFunction(%p): %s.",
86  static_cast<void *>(this), m_constructor_errors.GetData());
87  return false;
88  }
89 
90  m_start_addr = objectFile->GetEntryPointAddress();
91  if (!m_start_addr.IsValid()) {
92  m_constructor_errors.Printf(
93  "Could not find entry point address for executable module \"%s\".",
94  exe_module->GetFileSpec().GetFilename().AsCString());
95  if (log)
96  log->Printf("ThreadPlanCallFunction(%p): %s.",
97  static_cast<void *>(this), m_constructor_errors.GetData());
98  return false;
99  }
100  }
101 
102  start_load_addr = m_start_addr.GetLoadAddress(&GetTarget());
103 
104  // Checkpoint the thread state so we can restore it later.
105  if (log && log->GetVerbose())
106  ReportRegisterState("About to checkpoint thread before function call. "
107  "Original register state was:");
108 
109  if (!thread.CheckpointThreadState(m_stored_thread_state)) {
110  m_constructor_errors.Printf("Setting up ThreadPlanCallFunction, failed to "
111  "checkpoint thread state.");
112  if (log)
113  log->Printf("ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
114  m_constructor_errors.GetData());
115  return false;
116  }
117  function_load_addr = m_function_addr.GetLoadAddress(&GetTarget());
118 
119  return true;
120 }
121 
122 ThreadPlanCallFunction::ThreadPlanCallFunction(
123  Thread &thread, const Address &function, const CompilerType &return_type,
124  llvm::ArrayRef<addr_t> args, const EvaluateExpressionOptions &options)
125  : ThreadPlan(ThreadPlan::eKindCallFunction, "Call function plan", thread,
127  m_valid(false), m_stop_other_threads(options.GetStopOthers()),
128  m_unwind_on_error(options.DoesUnwindOnError()),
129  m_ignore_breakpoints(options.DoesIgnoreBreakpoints()),
130  m_debug_execution(options.GetDebug()),
131  m_trap_exceptions(options.GetTrapExceptions()), m_function_addr(function),
132  m_function_sp(0), m_takedown_done(false),
133  m_should_clear_objc_exception_bp(false),
134  m_should_clear_cxx_exception_bp(false),
135  m_stop_address(LLDB_INVALID_ADDRESS), m_return_type(return_type) {
136  lldb::addr_t start_load_addr = LLDB_INVALID_ADDRESS;
137  lldb::addr_t function_load_addr = LLDB_INVALID_ADDRESS;
138  ABI *abi = nullptr;
139 
140  if (!ConstructorSetup(thread, abi, start_load_addr, function_load_addr))
141  return;
142 
143  if (!abi->PrepareTrivialCall(thread, m_function_sp, function_load_addr,
144  start_load_addr, args))
145  return;
146 
147  ReportRegisterState("Function call was set up. Register state was:");
148 
149  m_valid = true;
150 }
151 
152 ThreadPlanCallFunction::ThreadPlanCallFunction(
153  Thread &thread, const Address &function,
154  const EvaluateExpressionOptions &options)
155  : ThreadPlan(ThreadPlan::eKindCallFunction, "Call function plan", thread,
157  m_valid(false), m_stop_other_threads(options.GetStopOthers()),
158  m_unwind_on_error(options.DoesUnwindOnError()),
159  m_ignore_breakpoints(options.DoesIgnoreBreakpoints()),
160  m_debug_execution(options.GetDebug()),
161  m_trap_exceptions(options.GetTrapExceptions()), m_function_addr(function),
162  m_function_sp(0), m_takedown_done(false),
163  m_should_clear_objc_exception_bp(false),
164  m_should_clear_cxx_exception_bp(false),
165  m_stop_address(LLDB_INVALID_ADDRESS), m_return_type(CompilerType()) {}
166 
169 }
170 
173  if (log && log->GetVerbose()) {
174  StreamString strm;
175  RegisterContext *reg_ctx = m_thread.GetRegisterContext().get();
176 
177  log->PutCString(message);
178 
179  RegisterValue reg_value;
180 
181  for (uint32_t reg_idx = 0, num_registers = reg_ctx->GetRegisterCount();
182  reg_idx < num_registers; ++reg_idx) {
183  const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg_idx);
184  if (reg_ctx->ReadRegister(reg_info, reg_value)) {
185  DumpRegisterValue(reg_value, &strm, reg_info, true, false,
187  strm.EOL();
188  }
189  }
190  log->PutString(strm.GetString());
191  }
192 }
193 
196 
197  if (!m_valid) {
198  // Don't call DoTakedown if we were never valid to begin with.
199  if (log)
200  log->Printf("ThreadPlanCallFunction(%p): Log called on "
201  "ThreadPlanCallFunction that was never valid.",
202  static_cast<void *>(this));
203  return;
204  }
205 
206  if (!m_takedown_done) {
207  if (success) {
208  SetReturnValue();
209  }
210  if (log)
211  log->Printf("ThreadPlanCallFunction(%p): DoTakedown called for thread "
212  "0x%4.4" PRIx64 ", m_valid: %d complete: %d.\n",
213  static_cast<void *>(this), m_thread.GetID(), m_valid,
214  IsPlanComplete());
215  m_takedown_done = true;
217  m_thread.GetStackFrameAtIndex(0)->GetRegisterContext()->GetPC();
220  if (log)
221  log->Printf("ThreadPlanCallFunction(%p): DoTakedown failed to restore "
222  "register state",
223  static_cast<void *>(this));
224  }
225  SetPlanComplete(success);
227  if (log && log->GetVerbose())
228  ReportRegisterState("Restoring thread state after function call. "
229  "Restored register state:");
230  } else {
231  if (log)
232  log->Printf("ThreadPlanCallFunction(%p): DoTakedown called as no-op for "
233  "thread 0x%4.4" PRIx64 ", m_valid: %d complete: %d.\n",
234  static_cast<void *>(this), m_thread.GetID(), m_valid,
235  IsPlanComplete());
236  }
237 }
238 
240 
242  if (level == eDescriptionLevelBrief) {
243  s->Printf("Function call thread plan");
244  } else {
245  TargetSP target_sp(m_thread.CalculateTarget());
246  s->Printf("Thread plan to call 0x%" PRIx64,
247  m_function_addr.GetLoadAddress(target_sp.get()));
248  }
249 }
250 
252  if (!m_valid) {
253  if (error) {
254  if (m_constructor_errors.GetSize() > 0)
256  else
257  error->PutCString("Unknown error");
258  }
259  return false;
260  }
261 
262  return true;
263 }
264 
267  return eVoteYes;
268  else
269  return ThreadPlan::ShouldReportStop(event_ptr);
270 }
271 
276 
277  // If our subplan knows why we stopped, even if it's done (which would
278  // forward the question to us) we answer yes.
279  if (m_subplan_sp && m_subplan_sp->PlanExplainsStop(event_ptr)) {
280  SetPlanComplete();
281  return true;
282  }
283 
284  // Check if the breakpoint is one of ours.
285 
286  StopReason stop_reason;
287  if (!m_real_stop_info_sp)
288  stop_reason = eStopReasonNone;
289  else
290  stop_reason = m_real_stop_info_sp->GetStopReason();
291  if (log)
292  log->Printf(
293  "ThreadPlanCallFunction::PlanExplainsStop: Got stop reason - %s.",
294  Thread::StopReasonAsCString(stop_reason));
295 
296  if (stop_reason == eStopReasonBreakpoint && BreakpointsExplainStop())
297  return true;
298 
299  // One more quirk here. If this event was from Halt interrupting the target,
300  // then we should not consider ourselves complete. Return true to
301  // acknowledge the stop.
303  if (log)
304  log->Printf("ThreadPlanCallFunction::PlanExplainsStop: The event is an "
305  "Interrupt, returning true.");
306  return true;
307  }
308  // We control breakpoints separately from other "stop reasons." So first,
309  // check the case where we stopped for an internal breakpoint, in that case,
310  // continue on. If it is not an internal breakpoint, consult
311  // m_ignore_breakpoints.
312 
313  if (stop_reason == eStopReasonBreakpoint) {
314  ProcessSP process_sp(m_thread.CalculateProcess());
315  uint64_t break_site_id = m_real_stop_info_sp->GetValue();
316  BreakpointSiteSP bp_site_sp;
317  if (process_sp)
318  bp_site_sp = process_sp->GetBreakpointSiteList().FindByID(break_site_id);
319  if (bp_site_sp) {
320  uint32_t num_owners = bp_site_sp->GetNumberOfOwners();
321  bool is_internal = true;
322  for (uint32_t i = 0; i < num_owners; i++) {
323  Breakpoint &bp = bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
324  if (log)
325  log->Printf("ThreadPlanCallFunction::PlanExplainsStop: hit "
326  "breakpoint %d while calling function",
327  bp.GetID());
328 
329  if (!bp.IsInternal()) {
330  is_internal = false;
331  break;
332  }
333  }
334  if (is_internal) {
335  if (log)
336  log->Printf("ThreadPlanCallFunction::PlanExplainsStop hit an "
337  "internal breakpoint, not stopping.");
338  return false;
339  }
340  }
341 
342  if (m_ignore_breakpoints) {
343  if (log)
344  log->Printf("ThreadPlanCallFunction::PlanExplainsStop: we are ignoring "
345  "breakpoints, overriding breakpoint stop info ShouldStop, "
346  "returning true");
347  m_real_stop_info_sp->OverrideShouldStop(false);
348  return true;
349  } else {
350  if (log)
351  log->Printf("ThreadPlanCallFunction::PlanExplainsStop: we are not "
352  "ignoring breakpoints, overriding breakpoint stop info "
353  "ShouldStop, returning true");
354  m_real_stop_info_sp->OverrideShouldStop(true);
355  return false;
356  }
357  } else if (!m_unwind_on_error) {
358  // If we don't want to discard this plan, than any stop we don't understand
359  // should be propagated up the stack.
360  return false;
361  } else {
362  // If the subplan is running, any crashes are attributable to us. If we
363  // want to discard the plan, then we say we explain the stop but if we are
364  // going to be discarded, let whoever is above us explain the stop. But
365  // don't discard the plan if the stop would restart itself (for instance if
366  // it is a signal that is set not to stop. Check that here first. We just
367  // say we explain the stop but aren't done and everything will continue on
368  // from there.
369 
370  if (m_real_stop_info_sp &&
371  m_real_stop_info_sp->ShouldStopSynchronous(event_ptr)) {
372  SetPlanComplete(false);
373  return m_subplan_sp ? m_unwind_on_error : false;
374  } else
375  return true;
376  }
377 }
378 
380  // We do some computation in DoPlanExplainsStop that may or may not set the
381  // plan as complete. We need to do that here to make sure our state is
382  // correct.
383  DoPlanExplainsStop(event_ptr);
384 
385  if (IsPlanComplete()) {
386  ReportRegisterState("Function completed. Register state was:");
387  return true;
388  } else {
389  return false;
390  }
391 }
392 
394 
396 
398  //#define SINGLE_STEP_EXPRESSIONS
399 
400  // Now set the thread state to "no reason" so we don't run with whatever
401  // signal was outstanding... Wait till the plan is pushed so we aren't
402  // changing the stop info till we're about to run.
403 
405 
406 #ifndef SINGLE_STEP_EXPRESSIONS
407  m_subplan_sp = std::make_shared<ThreadPlanRunToAddress>(
409 
410  m_thread.QueueThreadPlan(m_subplan_sp, false);
411  m_subplan_sp->SetPrivate(true);
412 #endif
413 }
414 
415 bool ThreadPlanCallFunction::WillStop() { return true; }
416 
419 
420  if (IsPlanComplete()) {
421  if (log)
422  log->Printf("ThreadPlanCallFunction(%p): Completed call function plan.",
423  static_cast<void *>(this));
424 
426  return true;
427  } else {
428  return false;
429  }
430 }
431 
433  ProcessSP process_sp(m_thread.CalculateProcess());
434  if (m_trap_exceptions && process_sp) {
436  process_sp->GetLanguageRuntime(eLanguageTypeC_plus_plus);
437  m_objc_language_runtime = process_sp->GetLanguageRuntime(eLanguageTypeObjC);
438 
443  }
448  }
449  }
450 }
451 
453  if (m_trap_exceptions) {
458  }
459 }
460 
462  StopInfoSP stop_info_sp = GetPrivateStopInfo();
463 
464  if (m_trap_exceptions) {
465  if ((m_cxx_language_runtime &&
467  stop_info_sp)) ||
470  stop_info_sp))) {
472  if (log)
473  log->Printf("ThreadPlanCallFunction::BreakpointsExplainStop - Hit an "
474  "exception breakpoint, setting plan complete.");
475 
476  SetPlanComplete(false);
477 
478  // If the user has set the ObjC language breakpoint, it would normally
479  // get priority over our internal catcher breakpoint, but in this case we
480  // can't let that happen, so force the ShouldStop here.
481  stop_info_sp->OverrideShouldStop(true);
482  return true;
483  }
484  }
485 
486  return false;
487 }
488 
490  m_subplan_sp->SetStopOthers(new_value);
491 }
492 
495 }
496 
498  ProcessSP process_sp(m_thread.GetProcess());
499  const ABI *abi = process_sp ? process_sp->GetABI().get() : nullptr;
500  if (abi && m_return_type.IsValid()) {
501  const bool persistent = false;
503  abi->GetReturnValueObject(m_thread, m_return_type, persistent);
504  }
505 }
ConstString & GetFilename()
Filename string get accessor.
Definition: FileSpec.cpp:369
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition: Stream.cpp:61
lldb::StopInfoSP GetPrivateStopInfo()
Definition: ThreadPlan.h:564
#define LIBLLDB_LOG_PROCESS
Definition: Logging.h:15
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
Definition: ConstString.h:224
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
virtual bool PrepareTrivialCall(lldb_private::Thread &thread, lldb::addr_t sp, lldb::addr_t functionAddress, lldb::addr_t returnAddress, llvm::ArrayRef< lldb::addr_t > args) const =0
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
Definition: Module.h:531
virtual void SetExceptionBreakpoints()
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition: Address.cpp:292
Thread::ThreadStateCheckpoint m_stored_thread_state
virtual bool CheckpointThreadState(ThreadStateCheckpoint &saved_state)
Definition: Thread.cpp:523
General Outline: A breakpoint has four main parts, a filter, a resolver, the list of breakpoint locat...
Definition: Breakpoint.h:78
virtual ObjectFile * GetObjectFile()
Get the object file representation for the current architecture.
Definition: Module.cpp:1251
void PutString(llvm::StringRef str)
Definition: Log.cpp:110
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition: UserID.h:49
A plug-in interface definition class for object file parsers.
Definition: ObjectFile.h:58
virtual size_t GetRedZoneSize() const =0
void SetStopInfoToNothing()
Definition: Thread.cpp:511
void SetStopOthers(bool new_value) override
virtual bool RestoreThreadStateFromCheckpoint(ThreadStateCheckpoint &saved_state)
Definition: Thread.cpp:570
bool ValidatePlan(Stream *error) override
Returns whether this plan could be successfully created.
bool DumpRegisterValue(const RegisterValue &reg_val, Stream *s, const RegisterInfo *reg_info, bool prefix_with_name, bool prefix_with_alt_name, lldb::Format format, uint32_t reg_name_right_align_at=0)
virtual size_t GetRegisterCount()=0
virtual lldb_private::Address GetEntryPointAddress()
Returns the address of the Entry Point in this object file - if the object file doesn&#39;t have an entry...
Definition: ObjectFile.h:468
#define LLDB_INVALID_ADDRESS
Invalid value definitions.
Definition: lldb-defines.h:85
Vote ShouldReportStop(Event *event_ptr) override
bool IsInternal() const
Tell whether this breakpoint is an "internal" breakpoint.
Definition: Breakpoint.cpp:251
Log * GetLogIfAllCategoriesSet(uint32_t mask)
Definition: Logging.cpp:57
size_t EOL()
Output and End of Line character to the stream.
Definition: Stream.cpp:127
A class that describes an executable image and its associated object and symbol files.
Definition: Module.h:109
lldb::TargetSP CalculateTarget() override
Definition: Thread.cpp:1584
lldb::break_id_t GetID() const
Definition: Stoppoint.cpp:22
llvm::StringRef GetString() const
virtual lldb::RegisterContextSP GetRegisterContext()=0
virtual const RegisterInfo * GetRegisterInfoAtIndex(size_t reg)=0
virtual bool ReadRegister(const RegisterInfo *reg_info, RegisterValue &reg_value)=0
virtual bool MischiefManaged()
Definition: ThreadPlan.cpp:57
lldb::ProcessSP CalculateProcess() override
Definition: Thread.cpp:1592
virtual bool ExceptionBreakpointsExplainStop(lldb::StopInfoSP stop_reason)
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:106
bool GetVerbose() const
Definition: Log.cpp:250
bool Success() const
Test for success condition.
Definition: Status.cpp:287
A section + offset based address class.
Definition: Address.h:80
static bool GetInterruptedFromEvent(const Event *event_ptr)
Definition: Process.cpp:4173
void SetPlanComplete(bool success=true)
Definition: ThreadPlan.cpp:51
lldb::ProcessSP GetProcess() const
Definition: Thread.h:154
bool ShouldStop(Event *event_ptr) override
virtual Vote ShouldReportStop(Event *event_ptr)
Definition: ThreadPlan.cpp:64
uint64_t addr_t
Definition: lldb-types.h:83
void GetDescription(Stream *s, lldb::DescriptionLevel level) override
Print a description of this thread to the stream s.
void PutCString(const char *cstr)
Definition: Log.cpp:109
Log * GetLogIfAnyCategoriesSet(uint32_t mask)
Definition: Logging.cpp:61
Definition: SBAddress.h:15
virtual void ClearExceptionBreakpoints()
Thread & GetThread()
Returns the Thread that is using this thread plan.
Definition: ThreadPlan.h:372
virtual bool ExceptionBreakpointsAreSet()
virtual lldb::StackFrameSP GetStackFrameAtIndex(uint32_t idx)
Definition: Thread.h:395
#define LIBLLDB_LOG_STEP
Definition: Logging.h:21
void Printf(const char *format,...) __attribute__((format(printf
Definition: Log.cpp:113
virtual bool RestoreRegisterStateFromCheckpoint(ThreadStateCheckpoint &saved_state)
Definition: Thread.cpp:548
static const char * StopReasonAsCString(lldb::StopReason reason)
Definition: Thread.cpp:1860
An error handling class.
Definition: Status.h:44
Process or thread is running and can&#39;t be examined.
bool DoPlanExplainsStop(Event *event_ptr) override