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 <stdio.h>
10 #if HAVE_SYS_TYPES_H
11 #include <sys/types.h>
12 #endif
13 
14 #include <cstdlib>
15 #include <map>
16 #include <string>
17 
18 #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
19 #include "lldb/Core/Module.h"
20 #include "lldb/Core/StreamFile.h"
21 #include "lldb/Core/ValueObjectConstResult.h"
22 #include "lldb/Expression/DiagnosticManager.h"
23 #include "lldb/Expression/ExpressionSourceCode.h"
24 #include "lldb/Expression/IRExecutionUnit.h"
25 #include "lldb/Expression/IRInterpreter.h"
26 #include "lldb/Expression/Materializer.h"
27 #include "lldb/Expression/UserExpression.h"
28 #include "lldb/Host/HostInfo.h"
29 #include "lldb/Symbol/Block.h"
30 #include "lldb/Symbol/Function.h"
31 #include "lldb/Symbol/ObjectFile.h"
32 #include "lldb/Symbol/SymbolVendor.h"
33 #include "lldb/Symbol/Type.h"
34 #include "lldb/Symbol/TypeSystem.h"
35 #include "lldb/Symbol/VariableList.h"
36 #include "lldb/Target/ExecutionContext.h"
37 #include "lldb/Target/Process.h"
38 #include "lldb/Target/StackFrame.h"
39 #include "lldb/Target/Target.h"
40 #include "lldb/Target/ThreadPlan.h"
41 #include "lldb/Target/ThreadPlanCallUserExpression.h"
42 #include "lldb/Utility/ConstString.h"
43 #include "lldb/Utility/Log.h"
44 #include "lldb/Utility/StreamString.h"
45 
46 using namespace lldb_private;
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(expr), m_expr_prefix(prefix),
54       m_language(language), m_desired_type(desired_type), m_options(options) {}
55 
56 UserExpression::~UserExpression() {}
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     else
85       return (0 == Address::CompareLoadAddress(m_address,
86                                                frame_sp->GetFrameCodeAddress(),
87                                                target_sp.get()));
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.AsCString(), 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 UserExpression::Evaluate(
140     ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options,
141     llvm::StringRef expr, llvm::StringRef prefix,
142     lldb::ValueObjectSP &result_valobj_sp, Status &error, uint32_t line_offset,
143     std::string *fixed_expression, lldb::ModuleSP *jit_module_sp_ptr) {
144   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS |
145                                                   LIBLLDB_LOG_STEP));
146 
147   lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy();
148   lldb::LanguageType language = options.GetLanguage();
149   const ResultType desired_type = options.DoesCoerceToId()
150                                       ? UserExpression::eResultTypeId
151                                       : UserExpression::eResultTypeAny;
152   lldb::ExpressionResults execution_results = lldb::eExpressionSetupError;
153 
154   Target *target = exe_ctx.GetTargetPtr();
155   if (!target) {
156     if (log)
157       log->Printf("== [UserExpression::Evaluate] Passed a NULL target, can't "
158                   "run expressions.");
159     error.SetErrorString("expression passed a null target");
160     return lldb::eExpressionSetupError;
161   }
162 
163   Process *process = exe_ctx.GetProcessPtr();
164 
165   if (process == NULL || process->GetState() != lldb::eStateStopped) {
166     if (execution_policy == eExecutionPolicyAlways) {
167       if (log)
168         log->Printf("== [UserExpression::Evaluate] Expression may not run, but "
169                     "is not constant ==");
170 
171       error.SetErrorString("expression needed to run but couldn't");
172 
173       return execution_results;
174     }
175   }
176 
177   if (process == NULL || !process->CanJIT())
178     execution_policy = eExecutionPolicyNever;
179 
180   // We need to set the expression execution thread here, turns out parse can
181   // call functions in the process of looking up symbols, which will escape the
182   // context set by exe_ctx passed to Execute.
183   lldb::ThreadSP thread_sp = exe_ctx.GetThreadSP();
184   ThreadList::ExpressionExecutionThreadPusher execution_thread_pusher(
185       thread_sp);
186 
187   llvm::StringRef full_prefix;
188   llvm::StringRef option_prefix(options.GetPrefix());
189   std::string full_prefix_storage;
190   if (!prefix.empty() && !option_prefix.empty()) {
191     full_prefix_storage = prefix;
192     full_prefix_storage.append(option_prefix);
193     full_prefix = full_prefix_storage;
194   } else if (!prefix.empty())
195     full_prefix = prefix;
196   else
197     full_prefix = option_prefix;
198 
199   // If the language was not specified in the expression command, set it to the
200   // language in the target's properties if specified, else default to the
201   // langage for the frame.
202   if (language == lldb::eLanguageTypeUnknown) {
203     if (target->GetLanguage() != lldb::eLanguageTypeUnknown)
204       language = target->GetLanguage();
205     else if (StackFrame *frame = exe_ctx.GetFramePtr())
206       language = frame->GetLanguage();
207   }
208 
209   lldb::UserExpressionSP user_expression_sp(
210       target->GetUserExpressionForLanguage(expr, full_prefix, language,
211                                            desired_type, options, error));
212   if (error.Fail()) {
213     if (log)
214       log->Printf("== [UserExpression::Evaluate] Getting expression: %s ==",
215                   error.AsCString());
216     return lldb::eExpressionSetupError;
217   }
218 
219   if (log)
220     log->Printf("== [UserExpression::Evaluate] Parsing expression %s ==",
221                 expr.str().c_str());
222 
223   const bool keep_expression_in_memory = true;
224   const bool generate_debug_info = options.GetGenerateDebugInfo();
225 
226   if (options.InvokeCancelCallback(lldb::eExpressionEvaluationParse)) {
227     error.SetErrorString("expression interrupted by callback before parse");
228     result_valobj_sp = ValueObjectConstResult::Create(
229         exe_ctx.GetBestExecutionContextScope(), error);
230     return lldb::eExpressionInterrupted;
231   }
232 
233   DiagnosticManager diagnostic_manager;
234 
235   bool parse_success =
236       user_expression_sp->Parse(diagnostic_manager, exe_ctx, execution_policy,
237                                 keep_expression_in_memory, generate_debug_info);
238 
239   // Calculate the fixed expression always, since we need it for errors.
240   std::string tmp_fixed_expression;
241   if (fixed_expression == nullptr)
242     fixed_expression = &tmp_fixed_expression;
243 
244   const char *fixed_text = user_expression_sp->GetFixedText();
245   if (fixed_text != nullptr)
246     fixed_expression->append(fixed_text);
247 
248   // If there is a fixed expression, try to parse it:
249   if (!parse_success) {
250     execution_results = lldb::eExpressionParseError;
251     if (fixed_expression && !fixed_expression->empty() &&
252         options.GetAutoApplyFixIts()) {
253       lldb::UserExpressionSP fixed_expression_sp(
254           target->GetUserExpressionForLanguage(fixed_expression->c_str(),
255                                                full_prefix, language,
256                                                desired_type, options, error));
257       DiagnosticManager fixed_diagnostic_manager;
258       parse_success = fixed_expression_sp->Parse(
259           fixed_diagnostic_manager, exe_ctx, execution_policy,
260           keep_expression_in_memory, generate_debug_info);
261       if (parse_success) {
262         diagnostic_manager.Clear();
263         user_expression_sp = fixed_expression_sp;
264       } else {
265         // If the fixed expression failed to parse, don't tell the user about,
266         // that won't help.
267         fixed_expression->clear();
268       }
269     }
270 
271     if (!parse_success) {
272       if (!fixed_expression->empty() && target->GetEnableNotifyAboutFixIts()) {
273         error.SetExpressionErrorWithFormat(
274             execution_results,
275             "expression failed to parse, fixed expression suggested:\n  %s",
276             fixed_expression->c_str());
277       } else {
278         if (!diagnostic_manager.Diagnostics().size())
279           error.SetExpressionError(execution_results,
280                                    "expression failed to parse, unknown error");
281         else
282           error.SetExpressionError(execution_results,
283                                    diagnostic_manager.GetString().c_str());
284       }
285     }
286   }
287 
288   if (parse_success) {
289     // If a pointer to a lldb::ModuleSP was passed in, return the JIT'ed module
290     // if one was created
291     if (jit_module_sp_ptr)
292       *jit_module_sp_ptr = user_expression_sp->GetJITModule();
293 
294     lldb::ExpressionVariableSP expr_result;
295 
296     if (execution_policy == eExecutionPolicyNever &&
297         !user_expression_sp->CanInterpret()) {
298       if (log)
299         log->Printf("== [UserExpression::Evaluate] Expression may not run, but "
300                     "is not constant ==");
301 
302       if (!diagnostic_manager.Diagnostics().size())
303         error.SetExpressionError(lldb::eExpressionSetupError,
304                                  "expression needed to run but couldn't");
305     } else if (execution_policy == eExecutionPolicyTopLevel) {
306       error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric);
307       return lldb::eExpressionCompleted;
308     } else {
309       if (options.InvokeCancelCallback(lldb::eExpressionEvaluationExecution)) {
310         error.SetExpressionError(
311             lldb::eExpressionInterrupted,
312             "expression interrupted by callback before execution");
313         result_valobj_sp = ValueObjectConstResult::Create(
314             exe_ctx.GetBestExecutionContextScope(), error);
315         return lldb::eExpressionInterrupted;
316       }
317 
318       diagnostic_manager.Clear();
319 
320       if (log)
321         log->Printf("== [UserExpression::Evaluate] Executing expression ==");
322 
323       execution_results =
324           user_expression_sp->Execute(diagnostic_manager, exe_ctx, options,
325                                       user_expression_sp, expr_result);
326 
327       if (execution_results != lldb::eExpressionCompleted) {
328         if (log)
329           log->Printf("== [UserExpression::Evaluate] Execution completed "
330                       "abnormally ==");
331 
332         if (!diagnostic_manager.Diagnostics().size())
333           error.SetExpressionError(
334               execution_results, "expression failed to execute, unknown error");
335         else
336           error.SetExpressionError(execution_results,
337                                    diagnostic_manager.GetString().c_str());
338       } else {
339         if (expr_result) {
340           result_valobj_sp = expr_result->GetValueObject();
341 
342           if (log)
343             log->Printf("== [UserExpression::Evaluate] Execution completed "
344                         "normally with result %s ==",
345                         result_valobj_sp->GetValueAsCString());
346         } else {
347           if (log)
348             log->Printf("== [UserExpression::Evaluate] Execution completed "
349                         "normally with no result ==");
350 
351           error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric);
352         }
353       }
354     }
355   }
356 
357   if (options.InvokeCancelCallback(lldb::eExpressionEvaluationComplete)) {
358     error.SetExpressionError(
359         lldb::eExpressionInterrupted,
360         "expression interrupted by callback after complete");
361     return lldb::eExpressionInterrupted;
362   }
363 
364   if (result_valobj_sp.get() == NULL) {
365     result_valobj_sp = ValueObjectConstResult::Create(
366         exe_ctx.GetBestExecutionContextScope(), error);
367   }
368 
369   return execution_results;
370 }
371 
372 lldb::ExpressionResults
373 UserExpression::Execute(DiagnosticManager &diagnostic_manager,
374                         ExecutionContext &exe_ctx,
375                         const EvaluateExpressionOptions &options,
376                         lldb::UserExpressionSP &shared_ptr_to_me,
377                         lldb::ExpressionVariableSP &result_var) {
378   lldb::ExpressionResults expr_result = DoExecute(
379       diagnostic_manager, exe_ctx, options, shared_ptr_to_me, result_var);
380   Target *target = exe_ctx.GetTargetPtr();
381   if (options.GetResultIsInternal() && result_var && target) {
382     target->GetPersistentExpressionStateForLanguage(m_language)
383         ->RemovePersistentVariable(result_var);
384   }
385   return expr_result;
386 }
387