xref: /freebsd-src/contrib/llvm-project/lldb/source/Expression/UserExpression.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
1 //===-- UserExpression.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 <cstdio>
10 #include <sys/types.h>
11 
12 #include <cstdlib>
13 #include <map>
14 #include <string>
15 
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/StreamFile.h"
18 #include "lldb/Core/ValueObjectConstResult.h"
19 #include "lldb/Expression/DiagnosticManager.h"
20 #include "lldb/Expression/ExpressionVariable.h"
21 #include "lldb/Expression/IRExecutionUnit.h"
22 #include "lldb/Expression/IRInterpreter.h"
23 #include "lldb/Expression/Materializer.h"
24 #include "lldb/Expression/UserExpression.h"
25 #include "lldb/Host/HostInfo.h"
26 #include "lldb/Symbol/Block.h"
27 #include "lldb/Symbol/Function.h"
28 #include "lldb/Symbol/ObjectFile.h"
29 #include "lldb/Symbol/SymbolVendor.h"
30 #include "lldb/Symbol/Type.h"
31 #include "lldb/Symbol/TypeSystem.h"
32 #include "lldb/Symbol/VariableList.h"
33 #include "lldb/Target/ExecutionContext.h"
34 #include "lldb/Target/Process.h"
35 #include "lldb/Target/StackFrame.h"
36 #include "lldb/Target/Target.h"
37 #include "lldb/Target/ThreadPlan.h"
38 #include "lldb/Target/ThreadPlanCallUserExpression.h"
39 #include "lldb/Utility/ConstString.h"
40 #include "lldb/Utility/LLDBLog.h"
41 #include "lldb/Utility/Log.h"
42 #include "lldb/Utility/StreamString.h"
43 
44 using namespace lldb_private;
45 
46 char UserExpression::ID;
47 
48 UserExpression::UserExpression(ExecutionContextScope &exe_scope,
49                                llvm::StringRef expr, llvm::StringRef prefix,
50                                lldb::LanguageType language,
51                                ResultType desired_type,
52                                const EvaluateExpressionOptions &options)
53     : Expression(exe_scope), m_expr_text(std::string(expr)),
54       m_expr_prefix(std::string(prefix)), m_language(language),
55       m_desired_type(desired_type), m_options(options) {}
56 
57 UserExpression::~UserExpression() = default;
58 
59 void UserExpression::InstallContext(ExecutionContext &exe_ctx) {
60   m_jit_process_wp = exe_ctx.GetProcessSP();
61 
62   lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
63 
64   if (frame_sp)
65     m_address = frame_sp->GetFrameCodeAddress();
66 }
67 
68 bool UserExpression::LockAndCheckContext(ExecutionContext &exe_ctx,
69                                          lldb::TargetSP &target_sp,
70                                          lldb::ProcessSP &process_sp,
71                                          lldb::StackFrameSP &frame_sp) {
72   lldb::ProcessSP expected_process_sp = m_jit_process_wp.lock();
73   process_sp = exe_ctx.GetProcessSP();
74 
75   if (process_sp != expected_process_sp)
76     return false;
77 
78   process_sp = exe_ctx.GetProcessSP();
79   target_sp = exe_ctx.GetTargetSP();
80   frame_sp = exe_ctx.GetFrameSP();
81 
82   if (m_address.IsValid()) {
83     if (!frame_sp)
84       return false;
85     return (Address::CompareLoadAddress(m_address,
86                                         frame_sp->GetFrameCodeAddress(),
87                                         target_sp.get()) == 0);
88   }
89 
90   return true;
91 }
92 
93 bool UserExpression::MatchesContext(ExecutionContext &exe_ctx) {
94   lldb::TargetSP target_sp;
95   lldb::ProcessSP process_sp;
96   lldb::StackFrameSP frame_sp;
97 
98   return LockAndCheckContext(exe_ctx, target_sp, process_sp, frame_sp);
99 }
100 
101 lldb::addr_t UserExpression::GetObjectPointer(lldb::StackFrameSP frame_sp,
102                                               ConstString &object_name,
103                                               Status &err) {
104   err.Clear();
105 
106   if (!frame_sp) {
107     err.SetErrorStringWithFormat(
108         "Couldn't load '%s' because the context is incomplete",
109         object_name.AsCString());
110     return LLDB_INVALID_ADDRESS;
111   }
112 
113   lldb::VariableSP var_sp;
114   lldb::ValueObjectSP valobj_sp;
115 
116   valobj_sp = frame_sp->GetValueForVariableExpressionPath(
117       object_name.GetStringRef(), lldb::eNoDynamicValues,
118       StackFrame::eExpressionPathOptionCheckPtrVsMember |
119           StackFrame::eExpressionPathOptionsNoFragileObjcIvar |
120           StackFrame::eExpressionPathOptionsNoSyntheticChildren |
121           StackFrame::eExpressionPathOptionsNoSyntheticArrayRange,
122       var_sp, err);
123 
124   if (!err.Success() || !valobj_sp.get())
125     return LLDB_INVALID_ADDRESS;
126 
127   lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
128 
129   if (ret == LLDB_INVALID_ADDRESS) {
130     err.SetErrorStringWithFormat(
131         "Couldn't load '%s' because its value couldn't be evaluated",
132         object_name.AsCString());
133     return LLDB_INVALID_ADDRESS;
134   }
135 
136   return ret;
137 }
138 
139 lldb::ExpressionResults
140 UserExpression::Evaluate(ExecutionContext &exe_ctx,
141                          const EvaluateExpressionOptions &options,
142                          llvm::StringRef expr, llvm::StringRef prefix,
143                          lldb::ValueObjectSP &result_valobj_sp, Status &error,
144                          std::string *fixed_expression, ValueObject *ctx_obj) {
145   Log *log(GetLog(LLDBLog::Expressions | LLDBLog::Step));
146 
147   if (ctx_obj) {
148     static unsigned const ctx_type_mask = lldb::TypeFlags::eTypeIsClass |
149                                           lldb::TypeFlags::eTypeIsStructUnion |
150                                           lldb::TypeFlags::eTypeIsReference;
151     if (!(ctx_obj->GetTypeInfo() & ctx_type_mask)) {
152       LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of "
153                     "an invalid type, can't run expressions.");
154       error.SetErrorString("a context object of an invalid type passed");
155       return lldb::eExpressionSetupError;
156     }
157   }
158 
159   if (ctx_obj && ctx_obj->GetTypeInfo() & lldb::TypeFlags::eTypeIsReference) {
160     Status error;
161     lldb::ValueObjectSP deref_ctx_sp = ctx_obj->Dereference(error);
162     if (!error.Success()) {
163       LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of "
164                     "a reference type that can't be dereferenced, can't run "
165                     "expressions.");
166       error.SetErrorString(
167           "passed context object of an reference type cannot be deferenced");
168       return lldb::eExpressionSetupError;
169     }
170 
171     ctx_obj = deref_ctx_sp.get();
172   }
173 
174   lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy();
175   lldb::LanguageType language = options.GetLanguage();
176   const ResultType desired_type = options.DoesCoerceToId()
177                                       ? UserExpression::eResultTypeId
178                                       : UserExpression::eResultTypeAny;
179   lldb::ExpressionResults execution_results = lldb::eExpressionSetupError;
180 
181   Target *target = exe_ctx.GetTargetPtr();
182   if (!target) {
183     LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a NULL target, can't "
184                   "run expressions.");
185     error.SetErrorString("expression passed a null target");
186     return lldb::eExpressionSetupError;
187   }
188 
189   Process *process = exe_ctx.GetProcessPtr();
190 
191   if (process == nullptr || process->GetState() != lldb::eStateStopped) {
192     if (execution_policy == eExecutionPolicyAlways) {
193       LLDB_LOG(log, "== [UserExpression::Evaluate] Expression may not run, but "
194                     "is not constant ==");
195 
196       error.SetErrorString("expression needed to run but couldn't");
197 
198       return execution_results;
199     }
200   }
201 
202   // Explicitly force the IR interpreter to evaluate the expression when the
203   // there is no process that supports running the expression for us. Don't
204   // change the execution policy if we have the special top-level policy that
205   // doesn't contain any expression and there is nothing to interpret.
206   if (execution_policy != eExecutionPolicyTopLevel &&
207       (process == nullptr || !process->CanJIT()))
208     execution_policy = eExecutionPolicyNever;
209 
210   // We need to set the expression execution thread here, turns out parse can
211   // call functions in the process of looking up symbols, which will escape the
212   // context set by exe_ctx passed to Execute.
213   lldb::ThreadSP thread_sp = exe_ctx.GetThreadSP();
214   ThreadList::ExpressionExecutionThreadPusher execution_thread_pusher(
215       thread_sp);
216 
217   llvm::StringRef full_prefix;
218   llvm::StringRef option_prefix(options.GetPrefix());
219   std::string full_prefix_storage;
220   if (!prefix.empty() && !option_prefix.empty()) {
221     full_prefix_storage = std::string(prefix);
222     full_prefix_storage.append(std::string(option_prefix));
223     full_prefix = full_prefix_storage;
224   } else if (!prefix.empty())
225     full_prefix = prefix;
226   else
227     full_prefix = option_prefix;
228 
229   // If the language was not specified in the expression command, set it to the
230   // language in the target's properties if specified, else default to the
231   // langage for the frame.
232   if (language == lldb::eLanguageTypeUnknown) {
233     if (target->GetLanguage() != lldb::eLanguageTypeUnknown)
234       language = target->GetLanguage();
235     else if (StackFrame *frame = exe_ctx.GetFramePtr())
236       language = frame->GetLanguage();
237   }
238 
239   lldb::UserExpressionSP user_expression_sp(
240       target->GetUserExpressionForLanguage(expr, full_prefix, language,
241                                            desired_type, options, ctx_obj,
242                                            error));
243   if (error.Fail()) {
244     LLDB_LOG(log, "== [UserExpression::Evaluate] Getting expression: {0} ==",
245              error.AsCString());
246     return lldb::eExpressionSetupError;
247   }
248 
249   LLDB_LOG(log, "== [UserExpression::Evaluate] Parsing expression {0} ==",
250            expr.str());
251 
252   const bool keep_expression_in_memory = true;
253   const bool generate_debug_info = options.GetGenerateDebugInfo();
254 
255   if (options.InvokeCancelCallback(lldb::eExpressionEvaluationParse)) {
256     error.SetErrorString("expression interrupted by callback before parse");
257     result_valobj_sp = ValueObjectConstResult::Create(
258         exe_ctx.GetBestExecutionContextScope(), error);
259     return lldb::eExpressionInterrupted;
260   }
261 
262   DiagnosticManager diagnostic_manager;
263 
264   bool parse_success =
265       user_expression_sp->Parse(diagnostic_manager, exe_ctx, execution_policy,
266                                 keep_expression_in_memory, generate_debug_info);
267 
268   // Calculate the fixed expression always, since we need it for errors.
269   std::string tmp_fixed_expression;
270   if (fixed_expression == nullptr)
271     fixed_expression = &tmp_fixed_expression;
272 
273   *fixed_expression = user_expression_sp->GetFixedText().str();
274 
275   // If there is a fixed expression, try to parse it:
276   if (!parse_success) {
277     // Delete the expression that failed to parse before attempting to parse
278     // the next expression.
279     user_expression_sp.reset();
280 
281     execution_results = lldb::eExpressionParseError;
282     if (!fixed_expression->empty() && options.GetAutoApplyFixIts()) {
283       const uint64_t max_fix_retries = options.GetRetriesWithFixIts();
284       for (uint64_t i = 0; i < max_fix_retries; ++i) {
285         // Try parsing the fixed expression.
286         lldb::UserExpressionSP fixed_expression_sp(
287             target->GetUserExpressionForLanguage(
288                 fixed_expression->c_str(), full_prefix, language, desired_type,
289                 options, ctx_obj, error));
290         DiagnosticManager fixed_diagnostic_manager;
291         parse_success = fixed_expression_sp->Parse(
292             fixed_diagnostic_manager, exe_ctx, execution_policy,
293             keep_expression_in_memory, generate_debug_info);
294         if (parse_success) {
295           diagnostic_manager.Clear();
296           user_expression_sp = fixed_expression_sp;
297           break;
298         } else {
299           // The fixed expression also didn't parse. Let's check for any new
300           // Fix-Its we could try.
301           if (!fixed_expression_sp->GetFixedText().empty()) {
302             *fixed_expression = fixed_expression_sp->GetFixedText().str();
303           } else {
304             // Fixed expression didn't compile without a fixit, don't retry and
305             // don't tell the user about it.
306             fixed_expression->clear();
307             break;
308           }
309         }
310       }
311     }
312 
313     if (!parse_success) {
314       std::string msg;
315       {
316         llvm::raw_string_ostream os(msg);
317         os << "expression failed to parse:\n";
318         if (!diagnostic_manager.Diagnostics().empty())
319           os << diagnostic_manager.GetString();
320         else
321           os << "unknown error";
322         if (target->GetEnableNotifyAboutFixIts() && fixed_expression &&
323             !fixed_expression->empty())
324           os << "\nfixed expression suggested:\n  " << *fixed_expression;
325       }
326       error.SetExpressionError(execution_results, msg.c_str());
327     }
328   }
329 
330   if (parse_success) {
331     lldb::ExpressionVariableSP expr_result;
332 
333     if (execution_policy == eExecutionPolicyNever &&
334         !user_expression_sp->CanInterpret()) {
335       LLDB_LOG(log, "== [UserExpression::Evaluate] Expression may not run, but "
336                     "is not constant ==");
337 
338       if (!diagnostic_manager.Diagnostics().size())
339         error.SetExpressionError(lldb::eExpressionSetupError,
340                                  "expression needed to run but couldn't");
341     } else if (execution_policy == eExecutionPolicyTopLevel) {
342       error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric);
343       return lldb::eExpressionCompleted;
344     } else {
345       if (options.InvokeCancelCallback(lldb::eExpressionEvaluationExecution)) {
346         error.SetExpressionError(
347             lldb::eExpressionInterrupted,
348             "expression interrupted by callback before execution");
349         result_valobj_sp = ValueObjectConstResult::Create(
350             exe_ctx.GetBestExecutionContextScope(), error);
351         return lldb::eExpressionInterrupted;
352       }
353 
354       diagnostic_manager.Clear();
355 
356       LLDB_LOG(log, "== [UserExpression::Evaluate] Executing expression ==");
357 
358       execution_results =
359           user_expression_sp->Execute(diagnostic_manager, exe_ctx, options,
360                                       user_expression_sp, expr_result);
361 
362       if (execution_results != lldb::eExpressionCompleted) {
363         LLDB_LOG(log, "== [UserExpression::Evaluate] Execution completed "
364                       "abnormally ==");
365 
366         if (!diagnostic_manager.Diagnostics().size())
367           error.SetExpressionError(
368               execution_results, "expression failed to execute, unknown error");
369         else
370           error.SetExpressionError(execution_results,
371                                    diagnostic_manager.GetString().c_str());
372       } else {
373         if (expr_result) {
374           result_valobj_sp = expr_result->GetValueObject();
375           result_valobj_sp->SetPreferredDisplayLanguage(language);
376 
377           LLDB_LOG(log,
378                    "== [UserExpression::Evaluate] Execution completed "
379                    "normally with result {0} ==",
380                    result_valobj_sp->GetValueAsCString());
381         } else {
382           LLDB_LOG(log, "== [UserExpression::Evaluate] Execution completed "
383                         "normally with no result ==");
384 
385           error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric);
386         }
387       }
388     }
389   }
390 
391   if (options.InvokeCancelCallback(lldb::eExpressionEvaluationComplete)) {
392     error.SetExpressionError(
393         lldb::eExpressionInterrupted,
394         "expression interrupted by callback after complete");
395     return lldb::eExpressionInterrupted;
396   }
397 
398   if (result_valobj_sp.get() == nullptr) {
399     result_valobj_sp = ValueObjectConstResult::Create(
400         exe_ctx.GetBestExecutionContextScope(), error);
401   }
402 
403   return execution_results;
404 }
405 
406 lldb::ExpressionResults
407 UserExpression::Execute(DiagnosticManager &diagnostic_manager,
408                         ExecutionContext &exe_ctx,
409                         const EvaluateExpressionOptions &options,
410                         lldb::UserExpressionSP &shared_ptr_to_me,
411                         lldb::ExpressionVariableSP &result_var) {
412   lldb::ExpressionResults expr_result = DoExecute(
413       diagnostic_manager, exe_ctx, options, shared_ptr_to_me, result_var);
414   Target *target = exe_ctx.GetTargetPtr();
415   if (options.GetResultIsInternal() && result_var && target) {
416     if (auto *persistent_state =
417             target->GetPersistentExpressionStateForLanguage(m_language))
418       persistent_state->RemovePersistentVariable(result_var);
419   }
420   return expr_result;
421 }
422