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 "lldb/Core/Module.h" 19 #include "lldb/Core/StreamFile.h" 20 #include "lldb/Core/ValueObjectConstResult.h" 21 #include "lldb/Expression/DiagnosticManager.h" 22 #include "lldb/Expression/ExpressionVariable.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 ExpressionKind kind) 53 : Expression(exe_scope, kind), 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, 143 std::string *fixed_expression, lldb::ModuleSP *jit_module_sp_ptr, 144 ValueObject *ctx_obj) { 145 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS | 146 LIBLLDB_LOG_STEP)); 147 148 if (ctx_obj) { 149 static unsigned const ctx_type_mask = 150 lldb::TypeFlags::eTypeIsClass | lldb::TypeFlags::eTypeIsStructUnion; 151 if (!(ctx_obj->GetTypeInfo() & ctx_type_mask)) { 152 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of " 153 "an invalid type, can't run expressions."); 154 error.SetErrorString("a context object of an invalid type passed"); 155 return lldb::eExpressionSetupError; 156 } 157 } 158 159 lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy(); 160 lldb::LanguageType language = options.GetLanguage(); 161 const ResultType desired_type = options.DoesCoerceToId() 162 ? UserExpression::eResultTypeId 163 : UserExpression::eResultTypeAny; 164 lldb::ExpressionResults execution_results = lldb::eExpressionSetupError; 165 166 Target *target = exe_ctx.GetTargetPtr(); 167 if (!target) { 168 LLDB_LOGF(log, "== [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 == nullptr || process->GetState() != lldb::eStateStopped) { 177 if (execution_policy == eExecutionPolicyAlways) { 178 LLDB_LOGF(log, 179 "== [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 == nullptr || !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 LLDB_LOGF(log, "== [UserExpression::Evaluate] Getting expression: %s ==", 227 error.AsCString()); 228 return lldb::eExpressionSetupError; 229 } 230 231 if (log) 232 LLDB_LOGF(log, "== [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 LLDB_LOGF(log, 313 "== [UserExpression::Evaluate] Expression may not run, but " 314 "is not constant =="); 315 316 if (!diagnostic_manager.Diagnostics().size()) 317 error.SetExpressionError(lldb::eExpressionSetupError, 318 "expression needed to run but couldn't"); 319 } else if (execution_policy == eExecutionPolicyTopLevel) { 320 error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric); 321 return lldb::eExpressionCompleted; 322 } else { 323 if (options.InvokeCancelCallback(lldb::eExpressionEvaluationExecution)) { 324 error.SetExpressionError( 325 lldb::eExpressionInterrupted, 326 "expression interrupted by callback before execution"); 327 result_valobj_sp = ValueObjectConstResult::Create( 328 exe_ctx.GetBestExecutionContextScope(), error); 329 return lldb::eExpressionInterrupted; 330 } 331 332 diagnostic_manager.Clear(); 333 334 if (log) 335 LLDB_LOGF(log, "== [UserExpression::Evaluate] Executing expression =="); 336 337 execution_results = 338 user_expression_sp->Execute(diagnostic_manager, exe_ctx, options, 339 user_expression_sp, expr_result); 340 341 if (execution_results != lldb::eExpressionCompleted) { 342 if (log) 343 LLDB_LOGF(log, "== [UserExpression::Evaluate] Execution completed " 344 "abnormally =="); 345 346 if (!diagnostic_manager.Diagnostics().size()) 347 error.SetExpressionError( 348 execution_results, "expression failed to execute, unknown error"); 349 else 350 error.SetExpressionError(execution_results, 351 diagnostic_manager.GetString().c_str()); 352 } else { 353 if (expr_result) { 354 result_valobj_sp = expr_result->GetValueObject(); 355 356 if (log) 357 LLDB_LOGF(log, 358 "== [UserExpression::Evaluate] Execution completed " 359 "normally with result %s ==", 360 result_valobj_sp->GetValueAsCString()); 361 } else { 362 if (log) 363 LLDB_LOGF(log, "== [UserExpression::Evaluate] Execution completed " 364 "normally with no result =="); 365 366 error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric); 367 } 368 } 369 } 370 } 371 372 if (options.InvokeCancelCallback(lldb::eExpressionEvaluationComplete)) { 373 error.SetExpressionError( 374 lldb::eExpressionInterrupted, 375 "expression interrupted by callback after complete"); 376 return lldb::eExpressionInterrupted; 377 } 378 379 if (result_valobj_sp.get() == nullptr) { 380 result_valobj_sp = ValueObjectConstResult::Create( 381 exe_ctx.GetBestExecutionContextScope(), error); 382 } 383 384 return execution_results; 385 } 386 387 lldb::ExpressionResults 388 UserExpression::Execute(DiagnosticManager &diagnostic_manager, 389 ExecutionContext &exe_ctx, 390 const EvaluateExpressionOptions &options, 391 lldb::UserExpressionSP &shared_ptr_to_me, 392 lldb::ExpressionVariableSP &result_var) { 393 lldb::ExpressionResults expr_result = DoExecute( 394 diagnostic_manager, exe_ctx, options, shared_ptr_to_me, result_var); 395 Target *target = exe_ctx.GetTargetPtr(); 396 if (options.GetResultIsInternal() && result_var && target) { 397 target->GetPersistentExpressionStateForLanguage(m_language) 398 ->RemovePersistentVariable(result_var); 399 } 400 return expr_result; 401 } 402