]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/lldb/source/Target/ThreadPlanCallFunction.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm-project / lldb / source / Target / ThreadPlanCallFunction.cpp
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
9 #include "lldb/Target/ThreadPlanCallFunction.h"
10 #include "lldb/Breakpoint/Breakpoint.h"
11 #include "lldb/Breakpoint/BreakpointLocation.h"
12 #include "lldb/Core/Address.h"
13 #include "lldb/Core/DumpRegisterValue.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Symbol/ObjectFile.h"
16 #include "lldb/Target/ABI.h"
17 #include "lldb/Target/LanguageRuntime.h"
18 #include "lldb/Target/Process.h"
19 #include "lldb/Target/RegisterContext.h"
20 #include "lldb/Target/StopInfo.h"
21 #include "lldb/Target/Target.h"
22 #include "lldb/Target/Thread.h"
23 #include "lldb/Target/ThreadPlanRunToAddress.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
49   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP));
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,
126                  eVoteNoOpinion, eVoteNoOpinion),
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,
156                  eVoteNoOpinion, eVoteNoOpinion),
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
167 ThreadPlanCallFunction::~ThreadPlanCallFunction() {
168   DoTakedown(PlanSucceeded());
169 }
170
171 void ThreadPlanCallFunction::ReportRegisterState(const char *message) {
172   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
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,
186                           eFormatDefault);
187         strm.EOL();
188       }
189     }
190     log->PutString(strm.GetString());
191   }
192 }
193
194 void ThreadPlanCallFunction::DoTakedown(bool success) {
195   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP));
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;
216     m_stop_address =
217         m_thread.GetStackFrameAtIndex(0)->GetRegisterContext()->GetPC();
218     m_real_stop_info_sp = GetPrivateStopInfo();
219     if (!m_thread.RestoreRegisterStateFromCheckpoint(m_stored_thread_state)) {
220       if (log)
221         log->Printf("ThreadPlanCallFunction(%p): DoTakedown failed to restore "
222                     "register state",
223                     static_cast<void *>(this));
224     }
225     SetPlanComplete(success);
226     ClearBreakpoints();
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
239 void ThreadPlanCallFunction::WillPop() { DoTakedown(PlanSucceeded()); }
240
241 void ThreadPlanCallFunction::GetDescription(Stream *s, DescriptionLevel level) {
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
251 bool ThreadPlanCallFunction::ValidatePlan(Stream *error) {
252   if (!m_valid) {
253     if (error) {
254       if (m_constructor_errors.GetSize() > 0)
255         error->PutCString(m_constructor_errors.GetString());
256       else
257         error->PutCString("Unknown error");
258     }
259     return false;
260   }
261
262   return true;
263 }
264
265 Vote ThreadPlanCallFunction::ShouldReportStop(Event *event_ptr) {
266   if (m_takedown_done || IsPlanComplete())
267     return eVoteYes;
268   else
269     return ThreadPlan::ShouldReportStop(event_ptr);
270 }
271
272 bool ThreadPlanCallFunction::DoPlanExplainsStop(Event *event_ptr) {
273   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
274                                                   LIBLLDB_LOG_PROCESS));
275   m_real_stop_info_sp = GetPrivateStopInfo();
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.
302   if (Process::ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
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
379 bool ThreadPlanCallFunction::ShouldStop(Event *event_ptr) {
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
393 bool ThreadPlanCallFunction::StopOthers() { return m_stop_other_threads; }
394
395 StateType ThreadPlanCallFunction::GetPlanRunState() { return eStateRunning; }
396
397 void ThreadPlanCallFunction::DidPush() {
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
404   GetThread().SetStopInfoToNothing();
405
406 #ifndef SINGLE_STEP_EXPRESSIONS
407   m_subplan_sp = std::make_shared<ThreadPlanRunToAddress>(
408       m_thread, m_start_addr, m_stop_other_threads);
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
417 bool ThreadPlanCallFunction::MischiefManaged() {
418   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
419
420   if (IsPlanComplete()) {
421     if (log)
422       log->Printf("ThreadPlanCallFunction(%p): Completed call function plan.",
423                   static_cast<void *>(this));
424
425     ThreadPlan::MischiefManaged();
426     return true;
427   } else {
428     return false;
429   }
430 }
431
432 void ThreadPlanCallFunction::SetBreakpoints() {
433   ProcessSP process_sp(m_thread.CalculateProcess());
434   if (m_trap_exceptions && process_sp) {
435     m_cxx_language_runtime =
436         process_sp->GetLanguageRuntime(eLanguageTypeC_plus_plus);
437     m_objc_language_runtime = process_sp->GetLanguageRuntime(eLanguageTypeObjC);
438
439     if (m_cxx_language_runtime) {
440       m_should_clear_cxx_exception_bp =
441           !m_cxx_language_runtime->ExceptionBreakpointsAreSet();
442       m_cxx_language_runtime->SetExceptionBreakpoints();
443     }
444     if (m_objc_language_runtime) {
445       m_should_clear_objc_exception_bp =
446           !m_objc_language_runtime->ExceptionBreakpointsAreSet();
447       m_objc_language_runtime->SetExceptionBreakpoints();
448     }
449   }
450 }
451
452 void ThreadPlanCallFunction::ClearBreakpoints() {
453   if (m_trap_exceptions) {
454     if (m_cxx_language_runtime && m_should_clear_cxx_exception_bp)
455       m_cxx_language_runtime->ClearExceptionBreakpoints();
456     if (m_objc_language_runtime && m_should_clear_objc_exception_bp)
457       m_objc_language_runtime->ClearExceptionBreakpoints();
458   }
459 }
460
461 bool ThreadPlanCallFunction::BreakpointsExplainStop() {
462   StopInfoSP stop_info_sp = GetPrivateStopInfo();
463
464   if (m_trap_exceptions) {
465     if ((m_cxx_language_runtime &&
466          m_cxx_language_runtime->ExceptionBreakpointsExplainStop(
467              stop_info_sp)) ||
468         (m_objc_language_runtime &&
469          m_objc_language_runtime->ExceptionBreakpointsExplainStop(
470              stop_info_sp))) {
471       Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP));
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
489 void ThreadPlanCallFunction::SetStopOthers(bool new_value) {
490   m_subplan_sp->SetStopOthers(new_value);
491 }
492
493 bool ThreadPlanCallFunction::RestoreThreadState() {
494   return GetThread().RestoreThreadStateFromCheckpoint(m_stored_thread_state);
495 }
496
497 void ThreadPlanCallFunction::SetReturnValue() {
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;
502     m_return_valobj_sp =
503         abi->GetReturnValueObject(m_thread, m_return_type, persistent);
504   }
505 }