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/IRExecutionUnit.h" 24 #include "lldb/Expression/IRInterpreter.h" 25 #include "lldb/Expression/Materializer.h" 26 #include "lldb/Expression/UserExpression.h" 27 #include "lldb/Host/HostInfo.h" 28 #include "lldb/Symbol/Block.h" 29 #include "lldb/Symbol/Function.h" 30 #include "lldb/Symbol/ObjectFile.h" 31 #include "lldb/Symbol/SymbolVendor.h" 32 #include "lldb/Symbol/Type.h" 33 #include "lldb/Symbol/TypeSystem.h" 34 #include "lldb/Symbol/VariableList.h" 35 #include "lldb/Target/ExecutionContext.h" 36 #include "lldb/Target/Process.h" 37 #include "lldb/Target/StackFrame.h" 38 #include "lldb/Target/Target.h" 39 #include "lldb/Target/ThreadPlan.h" 40 #include "lldb/Target/ThreadPlanCallUserExpression.h" 41 #include "lldb/Utility/ConstString.h" 42 #include "lldb/Utility/Log.h" 43 #include "lldb/Utility/StreamString.h" 44 45 using namespace lldb_private; 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(expr), m_expr_prefix(prefix), 53 m_language(language), m_desired_type(desired_type), m_options(options) {} 54 55 UserExpression::~UserExpression() {} 56 57 void UserExpression::InstallContext(ExecutionContext &exe_ctx) { 58 m_jit_process_wp = exe_ctx.GetProcessSP(); 59 60 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP(); 61 62 if (frame_sp) 63 m_address = frame_sp->GetFrameCodeAddress(); 64 } 65 66 bool UserExpression::LockAndCheckContext(ExecutionContext &exe_ctx, 67 lldb::TargetSP &target_sp, 68 lldb::ProcessSP &process_sp, 69 lldb::StackFrameSP &frame_sp) { 70 lldb::ProcessSP expected_process_sp = m_jit_process_wp.lock(); 71 process_sp = exe_ctx.GetProcessSP(); 72 73 if (process_sp != expected_process_sp) 74 return false; 75 76 process_sp = exe_ctx.GetProcessSP(); 77 target_sp = exe_ctx.GetTargetSP(); 78 frame_sp = exe_ctx.GetFrameSP(); 79 80 if (m_address.IsValid()) { 81 if (!frame_sp) 82 return false; 83 else 84 return (0 == Address::CompareLoadAddress(m_address, 85 frame_sp->GetFrameCodeAddress(), 86 target_sp.get())); 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.AsCString(), 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 UserExpression::Evaluate( 139 ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, 140 llvm::StringRef expr, llvm::StringRef prefix, 141 lldb::ValueObjectSP &result_valobj_sp, Status &error, 142 std::string *fixed_expression, lldb::ModuleSP *jit_module_sp_ptr, 143 ValueObject *ctx_obj) { 144 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS | 145 LIBLLDB_LOG_STEP)); 146 147 if (ctx_obj) { 148 static unsigned const ctx_type_mask = 149 lldb::TypeFlags::eTypeIsClass | lldb::TypeFlags::eTypeIsStructUnion; 150 if (!(ctx_obj->GetTypeInfo() & ctx_type_mask)) { 151 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of " 152 "an invalid type, can't run expressions."); 153 error.SetErrorString("a context object of an invalid type passed"); 154 return lldb::eExpressionSetupError; 155 } 156 } 157 158 lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy(); 159 lldb::LanguageType language = options.GetLanguage(); 160 const ResultType desired_type = options.DoesCoerceToId() 161 ? UserExpression::eResultTypeId 162 : UserExpression::eResultTypeAny; 163 lldb::ExpressionResults execution_results = lldb::eExpressionSetupError; 164 165 Target *target = exe_ctx.GetTargetPtr(); 166 if (!target) { 167 if (log) 168 log->Printf("== [UserExpression::Evaluate] Passed a NULL target, can't " 169 "run expressions."); 170 error.SetErrorString("expression passed a null target"); 171 return lldb::eExpressionSetupError; 172 } 173 174 Process *process = exe_ctx.GetProcessPtr(); 175 176 if (process == NULL || process->GetState() != lldb::eStateStopped) { 177 if (execution_policy == eExecutionPolicyAlways) { 178 if (log) 179 log->Printf("== [UserExpression::Evaluate] Expression may not run, but " 180 "is not constant =="); 181 182 error.SetErrorString("expression needed to run but couldn't"); 183 184 return execution_results; 185 } 186 } 187 188 if (process == NULL || !process->CanJIT()) 189 execution_policy = eExecutionPolicyNever; 190 191 // We need to set the expression execution thread here, turns out parse can 192 // call functions in the process of looking up symbols, which will escape the 193 // context set by exe_ctx passed to Execute. 194 lldb::ThreadSP thread_sp = exe_ctx.GetThreadSP(); 195 ThreadList::ExpressionExecutionThreadPusher execution_thread_pusher( 196 thread_sp); 197 198 llvm::StringRef full_prefix; 199 llvm::StringRef option_prefix(options.GetPrefix()); 200 std::string full_prefix_storage; 201 if (!prefix.empty() && !option_prefix.empty()) { 202 full_prefix_storage = prefix; 203 full_prefix_storage.append(option_prefix); 204 full_prefix = full_prefix_storage; 205 } else if (!prefix.empty()) 206 full_prefix = prefix; 207 else 208 full_prefix = option_prefix; 209 210 // If the language was not specified in the expression command, set it to the 211 // language in the target's properties if specified, else default to the 212 // langage for the frame. 213 if (language == lldb::eLanguageTypeUnknown) { 214 if (target->GetLanguage() != lldb::eLanguageTypeUnknown) 215 language = target->GetLanguage(); 216 else if (StackFrame *frame = exe_ctx.GetFramePtr()) 217 language = frame->GetLanguage(); 218 } 219 220 lldb::UserExpressionSP user_expression_sp( 221 target->GetUserExpressionForLanguage(expr, full_prefix, language, 222 desired_type, options, ctx_obj, 223 error)); 224 if (error.Fail()) { 225 if (log) 226 log->Printf("== [UserExpression::Evaluate] Getting expression: %s ==", 227 error.AsCString()); 228 return lldb::eExpressionSetupError; 229 } 230 231 if (log) 232 log->Printf("== [UserExpression::Evaluate] Parsing expression %s ==", 233 expr.str().c_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 const char *fixed_text = user_expression_sp->GetFixedText(); 257 if (fixed_text != nullptr) 258 fixed_expression->append(fixed_text); 259 260 // If there is a fixed expression, try to parse it: 261 if (!parse_success) { 262 execution_results = lldb::eExpressionParseError; 263 if (fixed_expression && !fixed_expression->empty() && 264 options.GetAutoApplyFixIts()) { 265 lldb::UserExpressionSP fixed_expression_sp( 266 target->GetUserExpressionForLanguage(fixed_expression->c_str(), 267 full_prefix, language, 268 desired_type, options, ctx_obj, 269 error)); 270 DiagnosticManager fixed_diagnostic_manager; 271 parse_success = fixed_expression_sp->Parse( 272 fixed_diagnostic_manager, exe_ctx, execution_policy, 273 keep_expression_in_memory, generate_debug_info); 274 if (parse_success) { 275 diagnostic_manager.Clear(); 276 user_expression_sp = fixed_expression_sp; 277 } else { 278 // If the fixed expression failed to parse, don't tell the user about, 279 // that won't help. 280 fixed_expression->clear(); 281 } 282 } 283 284 if (!parse_success) { 285 if (!fixed_expression->empty() && target->GetEnableNotifyAboutFixIts()) { 286 error.SetExpressionErrorWithFormat( 287 execution_results, 288 "expression failed to parse, fixed expression suggested:\n %s", 289 fixed_expression->c_str()); 290 } else { 291 if (!diagnostic_manager.Diagnostics().size()) 292 error.SetExpressionError(execution_results, 293 "expression failed to parse, unknown error"); 294 else 295 error.SetExpressionError(execution_results, 296 diagnostic_manager.GetString().c_str()); 297 } 298 } 299 } 300 301 if (parse_success) { 302 // If a pointer to a lldb::ModuleSP was passed in, return the JIT'ed module 303 // if one was created 304 if (jit_module_sp_ptr) 305 *jit_module_sp_ptr = user_expression_sp->GetJITModule(); 306 307 lldb::ExpressionVariableSP expr_result; 308 309 if (execution_policy == eExecutionPolicyNever && 310 !user_expression_sp->CanInterpret()) { 311 if (log) 312 log->Printf("== [UserExpression::Evaluate] Expression may not run, but " 313 "is not constant =="); 314 315 if (!diagnostic_manager.Diagnostics().size()) 316 error.SetExpressionError(lldb::eExpressionSetupError, 317 "expression needed to run but couldn't"); 318 } else if (execution_policy == eExecutionPolicyTopLevel) { 319 error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric); 320 return lldb::eExpressionCompleted; 321 } else { 322 if (options.InvokeCancelCallback(lldb::eExpressionEvaluationExecution)) { 323 error.SetExpressionError( 324 lldb::eExpressionInterrupted, 325 "expression interrupted by callback before execution"); 326 result_valobj_sp = ValueObjectConstResult::Create( 327 exe_ctx.GetBestExecutionContextScope(), error); 328 return lldb::eExpressionInterrupted; 329 } 330 331 diagnostic_manager.Clear(); 332 333 if (log) 334 log->Printf("== [UserExpression::Evaluate] Executing expression =="); 335 336 execution_results = 337 user_expression_sp->Execute(diagnostic_manager, exe_ctx, options, 338 user_expression_sp, expr_result); 339 340 if (execution_results != lldb::eExpressionCompleted) { 341 if (log) 342 log->Printf("== [UserExpression::Evaluate] Execution completed " 343 "abnormally =="); 344 345 if (!diagnostic_manager.Diagnostics().size()) 346 error.SetExpressionError( 347 execution_results, "expression failed to execute, unknown error"); 348 else 349 error.SetExpressionError(execution_results, 350 diagnostic_manager.GetString().c_str()); 351 } else { 352 if (expr_result) { 353 result_valobj_sp = expr_result->GetValueObject(); 354 355 if (log) 356 log->Printf("== [UserExpression::Evaluate] Execution completed " 357 "normally with result %s ==", 358 result_valobj_sp->GetValueAsCString()); 359 } else { 360 if (log) 361 log->Printf("== [UserExpression::Evaluate] Execution completed " 362 "normally with no result =="); 363 364 error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric); 365 } 366 } 367 } 368 } 369 370 if (options.InvokeCancelCallback(lldb::eExpressionEvaluationComplete)) { 371 error.SetExpressionError( 372 lldb::eExpressionInterrupted, 373 "expression interrupted by callback after complete"); 374 return lldb::eExpressionInterrupted; 375 } 376 377 if (result_valobj_sp.get() == NULL) { 378 result_valobj_sp = ValueObjectConstResult::Create( 379 exe_ctx.GetBestExecutionContextScope(), error); 380 } 381 382 return execution_results; 383 } 384 385 lldb::ExpressionResults 386 UserExpression::Execute(DiagnosticManager &diagnostic_manager, 387 ExecutionContext &exe_ctx, 388 const EvaluateExpressionOptions &options, 389 lldb::UserExpressionSP &shared_ptr_to_me, 390 lldb::ExpressionVariableSP &result_var) { 391 lldb::ExpressionResults expr_result = DoExecute( 392 diagnostic_manager, exe_ctx, options, shared_ptr_to_me, result_var); 393 Target *target = exe_ctx.GetTargetPtr(); 394 if (options.GetResultIsInternal() && result_var && target) { 395 target->GetPersistentExpressionStateForLanguage(m_language) 396 ->RemovePersistentVariable(result_var); 397 } 398 return expr_result; 399 } 400