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::ValueObjectSP UserExpression::GetObjectPointerValueObject(
102     lldb::StackFrameSP frame_sp, ConstString const &object_name, Status &err) {
103   err.Clear();
104 
105   if (!frame_sp) {
106     err.SetErrorStringWithFormat(
107         "Couldn't load '%s' because the context is incomplete",
108         object_name.AsCString());
109     return {};
110   }
111 
112   lldb::VariableSP var_sp;
113   lldb::ValueObjectSP valobj_sp;
114 
115   return frame_sp->GetValueForVariableExpressionPath(
116       object_name.GetStringRef(), lldb::eNoDynamicValues,
117       StackFrame::eExpressionPathOptionCheckPtrVsMember |
118           StackFrame::eExpressionPathOptionsNoFragileObjcIvar |
119           StackFrame::eExpressionPathOptionsNoSyntheticChildren |
120           StackFrame::eExpressionPathOptionsNoSyntheticArrayRange,
121       var_sp, err);
122 }
123 
124 lldb::addr_t UserExpression::GetObjectPointer(lldb::StackFrameSP frame_sp,
125                                               ConstString &object_name,
126                                               Status &err) {
127   auto valobj_sp =
128       GetObjectPointerValueObject(std::move(frame_sp), object_name, err);
129 
130   if (!err.Success() || !valobj_sp.get())
131     return LLDB_INVALID_ADDRESS;
132 
133   lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
134 
135   if (ret == LLDB_INVALID_ADDRESS) {
136     err.SetErrorStringWithFormat(
137         "Couldn't load '%s' because its value couldn't be evaluated",
138         object_name.AsCString());
139     return LLDB_INVALID_ADDRESS;
140   }
141 
142   return ret;
143 }
144 
145 lldb::ExpressionResults
146 UserExpression::Evaluate(ExecutionContext &exe_ctx,
147                          const EvaluateExpressionOptions &options,
148                          llvm::StringRef expr, llvm::StringRef prefix,
149                          lldb::ValueObjectSP &result_valobj_sp, Status &error,
150                          std::string *fixed_expression, ValueObject *ctx_obj) {
151   Log *log(GetLog(LLDBLog::Expressions | LLDBLog::Step));
152 
153   if (ctx_obj) {
154     static unsigned const ctx_type_mask = lldb::TypeFlags::eTypeIsClass |
155                                           lldb::TypeFlags::eTypeIsStructUnion |
156                                           lldb::TypeFlags::eTypeIsReference;
157     if (!(ctx_obj->GetTypeInfo() & ctx_type_mask)) {
158       LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of "
159                     "an invalid type, can't run expressions.");
160       error.SetErrorString("a context object of an invalid type passed");
161       return lldb::eExpressionSetupError;
162     }
163   }
164 
165   if (ctx_obj && ctx_obj->GetTypeInfo() & lldb::TypeFlags::eTypeIsReference) {
166     Status error;
167     lldb::ValueObjectSP deref_ctx_sp = ctx_obj->Dereference(error);
168     if (!error.Success()) {
169       LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of "
170                     "a reference type that can't be dereferenced, can't run "
171                     "expressions.");
172       error.SetErrorString(
173           "passed context object of an reference type cannot be deferenced");
174       return lldb::eExpressionSetupError;
175     }
176 
177     ctx_obj = deref_ctx_sp.get();
178   }
179 
180   lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy();
181   lldb::LanguageType language = options.GetLanguage();
182   const ResultType desired_type = options.DoesCoerceToId()
183                                       ? UserExpression::eResultTypeId
184                                       : UserExpression::eResultTypeAny;
185   lldb::ExpressionResults execution_results = lldb::eExpressionSetupError;
186 
187   Target *target = exe_ctx.GetTargetPtr();
188   if (!target) {
189     LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a NULL target, can't "
190                   "run expressions.");
191     error.SetErrorString("expression passed a null target");
192     return lldb::eExpressionSetupError;
193   }
194 
195   Process *process = exe_ctx.GetProcessPtr();
196 
197   if (process == nullptr || process->GetState() != lldb::eStateStopped) {
198     if (execution_policy == eExecutionPolicyAlways) {
199       LLDB_LOG(log, "== [UserExpression::Evaluate] Expression may not run, but "
200                     "is not constant ==");
201 
202       error.SetErrorString("expression needed to run but couldn't");
203 
204       return execution_results;
205     }
206   }
207 
208   // Explicitly force the IR interpreter to evaluate the expression when the
209   // there is no process that supports running the expression for us. Don't
210   // change the execution policy if we have the special top-level policy that
211   // doesn't contain any expression and there is nothing to interpret.
212   if (execution_policy != eExecutionPolicyTopLevel &&
213       (process == nullptr || !process->CanJIT()))
214     execution_policy = eExecutionPolicyNever;
215 
216   // We need to set the expression execution thread here, turns out parse can
217   // call functions in the process of looking up symbols, which will escape the
218   // context set by exe_ctx passed to Execute.
219   lldb::ThreadSP thread_sp = exe_ctx.GetThreadSP();
220   ThreadList::ExpressionExecutionThreadPusher execution_thread_pusher(
221       thread_sp);
222 
223   llvm::StringRef full_prefix;
224   llvm::StringRef option_prefix(options.GetPrefix());
225   std::string full_prefix_storage;
226   if (!prefix.empty() && !option_prefix.empty()) {
227     full_prefix_storage = std::string(prefix);
228     full_prefix_storage.append(std::string(option_prefix));
229     full_prefix = full_prefix_storage;
230   } else if (!prefix.empty())
231     full_prefix = prefix;
232   else
233     full_prefix = option_prefix;
234 
235   // If the language was not specified in the expression command, set it to the
236   // language in the target's properties if specified, else default to the
237   // langage for the frame.
238   if (language == lldb::eLanguageTypeUnknown) {
239     if (target->GetLanguage() != lldb::eLanguageTypeUnknown)
240       language = target->GetLanguage();
241     else if (StackFrame *frame = exe_ctx.GetFramePtr())
242       language = frame->GetLanguage();
243   }
244 
245   lldb::UserExpressionSP user_expression_sp(
246       target->GetUserExpressionForLanguage(expr, full_prefix, language,
247                                            desired_type, options, ctx_obj,
248                                            error));
249   if (error.Fail()) {
250     LLDB_LOG(log, "== [UserExpression::Evaluate] Getting expression: {0} ==",
251              error.AsCString());
252     return lldb::eExpressionSetupError;
253   }
254 
255   LLDB_LOG(log, "== [UserExpression::Evaluate] Parsing expression {0} ==",
256            expr.str());
257 
258   const bool keep_expression_in_memory = true;
259   const bool generate_debug_info = options.GetGenerateDebugInfo();
260 
261   if (options.InvokeCancelCallback(lldb::eExpressionEvaluationParse)) {
262     error.SetErrorString("expression interrupted by callback before parse");
263     result_valobj_sp = ValueObjectConstResult::Create(
264         exe_ctx.GetBestExecutionContextScope(), error);
265     return lldb::eExpressionInterrupted;
266   }
267 
268   DiagnosticManager diagnostic_manager;
269 
270   bool parse_success =
271       user_expression_sp->Parse(diagnostic_manager, exe_ctx, execution_policy,
272                                 keep_expression_in_memory, generate_debug_info);
273 
274   // Calculate the fixed expression always, since we need it for errors.
275   std::string tmp_fixed_expression;
276   if (fixed_expression == nullptr)
277     fixed_expression = &tmp_fixed_expression;
278 
279   *fixed_expression = user_expression_sp->GetFixedText().str();
280 
281   // If there is a fixed expression, try to parse it:
282   if (!parse_success) {
283     // Delete the expression that failed to parse before attempting to parse
284     // the next expression.
285     user_expression_sp.reset();
286 
287     execution_results = lldb::eExpressionParseError;
288     if (!fixed_expression->empty() && options.GetAutoApplyFixIts()) {
289       const uint64_t max_fix_retries = options.GetRetriesWithFixIts();
290       for (uint64_t i = 0; i < max_fix_retries; ++i) {
291         // Try parsing the fixed expression.
292         lldb::UserExpressionSP fixed_expression_sp(
293             target->GetUserExpressionForLanguage(
294                 fixed_expression->c_str(), full_prefix, language, desired_type,
295                 options, ctx_obj, error));
296         DiagnosticManager fixed_diagnostic_manager;
297         parse_success = fixed_expression_sp->Parse(
298             fixed_diagnostic_manager, exe_ctx, execution_policy,
299             keep_expression_in_memory, generate_debug_info);
300         if (parse_success) {
301           diagnostic_manager.Clear();
302           user_expression_sp = fixed_expression_sp;
303           break;
304         } else {
305           // The fixed expression also didn't parse. Let's check for any new
306           // Fix-Its we could try.
307           if (!fixed_expression_sp->GetFixedText().empty()) {
308             *fixed_expression = fixed_expression_sp->GetFixedText().str();
309           } else {
310             // Fixed expression didn't compile without a fixit, don't retry and
311             // don't tell the user about it.
312             fixed_expression->clear();
313             break;
314           }
315         }
316       }
317     }
318 
319     if (!parse_success) {
320       std::string msg;
321       {
322         llvm::raw_string_ostream os(msg);
323         os << "expression failed to parse:\n";
324         if (!diagnostic_manager.Diagnostics().empty())
325           os << diagnostic_manager.GetString();
326         else
327           os << "unknown error";
328         if (target->GetEnableNotifyAboutFixIts() && fixed_expression &&
329             !fixed_expression->empty())
330           os << "\nfixed expression suggested:\n  " << *fixed_expression;
331       }
332       error.SetExpressionError(execution_results, msg.c_str());
333     }
334   }
335 
336   if (parse_success) {
337     lldb::ExpressionVariableSP expr_result;
338 
339     if (execution_policy == eExecutionPolicyNever &&
340         !user_expression_sp->CanInterpret()) {
341       LLDB_LOG(log, "== [UserExpression::Evaluate] Expression may not run, but "
342                     "is not constant ==");
343 
344       if (!diagnostic_manager.Diagnostics().size())
345         error.SetExpressionError(lldb::eExpressionSetupError,
346                                  "expression needed to run but couldn't");
347     } else if (execution_policy == eExecutionPolicyTopLevel) {
348       error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric);
349       return lldb::eExpressionCompleted;
350     } else {
351       if (options.InvokeCancelCallback(lldb::eExpressionEvaluationExecution)) {
352         error.SetExpressionError(
353             lldb::eExpressionInterrupted,
354             "expression interrupted by callback before execution");
355         result_valobj_sp = ValueObjectConstResult::Create(
356             exe_ctx.GetBestExecutionContextScope(), error);
357         return lldb::eExpressionInterrupted;
358       }
359 
360       diagnostic_manager.Clear();
361 
362       LLDB_LOG(log, "== [UserExpression::Evaluate] Executing expression ==");
363 
364       execution_results =
365           user_expression_sp->Execute(diagnostic_manager, exe_ctx, options,
366                                       user_expression_sp, expr_result);
367 
368       if (execution_results != lldb::eExpressionCompleted) {
369         LLDB_LOG(log, "== [UserExpression::Evaluate] Execution completed "
370                       "abnormally ==");
371 
372         if (!diagnostic_manager.Diagnostics().size())
373           error.SetExpressionError(
374               execution_results, "expression failed to execute, unknown error");
375         else
376           error.SetExpressionError(execution_results,
377                                    diagnostic_manager.GetString().c_str());
378       } else {
379         if (expr_result) {
380           result_valobj_sp = expr_result->GetValueObject();
381           result_valobj_sp->SetPreferredDisplayLanguage(language);
382 
383           LLDB_LOG(log,
384                    "== [UserExpression::Evaluate] Execution completed "
385                    "normally with result {0} ==",
386                    result_valobj_sp->GetValueAsCString());
387         } else {
388           LLDB_LOG(log, "== [UserExpression::Evaluate] Execution completed "
389                         "normally with no result ==");
390 
391           error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric);
392         }
393       }
394     }
395   }
396 
397   if (options.InvokeCancelCallback(lldb::eExpressionEvaluationComplete)) {
398     error.SetExpressionError(
399         lldb::eExpressionInterrupted,
400         "expression interrupted by callback after complete");
401     return lldb::eExpressionInterrupted;
402   }
403 
404   if (result_valobj_sp.get() == nullptr) {
405     result_valobj_sp = ValueObjectConstResult::Create(
406         exe_ctx.GetBestExecutionContextScope(), error);
407   }
408 
409   return execution_results;
410 }
411 
412 lldb::ExpressionResults
413 UserExpression::Execute(DiagnosticManager &diagnostic_manager,
414                         ExecutionContext &exe_ctx,
415                         const EvaluateExpressionOptions &options,
416                         lldb::UserExpressionSP &shared_ptr_to_me,
417                         lldb::ExpressionVariableSP &result_var) {
418   lldb::ExpressionResults expr_result = DoExecute(
419       diagnostic_manager, exe_ctx, options, shared_ptr_to_me, result_var);
420   Target *target = exe_ctx.GetTargetPtr();
421   if (options.GetResultIsInternal() && result_var && target) {
422     if (auto *persistent_state =
423             target->GetPersistentExpressionStateForLanguage(m_language))
424       persistent_state->RemovePersistentVariable(result_var);
425   }
426   return expr_result;
427 }
428