1 //===-- UserExpression.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/Host/Config.h"
10 
11 #include <stdio.h>
12 #if HAVE_SYS_TYPES_H
13 #include <sys/types.h>
14 #endif
15 
16 #include <cstdlib>
17 #include <map>
18 #include <string>
19 
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/StreamFile.h"
22 #include "lldb/Core/ValueObjectConstResult.h"
23 #include "lldb/Expression/DiagnosticManager.h"
24 #include "lldb/Expression/ExpressionVariable.h"
25 #include "lldb/Expression/IRExecutionUnit.h"
26 #include "lldb/Expression/IRInterpreter.h"
27 #include "lldb/Expression/Materializer.h"
28 #include "lldb/Expression/UserExpression.h"
29 #include "lldb/Host/HostInfo.h"
30 #include "lldb/Symbol/Block.h"
31 #include "lldb/Symbol/Function.h"
32 #include "lldb/Symbol/ObjectFile.h"
33 #include "lldb/Symbol/SymbolVendor.h"
34 #include "lldb/Symbol/Type.h"
35 #include "lldb/Symbol/TypeSystem.h"
36 #include "lldb/Symbol/VariableList.h"
37 #include "lldb/Target/ExecutionContext.h"
38 #include "lldb/Target/Process.h"
39 #include "lldb/Target/StackFrame.h"
40 #include "lldb/Target/Target.h"
41 #include "lldb/Target/ThreadPlan.h"
42 #include "lldb/Target/ThreadPlanCallUserExpression.h"
43 #include "lldb/Utility/ConstString.h"
44 #include "lldb/Utility/Log.h"
45 #include "lldb/Utility/StreamString.h"
46 
47 using namespace lldb_private;
48 
49 char UserExpression::ID;
50 
51 UserExpression::UserExpression(ExecutionContextScope &exe_scope,
52                                llvm::StringRef expr, llvm::StringRef prefix,
53                                lldb::LanguageType language,
54                                ResultType desired_type,
55                                const EvaluateExpressionOptions &options)
56     : Expression(exe_scope), m_expr_text(expr), m_expr_prefix(prefix),
57       m_language(language), m_desired_type(desired_type), m_options(options) {}
58 
59 UserExpression::~UserExpression() {}
60 
61 void UserExpression::InstallContext(ExecutionContext &exe_ctx) {
62   m_jit_process_wp = exe_ctx.GetProcessSP();
63 
64   lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
65 
66   if (frame_sp)
67     m_address = frame_sp->GetFrameCodeAddress();
68 }
69 
70 bool UserExpression::LockAndCheckContext(ExecutionContext &exe_ctx,
71                                          lldb::TargetSP &target_sp,
72                                          lldb::ProcessSP &process_sp,
73                                          lldb::StackFrameSP &frame_sp) {
74   lldb::ProcessSP expected_process_sp = m_jit_process_wp.lock();
75   process_sp = exe_ctx.GetProcessSP();
76 
77   if (process_sp != expected_process_sp)
78     return false;
79 
80   process_sp = exe_ctx.GetProcessSP();
81   target_sp = exe_ctx.GetTargetSP();
82   frame_sp = exe_ctx.GetFrameSP();
83 
84   if (m_address.IsValid()) {
85     if (!frame_sp)
86       return false;
87     return (Address::CompareLoadAddress(m_address,
88                                         frame_sp->GetFrameCodeAddress(),
89                                         target_sp.get()) == 0);
90   }
91 
92   return true;
93 }
94 
95 bool UserExpression::MatchesContext(ExecutionContext &exe_ctx) {
96   lldb::TargetSP target_sp;
97   lldb::ProcessSP process_sp;
98   lldb::StackFrameSP frame_sp;
99 
100   return LockAndCheckContext(exe_ctx, target_sp, process_sp, frame_sp);
101 }
102 
103 lldb::addr_t UserExpression::GetObjectPointer(lldb::StackFrameSP frame_sp,
104                                               ConstString &object_name,
105                                               Status &err) {
106   err.Clear();
107 
108   if (!frame_sp) {
109     err.SetErrorStringWithFormat(
110         "Couldn't load '%s' because the context is incomplete",
111         object_name.AsCString());
112     return LLDB_INVALID_ADDRESS;
113   }
114 
115   lldb::VariableSP var_sp;
116   lldb::ValueObjectSP valobj_sp;
117 
118   valobj_sp = frame_sp->GetValueForVariableExpressionPath(
119       object_name.AsCString(), lldb::eNoDynamicValues,
120       StackFrame::eExpressionPathOptionCheckPtrVsMember |
121           StackFrame::eExpressionPathOptionsNoFragileObjcIvar |
122           StackFrame::eExpressionPathOptionsNoSyntheticChildren |
123           StackFrame::eExpressionPathOptionsNoSyntheticArrayRange,
124       var_sp, err);
125 
126   if (!err.Success() || !valobj_sp.get())
127     return LLDB_INVALID_ADDRESS;
128 
129   lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
130 
131   if (ret == LLDB_INVALID_ADDRESS) {
132     err.SetErrorStringWithFormat(
133         "Couldn't load '%s' because its value couldn't be evaluated",
134         object_name.AsCString());
135     return LLDB_INVALID_ADDRESS;
136   }
137 
138   return ret;
139 }
140 
141 lldb::ExpressionResults UserExpression::Evaluate(
142     ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options,
143     llvm::StringRef expr, llvm::StringRef prefix,
144     lldb::ValueObjectSP &result_valobj_sp, Status &error,
145     std::string *fixed_expression, lldb::ModuleSP *jit_module_sp_ptr,
146     ValueObject *ctx_obj) {
147   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS |
148                                                   LIBLLDB_LOG_STEP));
149 
150   if (ctx_obj) {
151     static unsigned const ctx_type_mask =
152         lldb::TypeFlags::eTypeIsClass | lldb::TypeFlags::eTypeIsStructUnion;
153     if (!(ctx_obj->GetTypeInfo() & ctx_type_mask)) {
154       LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of "
155                     "an invalid type, can't run expressions.");
156       error.SetErrorString("a context object of an invalid type passed");
157       return lldb::eExpressionSetupError;
158     }
159   }
160 
161   lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy();
162   lldb::LanguageType language = options.GetLanguage();
163   const ResultType desired_type = options.DoesCoerceToId()
164                                       ? UserExpression::eResultTypeId
165                                       : UserExpression::eResultTypeAny;
166   lldb::ExpressionResults execution_results = lldb::eExpressionSetupError;
167 
168   Target *target = exe_ctx.GetTargetPtr();
169   if (!target) {
170     LLDB_LOGF(log, "== [UserExpression::Evaluate] Passed a NULL target, can't "
171                    "run expressions.");
172     error.SetErrorString("expression passed a null target");
173     return lldb::eExpressionSetupError;
174   }
175 
176   Process *process = exe_ctx.GetProcessPtr();
177 
178   if (process == nullptr || process->GetState() != lldb::eStateStopped) {
179     if (execution_policy == eExecutionPolicyAlways) {
180       LLDB_LOGF(log,
181                 "== [UserExpression::Evaluate] Expression may not run, but "
182                 "is not constant ==");
183 
184       error.SetErrorString("expression needed to run but couldn't");
185 
186       return execution_results;
187     }
188   }
189 
190   if (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 = prefix;
205     full_prefix_storage.append(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     if (log)
228       LLDB_LOGF(log, "== [UserExpression::Evaluate] Getting expression: %s ==",
229                 error.AsCString());
230     return lldb::eExpressionSetupError;
231   }
232 
233   if (log)
234     LLDB_LOGF(log, "== [UserExpression::Evaluate] Parsing expression %s ==",
235               expr.str().c_str());
236 
237   const bool keep_expression_in_memory = true;
238   const bool generate_debug_info = options.GetGenerateDebugInfo();
239 
240   if (options.InvokeCancelCallback(lldb::eExpressionEvaluationParse)) {
241     error.SetErrorString("expression interrupted by callback before parse");
242     result_valobj_sp = ValueObjectConstResult::Create(
243         exe_ctx.GetBestExecutionContextScope(), error);
244     return lldb::eExpressionInterrupted;
245   }
246 
247   DiagnosticManager diagnostic_manager;
248 
249   bool parse_success =
250       user_expression_sp->Parse(diagnostic_manager, exe_ctx, execution_policy,
251                                 keep_expression_in_memory, generate_debug_info);
252 
253   // Calculate the fixed expression always, since we need it for errors.
254   std::string tmp_fixed_expression;
255   if (fixed_expression == nullptr)
256     fixed_expression = &tmp_fixed_expression;
257 
258   const char *fixed_text = user_expression_sp->GetFixedText();
259   if (fixed_text != nullptr)
260     fixed_expression->append(fixed_text);
261 
262   // If there is a fixed expression, try to parse it:
263   if (!parse_success) {
264     execution_results = lldb::eExpressionParseError;
265     if (fixed_expression && !fixed_expression->empty() &&
266         options.GetAutoApplyFixIts()) {
267       lldb::UserExpressionSP fixed_expression_sp(
268           target->GetUserExpressionForLanguage(fixed_expression->c_str(),
269                                                full_prefix, language,
270                                                desired_type, options, ctx_obj,
271                                                error));
272       DiagnosticManager fixed_diagnostic_manager;
273       parse_success = fixed_expression_sp->Parse(
274           fixed_diagnostic_manager, exe_ctx, execution_policy,
275           keep_expression_in_memory, generate_debug_info);
276       if (parse_success) {
277         diagnostic_manager.Clear();
278         user_expression_sp = fixed_expression_sp;
279       } else {
280         // If the fixed expression failed to parse, don't tell the user about,
281         // that won't help.
282         fixed_expression->clear();
283       }
284     }
285 
286     if (!parse_success) {
287       if (!fixed_expression->empty() && target->GetEnableNotifyAboutFixIts()) {
288         error.SetExpressionErrorWithFormat(
289             execution_results,
290             "expression failed to parse, fixed expression suggested:\n  %s",
291             fixed_expression->c_str());
292       } else {
293         if (!diagnostic_manager.Diagnostics().size())
294           error.SetExpressionError(execution_results,
295                                    "expression failed to parse, unknown error");
296         else
297           error.SetExpressionError(execution_results,
298                                    diagnostic_manager.GetString().c_str());
299       }
300     }
301   }
302 
303   if (parse_success) {
304     // If a pointer to a lldb::ModuleSP was passed in, return the JIT'ed module
305     // if one was created
306     if (jit_module_sp_ptr)
307       *jit_module_sp_ptr = user_expression_sp->GetJITModule();
308 
309     lldb::ExpressionVariableSP expr_result;
310 
311     if (execution_policy == eExecutionPolicyNever &&
312         !user_expression_sp->CanInterpret()) {
313       if (log)
314         LLDB_LOGF(log,
315                   "== [UserExpression::Evaluate] Expression may not run, but "
316                   "is not constant ==");
317 
318       if (!diagnostic_manager.Diagnostics().size())
319         error.SetExpressionError(lldb::eExpressionSetupError,
320                                  "expression needed to run but couldn't");
321     } else if (execution_policy == eExecutionPolicyTopLevel) {
322       error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric);
323       return lldb::eExpressionCompleted;
324     } else {
325       if (options.InvokeCancelCallback(lldb::eExpressionEvaluationExecution)) {
326         error.SetExpressionError(
327             lldb::eExpressionInterrupted,
328             "expression interrupted by callback before execution");
329         result_valobj_sp = ValueObjectConstResult::Create(
330             exe_ctx.GetBestExecutionContextScope(), error);
331         return lldb::eExpressionInterrupted;
332       }
333 
334       diagnostic_manager.Clear();
335 
336       if (log)
337         LLDB_LOGF(log, "== [UserExpression::Evaluate] Executing expression ==");
338 
339       execution_results =
340           user_expression_sp->Execute(diagnostic_manager, exe_ctx, options,
341                                       user_expression_sp, expr_result);
342 
343       if (execution_results != lldb::eExpressionCompleted) {
344         if (log)
345           LLDB_LOGF(log, "== [UserExpression::Evaluate] Execution completed "
346                          "abnormally ==");
347 
348         if (!diagnostic_manager.Diagnostics().size())
349           error.SetExpressionError(
350               execution_results, "expression failed to execute, unknown error");
351         else
352           error.SetExpressionError(execution_results,
353                                    diagnostic_manager.GetString().c_str());
354       } else {
355         if (expr_result) {
356           result_valobj_sp = expr_result->GetValueObject();
357 
358           if (log)
359             LLDB_LOGF(log,
360                       "== [UserExpression::Evaluate] Execution completed "
361                       "normally with result %s ==",
362                       result_valobj_sp->GetValueAsCString());
363         } else {
364           if (log)
365             LLDB_LOGF(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