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