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 else 88 return (0 == Address::CompareLoadAddress(m_address, 89 frame_sp->GetFrameCodeAddress(), 90 target_sp.get())); 91 } 92 93 return true; 94 } 95 96 bool UserExpression::MatchesContext(ExecutionContext &exe_ctx) { 97 lldb::TargetSP target_sp; 98 lldb::ProcessSP process_sp; 99 lldb::StackFrameSP frame_sp; 100 101 return LockAndCheckContext(exe_ctx, target_sp, process_sp, frame_sp); 102 } 103 104 lldb::addr_t UserExpression::GetObjectPointer(lldb::StackFrameSP frame_sp, 105 ConstString &object_name, 106 Status &err) { 107 err.Clear(); 108 109 if (!frame_sp) { 110 err.SetErrorStringWithFormat( 111 "Couldn't load '%s' because the context is incomplete", 112 object_name.AsCString()); 113 return LLDB_INVALID_ADDRESS; 114 } 115 116 lldb::VariableSP var_sp; 117 lldb::ValueObjectSP valobj_sp; 118 119 valobj_sp = frame_sp->GetValueForVariableExpressionPath( 120 object_name.AsCString(), lldb::eNoDynamicValues, 121 StackFrame::eExpressionPathOptionCheckPtrVsMember | 122 StackFrame::eExpressionPathOptionsNoFragileObjcIvar | 123 StackFrame::eExpressionPathOptionsNoSyntheticChildren | 124 StackFrame::eExpressionPathOptionsNoSyntheticArrayRange, 125 var_sp, err); 126 127 if (!err.Success() || !valobj_sp.get()) 128 return LLDB_INVALID_ADDRESS; 129 130 lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS); 131 132 if (ret == LLDB_INVALID_ADDRESS) { 133 err.SetErrorStringWithFormat( 134 "Couldn't load '%s' because its value couldn't be evaluated", 135 object_name.AsCString()); 136 return LLDB_INVALID_ADDRESS; 137 } 138 139 return ret; 140 } 141 142 lldb::ExpressionResults UserExpression::Evaluate( 143 ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, 144 llvm::StringRef expr, llvm::StringRef prefix, 145 lldb::ValueObjectSP &result_valobj_sp, Status &error, 146 std::string *fixed_expression, lldb::ModuleSP *jit_module_sp_ptr, 147 ValueObject *ctx_obj) { 148 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS | 149 LIBLLDB_LOG_STEP)); 150 151 if (ctx_obj) { 152 static unsigned const ctx_type_mask = 153 lldb::TypeFlags::eTypeIsClass | lldb::TypeFlags::eTypeIsStructUnion; 154 if (!(ctx_obj->GetTypeInfo() & ctx_type_mask)) { 155 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of " 156 "an invalid type, can't run expressions."); 157 error.SetErrorString("a context object of an invalid type passed"); 158 return lldb::eExpressionSetupError; 159 } 160 } 161 162 lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy(); 163 lldb::LanguageType language = options.GetLanguage(); 164 const ResultType desired_type = options.DoesCoerceToId() 165 ? UserExpression::eResultTypeId 166 : UserExpression::eResultTypeAny; 167 lldb::ExpressionResults execution_results = lldb::eExpressionSetupError; 168 169 Target *target = exe_ctx.GetTargetPtr(); 170 if (!target) { 171 LLDB_LOGF(log, "== [UserExpression::Evaluate] Passed a NULL target, can't " 172 "run expressions."); 173 error.SetErrorString("expression passed a null target"); 174 return lldb::eExpressionSetupError; 175 } 176 177 Process *process = exe_ctx.GetProcessPtr(); 178 179 if (process == nullptr || process->GetState() != lldb::eStateStopped) { 180 if (execution_policy == eExecutionPolicyAlways) { 181 LLDB_LOGF(log, 182 "== [UserExpression::Evaluate] Expression may not run, but " 183 "is not constant =="); 184 185 error.SetErrorString("expression needed to run but couldn't"); 186 187 return execution_results; 188 } 189 } 190 191 if (process == nullptr || !process->CanJIT()) 192 execution_policy = eExecutionPolicyNever; 193 194 // We need to set the expression execution thread here, turns out parse can 195 // call functions in the process of looking up symbols, which will escape the 196 // context set by exe_ctx passed to Execute. 197 lldb::ThreadSP thread_sp = exe_ctx.GetThreadSP(); 198 ThreadList::ExpressionExecutionThreadPusher execution_thread_pusher( 199 thread_sp); 200 201 llvm::StringRef full_prefix; 202 llvm::StringRef option_prefix(options.GetPrefix()); 203 std::string full_prefix_storage; 204 if (!prefix.empty() && !option_prefix.empty()) { 205 full_prefix_storage = prefix; 206 full_prefix_storage.append(option_prefix); 207 full_prefix = full_prefix_storage; 208 } else if (!prefix.empty()) 209 full_prefix = prefix; 210 else 211 full_prefix = option_prefix; 212 213 // If the language was not specified in the expression command, set it to the 214 // language in the target's properties if specified, else default to the 215 // langage for the frame. 216 if (language == lldb::eLanguageTypeUnknown) { 217 if (target->GetLanguage() != lldb::eLanguageTypeUnknown) 218 language = target->GetLanguage(); 219 else if (StackFrame *frame = exe_ctx.GetFramePtr()) 220 language = frame->GetLanguage(); 221 } 222 223 lldb::UserExpressionSP user_expression_sp( 224 target->GetUserExpressionForLanguage(expr, full_prefix, language, 225 desired_type, options, ctx_obj, 226 error)); 227 if (error.Fail()) { 228 if (log) 229 LLDB_LOGF(log, "== [UserExpression::Evaluate] Getting expression: %s ==", 230 error.AsCString()); 231 return lldb::eExpressionSetupError; 232 } 233 234 if (log) 235 LLDB_LOGF(log, "== [UserExpression::Evaluate] Parsing expression %s ==", 236 expr.str().c_str()); 237 238 const bool keep_expression_in_memory = true; 239 const bool generate_debug_info = options.GetGenerateDebugInfo(); 240 241 if (options.InvokeCancelCallback(lldb::eExpressionEvaluationParse)) { 242 error.SetErrorString("expression interrupted by callback before parse"); 243 result_valobj_sp = ValueObjectConstResult::Create( 244 exe_ctx.GetBestExecutionContextScope(), error); 245 return lldb::eExpressionInterrupted; 246 } 247 248 DiagnosticManager diagnostic_manager; 249 250 bool parse_success = 251 user_expression_sp->Parse(diagnostic_manager, exe_ctx, execution_policy, 252 keep_expression_in_memory, generate_debug_info); 253 254 // Calculate the fixed expression always, since we need it for errors. 255 std::string tmp_fixed_expression; 256 if (fixed_expression == nullptr) 257 fixed_expression = &tmp_fixed_expression; 258 259 const char *fixed_text = user_expression_sp->GetFixedText(); 260 if (fixed_text != nullptr) 261 fixed_expression->append(fixed_text); 262 263 // If there is a fixed expression, try to parse it: 264 if (!parse_success) { 265 execution_results = lldb::eExpressionParseError; 266 if (fixed_expression && !fixed_expression->empty() && 267 options.GetAutoApplyFixIts()) { 268 lldb::UserExpressionSP fixed_expression_sp( 269 target->GetUserExpressionForLanguage(fixed_expression->c_str(), 270 full_prefix, language, 271 desired_type, options, ctx_obj, 272 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 } else { 281 // If the fixed expression failed to parse, don't tell the user about, 282 // that won't help. 283 fixed_expression->clear(); 284 } 285 } 286 287 if (!parse_success) { 288 if (!fixed_expression->empty() && target->GetEnableNotifyAboutFixIts()) { 289 error.SetExpressionErrorWithFormat( 290 execution_results, 291 "expression failed to parse, fixed expression suggested:\n %s", 292 fixed_expression->c_str()); 293 } else { 294 if (!diagnostic_manager.Diagnostics().size()) 295 error.SetExpressionError(execution_results, 296 "expression failed to parse, unknown error"); 297 else 298 error.SetExpressionError(execution_results, 299 diagnostic_manager.GetString().c_str()); 300 } 301 } 302 } 303 304 if (parse_success) { 305 // If a pointer to a lldb::ModuleSP was passed in, return the JIT'ed module 306 // if one was created 307 if (jit_module_sp_ptr) 308 *jit_module_sp_ptr = user_expression_sp->GetJITModule(); 309 310 lldb::ExpressionVariableSP expr_result; 311 312 if (execution_policy == eExecutionPolicyNever && 313 !user_expression_sp->CanInterpret()) { 314 if (log) 315 LLDB_LOGF(log, 316 "== [UserExpression::Evaluate] Expression may not run, but " 317 "is not constant =="); 318 319 if (!diagnostic_manager.Diagnostics().size()) 320 error.SetExpressionError(lldb::eExpressionSetupError, 321 "expression needed to run but couldn't"); 322 } else if (execution_policy == eExecutionPolicyTopLevel) { 323 error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric); 324 return lldb::eExpressionCompleted; 325 } else { 326 if (options.InvokeCancelCallback(lldb::eExpressionEvaluationExecution)) { 327 error.SetExpressionError( 328 lldb::eExpressionInterrupted, 329 "expression interrupted by callback before execution"); 330 result_valobj_sp = ValueObjectConstResult::Create( 331 exe_ctx.GetBestExecutionContextScope(), error); 332 return lldb::eExpressionInterrupted; 333 } 334 335 diagnostic_manager.Clear(); 336 337 if (log) 338 LLDB_LOGF(log, "== [UserExpression::Evaluate] Executing expression =="); 339 340 execution_results = 341 user_expression_sp->Execute(diagnostic_manager, exe_ctx, options, 342 user_expression_sp, expr_result); 343 344 if (execution_results != lldb::eExpressionCompleted) { 345 if (log) 346 LLDB_LOGF(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 359 if (log) 360 LLDB_LOGF(log, 361 "== [UserExpression::Evaluate] Execution completed " 362 "normally with result %s ==", 363 result_valobj_sp->GetValueAsCString()); 364 } else { 365 if (log) 366 LLDB_LOGF(log, "== [UserExpression::Evaluate] Execution completed " 367 "normally with no result =="); 368 369 error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric); 370 } 371 } 372 } 373 } 374 375 if (options.InvokeCancelCallback(lldb::eExpressionEvaluationComplete)) { 376 error.SetExpressionError( 377 lldb::eExpressionInterrupted, 378 "expression interrupted by callback after complete"); 379 return lldb::eExpressionInterrupted; 380 } 381 382 if (result_valobj_sp.get() == nullptr) { 383 result_valobj_sp = ValueObjectConstResult::Create( 384 exe_ctx.GetBestExecutionContextScope(), error); 385 } 386 387 return execution_results; 388 } 389 390 lldb::ExpressionResults 391 UserExpression::Execute(DiagnosticManager &diagnostic_manager, 392 ExecutionContext &exe_ctx, 393 const EvaluateExpressionOptions &options, 394 lldb::UserExpressionSP &shared_ptr_to_me, 395 lldb::ExpressionVariableSP &result_var) { 396 lldb::ExpressionResults expr_result = DoExecute( 397 diagnostic_manager, exe_ctx, options, shared_ptr_to_me, result_var); 398 Target *target = exe_ctx.GetTargetPtr(); 399 if (options.GetResultIsInternal() && result_var && target) { 400 target->GetPersistentExpressionStateForLanguage(m_language) 401 ->RemovePersistentVariable(result_var); 402 } 403 return expr_result; 404 } 405