1 //===-- ClangUserExpression.cpp ---------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
11 #include <sys/types.h>
18 #include "ClangUserExpression.h"
20 #include "ASTResultSynthesizer.h"
21 #include "ClangDiagnostic.h"
22 #include "ClangExpressionDeclMap.h"
23 #include "ClangExpressionParser.h"
24 #include "ClangExpressionSourceCode.h"
25 #include "ClangModulesDeclVendor.h"
26 #include "ClangPersistentVariables.h"
28 #include "lldb/Core/Debugger.h"
29 #include "lldb/Core/Module.h"
30 #include "lldb/Core/StreamFile.h"
31 #include "lldb/Core/ValueObjectConstResult.h"
32 #include "lldb/Expression/ExpressionSourceCode.h"
33 #include "lldb/Expression/IRExecutionUnit.h"
34 #include "lldb/Expression/IRInterpreter.h"
35 #include "lldb/Expression/Materializer.h"
36 #include "lldb/Host/HostInfo.h"
37 #include "lldb/Symbol/Block.h"
38 #include "lldb/Symbol/ClangASTContext.h"
39 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
40 #include "lldb/Symbol/CompileUnit.h"
41 #include "lldb/Symbol/Function.h"
42 #include "lldb/Symbol/ObjectFile.h"
43 #include "lldb/Symbol/SymbolVendor.h"
44 #include "lldb/Symbol/Type.h"
45 #include "lldb/Symbol/VariableList.h"
46 #include "lldb/Target/ExecutionContext.h"
47 #include "lldb/Target/Process.h"
48 #include "lldb/Target/StackFrame.h"
49 #include "lldb/Target/Target.h"
50 #include "lldb/Target/ThreadPlan.h"
51 #include "lldb/Target/ThreadPlanCallUserExpression.h"
52 #include "lldb/Utility/ConstString.h"
53 #include "lldb/Utility/Log.h"
54 #include "lldb/Utility/StreamString.h"
56 #include "clang/AST/DeclCXX.h"
57 #include "clang/AST/DeclObjC.h"
59 #include "llvm/ADT/ScopeExit.h"
61 using namespace lldb_private;
63 ClangUserExpression::ClangUserExpression(
64 ExecutionContextScope &exe_scope, llvm::StringRef expr,
65 llvm::StringRef prefix, lldb::LanguageType language,
66 ResultType desired_type, const EvaluateExpressionOptions &options,
68 : LLVMUserExpression(exe_scope, expr, prefix, language, desired_type,
69 options, eKindClangUserExpression),
70 m_type_system_helper(*m_target_wp.lock(), options.GetExecutionPolicy() ==
71 eExecutionPolicyTopLevel),
72 m_result_delegate(exe_scope.CalculateTarget()), m_ctx_obj(ctx_obj) {
74 case lldb::eLanguageTypeC_plus_plus:
77 case lldb::eLanguageTypeObjC:
80 case lldb::eLanguageTypeObjC_plus_plus:
88 ClangUserExpression::~ClangUserExpression() {}
90 void ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Status &err) {
91 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
94 log->Printf("ClangUserExpression::ScanContext()");
96 m_target = exe_ctx.GetTargetPtr();
98 if (!(m_allow_cxx || m_allow_objc)) {
100 log->Printf(" [CUE::SC] Settings inhibit C++ and Objective-C");
104 StackFrame *frame = exe_ctx.GetFramePtr();
105 if (frame == nullptr) {
107 log->Printf(" [CUE::SC] Null stack frame");
111 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
112 lldb::eSymbolContextBlock);
114 if (!sym_ctx.function) {
116 log->Printf(" [CUE::SC] Null function");
120 // Find the block that defines the function represented by "sym_ctx"
121 Block *function_block = sym_ctx.GetFunctionBlock();
123 if (!function_block) {
125 log->Printf(" [CUE::SC] Null function block");
129 CompilerDeclContext decl_context = function_block->GetDeclContext();
133 log->Printf(" [CUE::SC] Null decl context");
138 switch (m_ctx_obj->GetObjectRuntimeLanguage()) {
139 case lldb::eLanguageTypeC:
140 case lldb::eLanguageTypeC89:
141 case lldb::eLanguageTypeC99:
142 case lldb::eLanguageTypeC11:
143 case lldb::eLanguageTypeC_plus_plus:
144 case lldb::eLanguageTypeC_plus_plus_03:
145 case lldb::eLanguageTypeC_plus_plus_11:
146 case lldb::eLanguageTypeC_plus_plus_14:
147 m_in_cplusplus_method = true;
149 case lldb::eLanguageTypeObjC:
150 case lldb::eLanguageTypeObjC_plus_plus:
151 m_in_objectivec_method = true;
156 m_needs_object_ptr = true;
157 } else if (clang::CXXMethodDecl *method_decl =
158 ClangASTContext::DeclContextGetAsCXXMethodDecl(decl_context)) {
159 if (m_allow_cxx && method_decl->isInstance()) {
160 if (m_enforce_valid_object) {
161 lldb::VariableListSP variable_list_sp(
162 function_block->GetBlockVariableList(true));
164 const char *thisErrorString = "Stopped in a C++ method, but 'this' "
165 "isn't available; pretending we are in a "
168 if (!variable_list_sp) {
169 err.SetErrorString(thisErrorString);
173 lldb::VariableSP this_var_sp(
174 variable_list_sp->FindVariable(ConstString("this")));
176 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
177 !this_var_sp->LocationIsValidForFrame(frame)) {
178 err.SetErrorString(thisErrorString);
183 m_in_cplusplus_method = true;
184 m_needs_object_ptr = true;
186 } else if (clang::ObjCMethodDecl *method_decl =
187 ClangASTContext::DeclContextGetAsObjCMethodDecl(
190 if (m_enforce_valid_object) {
191 lldb::VariableListSP variable_list_sp(
192 function_block->GetBlockVariableList(true));
194 const char *selfErrorString = "Stopped in an Objective-C method, but "
195 "'self' isn't available; pretending we "
196 "are in a generic context";
198 if (!variable_list_sp) {
199 err.SetErrorString(selfErrorString);
203 lldb::VariableSP self_variable_sp =
204 variable_list_sp->FindVariable(ConstString("self"));
206 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
207 !self_variable_sp->LocationIsValidForFrame(frame)) {
208 err.SetErrorString(selfErrorString);
213 m_in_objectivec_method = true;
214 m_needs_object_ptr = true;
216 if (!method_decl->isInstanceMethod())
217 m_in_static_method = true;
219 } else if (clang::FunctionDecl *function_decl =
220 ClangASTContext::DeclContextGetAsFunctionDecl(decl_context)) {
221 // We might also have a function that said in the debug information that it
222 // captured an object pointer. The best way to deal with getting to the
223 // ivars at present is by pretending that this is a method of a class in
224 // whatever runtime the debug info says the object pointer belongs to. Do
227 ClangASTMetadata *metadata =
228 ClangASTContext::DeclContextGetMetaData(decl_context, function_decl);
229 if (metadata && metadata->HasObjectPtr()) {
230 lldb::LanguageType language = metadata->GetObjectPtrLanguage();
231 if (language == lldb::eLanguageTypeC_plus_plus) {
232 if (m_enforce_valid_object) {
233 lldb::VariableListSP variable_list_sp(
234 function_block->GetBlockVariableList(true));
236 const char *thisErrorString = "Stopped in a context claiming to "
237 "capture a C++ object pointer, but "
238 "'this' isn't available; pretending we "
239 "are in a generic context";
241 if (!variable_list_sp) {
242 err.SetErrorString(thisErrorString);
246 lldb::VariableSP this_var_sp(
247 variable_list_sp->FindVariable(ConstString("this")));
249 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
250 !this_var_sp->LocationIsValidForFrame(frame)) {
251 err.SetErrorString(thisErrorString);
256 m_in_cplusplus_method = true;
257 m_needs_object_ptr = true;
258 } else if (language == lldb::eLanguageTypeObjC) {
259 if (m_enforce_valid_object) {
260 lldb::VariableListSP variable_list_sp(
261 function_block->GetBlockVariableList(true));
263 const char *selfErrorString =
264 "Stopped in a context claiming to capture an Objective-C object "
265 "pointer, but 'self' isn't available; pretending we are in a "
268 if (!variable_list_sp) {
269 err.SetErrorString(selfErrorString);
273 lldb::VariableSP self_variable_sp =
274 variable_list_sp->FindVariable(ConstString("self"));
276 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
277 !self_variable_sp->LocationIsValidForFrame(frame)) {
278 err.SetErrorString(selfErrorString);
282 Type *self_type = self_variable_sp->GetType();
285 err.SetErrorString(selfErrorString);
289 CompilerType self_clang_type = self_type->GetForwardCompilerType();
291 if (!self_clang_type) {
292 err.SetErrorString(selfErrorString);
296 if (ClangASTContext::IsObjCClassType(self_clang_type)) {
298 } else if (ClangASTContext::IsObjCObjectPointerType(
300 m_in_objectivec_method = true;
301 m_needs_object_ptr = true;
303 err.SetErrorString(selfErrorString);
307 m_in_objectivec_method = true;
308 m_needs_object_ptr = true;
315 // This is a really nasty hack, meant to fix Objective-C expressions of the
316 // form (int)[myArray count]. Right now, because the type information for
317 // count is not available, [myArray count] returns id, which can't be directly
318 // cast to int without causing a clang error.
319 static void ApplyObjcCastHack(std::string &expr) {
320 #define OBJC_CAST_HACK_FROM "(int)["
321 #define OBJC_CAST_HACK_TO "(int)(long long)["
325 while ((from_offset = expr.find(OBJC_CAST_HACK_FROM)) != expr.npos)
326 expr.replace(from_offset, sizeof(OBJC_CAST_HACK_FROM) - 1,
329 #undef OBJC_CAST_HACK_TO
330 #undef OBJC_CAST_HACK_FROM
333 bool ClangUserExpression::SetupPersistentState(DiagnosticManager &diagnostic_manager,
334 ExecutionContext &exe_ctx) {
335 if (Target *target = exe_ctx.GetTargetPtr()) {
336 if (PersistentExpressionState *persistent_state =
337 target->GetPersistentExpressionStateForLanguage(
338 lldb::eLanguageTypeC)) {
339 m_result_delegate.RegisterPersistentState(persistent_state);
341 diagnostic_manager.PutString(
342 eDiagnosticSeverityError,
343 "couldn't start parsing (no persistent data)");
347 diagnostic_manager.PutString(eDiagnosticSeverityError,
348 "error: couldn't start parsing (no target)");
354 static void SetupDeclVendor(ExecutionContext &exe_ctx, Target *target) {
355 if (ClangModulesDeclVendor *decl_vendor =
356 target->GetClangModulesDeclVendor()) {
357 const ClangModulesDeclVendor::ModuleVector &hand_imported_modules =
358 llvm::cast<ClangPersistentVariables>(
359 target->GetPersistentExpressionStateForLanguage(
360 lldb::eLanguageTypeC))
361 ->GetHandLoadedClangModules();
362 ClangModulesDeclVendor::ModuleVector modules_for_macros;
364 for (ClangModulesDeclVendor::ModuleID module : hand_imported_modules) {
365 modules_for_macros.push_back(module);
368 if (target->GetEnableAutoImportClangModules()) {
369 if (StackFrame *frame = exe_ctx.GetFramePtr()) {
370 if (Block *block = frame->GetFrameBlock()) {
373 block->CalculateSymbolContext(&sc);
376 StreamString error_stream;
378 decl_vendor->AddModulesForCompileUnit(
379 *sc.comp_unit, modules_for_macros, error_stream);
387 void ClangUserExpression::UpdateLanguageForExpr(
388 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
389 std::vector<std::string> modules_to_import, bool for_completion) {
390 m_expr_lang = lldb::LanguageType::eLanguageTypeUnknown;
392 std::string prefix = m_expr_prefix;
394 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
395 m_transformed_text = m_expr_text;
397 std::unique_ptr<ClangExpressionSourceCode> source_code(
398 ClangExpressionSourceCode::CreateWrapped(prefix.c_str(),
399 m_expr_text.c_str()));
401 if (m_in_cplusplus_method)
402 m_expr_lang = lldb::eLanguageTypeC_plus_plus;
403 else if (m_in_objectivec_method)
404 m_expr_lang = lldb::eLanguageTypeObjC;
406 m_expr_lang = lldb::eLanguageTypeC;
408 if (!source_code->GetText(m_transformed_text, m_expr_lang,
409 m_in_static_method, exe_ctx, !m_ctx_obj,
410 for_completion, modules_to_import)) {
411 diagnostic_manager.PutString(eDiagnosticSeverityError,
412 "couldn't construct expression body");
416 // Find and store the start position of the original code inside the
417 // transformed code. We need this later for the code completion.
418 std::size_t original_start;
419 std::size_t original_end;
420 bool found_bounds = source_code->GetOriginalBodyBounds(
421 m_transformed_text, m_expr_lang, original_start, original_end);
423 m_user_expression_start_pos = original_start;
427 static bool SupportsCxxModuleImport(lldb::LanguageType language) {
429 case lldb::eLanguageTypeC_plus_plus:
430 case lldb::eLanguageTypeC_plus_plus_03:
431 case lldb::eLanguageTypeC_plus_plus_11:
432 case lldb::eLanguageTypeC_plus_plus_14:
433 case lldb::eLanguageTypeObjC_plus_plus:
440 std::vector<std::string>
441 ClangUserExpression::GetModulesToImport(ExecutionContext &exe_ctx) {
442 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
444 if (!SupportsCxxModuleImport(Language()))
447 Target *target = exe_ctx.GetTargetPtr();
448 if (!target || !target->GetEnableImportStdModule())
451 StackFrame *frame = exe_ctx.GetFramePtr();
455 Block *block = frame->GetFrameBlock();
460 block->CalculateSymbolContext(&sc);
465 for (const SourceModule &m : sc.comp_unit->GetImportedModules()) {
466 LLDB_LOG(log, "Found module in compile unit: {0:$[.]} - include dir: {1}",
467 llvm::make_range(m.path.begin(), m.path.end()), m.search_path);
471 for (const SourceModule &m : sc.comp_unit->GetImportedModules())
472 m_include_directories.push_back(m.search_path);
474 // Check if we imported 'std' or any of its submodules.
475 // We currently don't support importing any other modules in the expression
477 for (const SourceModule &m : sc.comp_unit->GetImportedModules())
478 if (!m.path.empty() && m.path.front() == "std")
484 bool ClangUserExpression::PrepareForParsing(
485 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
486 bool for_completion) {
487 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
489 InstallContext(exe_ctx);
491 if (!SetupPersistentState(diagnostic_manager, exe_ctx))
495 ScanContext(exe_ctx, err);
497 if (!err.Success()) {
498 diagnostic_manager.PutString(eDiagnosticSeverityWarning, err.AsCString());
501 ////////////////////////////////////
502 // Generate the expression
505 ApplyObjcCastHack(m_expr_text);
507 SetupDeclVendor(exe_ctx, m_target);
509 std::vector<std::string> used_modules = GetModulesToImport(exe_ctx);
510 m_imported_cpp_modules = !used_modules.empty();
512 LLDB_LOG(log, "List of imported modules in expression: {0}",
513 llvm::make_range(used_modules.begin(), used_modules.end()));
515 UpdateLanguageForExpr(diagnostic_manager, exe_ctx, used_modules,
520 bool ClangUserExpression::Parse(DiagnosticManager &diagnostic_manager,
521 ExecutionContext &exe_ctx,
522 lldb_private::ExecutionPolicy execution_policy,
523 bool keep_result_in_memory,
524 bool generate_debug_info) {
525 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
527 if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ false))
531 log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str());
533 ////////////////////////////////////
534 // Set up the target and compiler
537 Target *target = exe_ctx.GetTargetPtr();
540 diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid target");
544 //////////////////////////
545 // Parse the expression
548 m_materializer_up.reset(new Materializer());
550 ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory);
552 auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); });
554 if (!DeclMap()->WillParse(exe_ctx, m_materializer_up.get())) {
555 diagnostic_manager.PutString(
556 eDiagnosticSeverityError,
557 "current process state is unsuitable for expression parsing");
561 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
562 DeclMap()->SetLookupsEnabled(true);
565 Process *process = exe_ctx.GetProcessPtr();
566 ExecutionContextScope *exe_scope = process;
569 exe_scope = exe_ctx.GetTargetPtr();
571 // We use a shared pointer here so we can use the original parser - if it
572 // succeeds or the rewrite parser we might make if it fails. But the
573 // parser_sp will never be empty.
575 ClangExpressionParser parser(exe_scope, *this, generate_debug_info,
576 m_include_directories);
578 unsigned num_errors = parser.Parse(diagnostic_manager);
580 // Check here for FixItHints. If there are any try to apply the fixits and
581 // set the fixed text in m_fixed_text before returning an error.
583 if (diagnostic_manager.HasFixIts()) {
584 if (parser.RewriteExpression(diagnostic_manager)) {
587 const std::string &fixed_expression =
588 diagnostic_manager.GetFixedExpression();
589 if (ClangExpressionSourceCode::GetOriginalBodyBounds(
590 fixed_expression, m_expr_lang, fixed_start, fixed_end))
592 fixed_expression.substr(fixed_start, fixed_end - fixed_start);
598 //////////////////////////////////////////////////////////////////////////////
599 // Prepare the output of the parser for execution, evaluating it statically
604 Status jit_error = parser.PrepareForExecution(
605 m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
606 m_can_interpret, execution_policy);
608 if (!jit_error.Success()) {
609 const char *error_cstr = jit_error.AsCString();
610 if (error_cstr && error_cstr[0])
611 diagnostic_manager.PutString(eDiagnosticSeverityError, error_cstr);
613 diagnostic_manager.PutString(eDiagnosticSeverityError,
614 "expression can't be interpreted or run");
619 if (exe_ctx.GetProcessPtr() && execution_policy == eExecutionPolicyTopLevel) {
620 Status static_init_error =
621 parser.RunStaticInitializers(m_execution_unit_sp, exe_ctx);
623 if (!static_init_error.Success()) {
624 const char *error_cstr = static_init_error.AsCString();
625 if (error_cstr && error_cstr[0])
626 diagnostic_manager.Printf(eDiagnosticSeverityError,
627 "couldn't run static initializers: %s\n",
630 diagnostic_manager.PutString(eDiagnosticSeverityError,
631 "couldn't run static initializers\n");
636 if (m_execution_unit_sp) {
637 bool register_execution_unit = false;
639 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
640 register_execution_unit = true;
643 // If there is more than one external function in the execution unit, it
644 // needs to keep living even if it's not top level, because the result
645 // could refer to that function.
647 if (m_execution_unit_sp->GetJittedFunctions().size() > 1) {
648 register_execution_unit = true;
651 if (register_execution_unit) {
652 llvm::cast<PersistentExpressionState>(
653 exe_ctx.GetTargetPtr()->GetPersistentExpressionStateForLanguage(
655 ->RegisterExecutionUnit(m_execution_unit_sp);
659 if (generate_debug_info) {
660 lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
663 ConstString const_func_name(FunctionName());
665 jit_file.GetFilename() = const_func_name;
666 jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
667 m_jit_module_wp = jit_module_sp;
668 target->GetImages().Append(jit_module_sp);
672 if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS)
673 m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
677 /// Converts an absolute position inside a given code string into
678 /// a column/line pair.
680 /// \param[in] abs_pos
681 /// A absolute position in the code string that we want to convert
682 /// to a column/line pair.
685 /// A multi-line string usually representing source code.
688 /// The line in the code that contains the given absolute position.
689 /// The first line in the string is indexed as 1.
691 /// \param[out] column
692 /// The column in the line that contains the absolute position.
693 /// The first character in a line is indexed as 0.
694 static void AbsPosToLineColumnPos(size_t abs_pos, llvm::StringRef code,
695 unsigned &line, unsigned &column) {
696 // Reset to code position to beginning of the file.
700 assert(abs_pos <= code.size() && "Absolute position outside code string?");
702 // We have to walk up to the position and count lines/columns.
703 for (std::size_t i = 0; i < abs_pos; ++i) {
704 // If we hit a line break, we go back to column 0 and enter a new line.
705 // We only handle \n because that's what we internally use to make new
706 // lines for our temporary code strings.
707 if (code[i] == '\n') {
716 bool ClangUserExpression::Complete(ExecutionContext &exe_ctx,
717 CompletionRequest &request,
718 unsigned complete_pos) {
719 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
721 // We don't want any visible feedback when completing an expression. Mostly
722 // because the results we get from an incomplete invocation are probably not
724 DiagnosticManager diagnostic_manager;
726 if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ true))
730 log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str());
732 //////////////////////////
733 // Parse the expression
736 m_materializer_up.reset(new Materializer());
738 ResetDeclMap(exe_ctx, m_result_delegate, /*keep result in memory*/ true);
740 auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); });
742 if (!DeclMap()->WillParse(exe_ctx, m_materializer_up.get())) {
743 diagnostic_manager.PutString(
744 eDiagnosticSeverityError,
745 "current process state is unsuitable for expression parsing");
750 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
751 DeclMap()->SetLookupsEnabled(true);
754 Process *process = exe_ctx.GetProcessPtr();
755 ExecutionContextScope *exe_scope = process;
758 exe_scope = exe_ctx.GetTargetPtr();
760 ClangExpressionParser parser(exe_scope, *this, false);
762 // We have to find the source code location where the user text is inside
763 // the transformed expression code. When creating the transformed text, we
764 // already stored the absolute position in the m_transformed_text string. The
765 // only thing left to do is to transform it into the line:column format that
768 // The line and column of the user expression inside the transformed source
770 unsigned user_expr_line, user_expr_column;
771 if (m_user_expression_start_pos.hasValue())
772 AbsPosToLineColumnPos(*m_user_expression_start_pos, m_transformed_text,
773 user_expr_line, user_expr_column);
777 // The actual column where we have to complete is the start column of the
778 // user expression + the offset inside the user code that we were given.
779 const unsigned completion_column = user_expr_column + complete_pos;
780 parser.Complete(request, user_expr_line, completion_column, complete_pos);
785 bool ClangUserExpression::AddArguments(ExecutionContext &exe_ctx,
786 std::vector<lldb::addr_t> &args,
787 lldb::addr_t struct_address,
788 DiagnosticManager &diagnostic_manager) {
789 lldb::addr_t object_ptr = LLDB_INVALID_ADDRESS;
790 lldb::addr_t cmd_ptr = LLDB_INVALID_ADDRESS;
792 if (m_needs_object_ptr) {
793 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
797 ConstString object_name;
799 if (m_in_cplusplus_method) {
800 object_name.SetCString("this");
801 } else if (m_in_objectivec_method) {
802 object_name.SetCString("self");
804 diagnostic_manager.PutString(
805 eDiagnosticSeverityError,
806 "need object pointer but don't know the language");
810 Status object_ptr_error;
813 AddressType address_type;
814 object_ptr = m_ctx_obj->GetAddressOf(false, &address_type);
815 if (object_ptr == LLDB_INVALID_ADDRESS ||
816 address_type != eAddressTypeLoad)
817 object_ptr_error.SetErrorString("Can't get context object's "
820 object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error);
822 if (!object_ptr_error.Success()) {
823 exe_ctx.GetTargetRef().GetDebugger().GetAsyncOutputStream()->Printf(
824 "warning: `%s' is not accessible (substituting 0)\n",
825 object_name.AsCString());
829 if (m_in_objectivec_method) {
830 ConstString cmd_name("_cmd");
832 cmd_ptr = GetObjectPointer(frame_sp, cmd_name, object_ptr_error);
834 if (!object_ptr_error.Success()) {
835 diagnostic_manager.Printf(
836 eDiagnosticSeverityWarning,
837 "couldn't get cmd pointer (substituting NULL): %s",
838 object_ptr_error.AsCString());
843 args.push_back(object_ptr);
845 if (m_in_objectivec_method)
846 args.push_back(cmd_ptr);
848 args.push_back(struct_address);
850 args.push_back(struct_address);
855 lldb::ExpressionVariableSP ClangUserExpression::GetResultAfterDematerialization(
856 ExecutionContextScope *exe_scope) {
857 return m_result_delegate.GetVariable();
860 void ClangUserExpression::ClangUserExpressionHelper::ResetDeclMap(
861 ExecutionContext &exe_ctx,
862 Materializer::PersistentVariableDelegate &delegate,
863 bool keep_result_in_memory,
864 ValueObject *ctx_obj) {
865 m_expr_decl_map_up.reset(
866 new ClangExpressionDeclMap(keep_result_in_memory, &delegate, exe_ctx,
871 ClangUserExpression::ClangUserExpressionHelper::ASTTransformer(
872 clang::ASTConsumer *passthrough) {
873 m_result_synthesizer_up.reset(
874 new ASTResultSynthesizer(passthrough, m_top_level, m_target));
876 return m_result_synthesizer_up.get();
879 void ClangUserExpression::ClangUserExpressionHelper::CommitPersistentDecls() {
880 if (m_result_synthesizer_up) {
881 m_result_synthesizer_up->CommitPersistentDecls();
885 ConstString ClangUserExpression::ResultDelegate::GetName() {
886 auto prefix = m_persistent_state->GetPersistentVariablePrefix();
887 return m_persistent_state->GetNextPersistentVariableName(*m_target_sp,
891 void ClangUserExpression::ResultDelegate::DidDematerialize(
892 lldb::ExpressionVariableSP &variable) {
893 m_variable = variable;
896 void ClangUserExpression::ResultDelegate::RegisterPersistentState(
897 PersistentExpressionState *persistent_state) {
898 m_persistent_state = persistent_state;
901 lldb::ExpressionVariableSP &ClangUserExpression::ResultDelegate::GetVariable() {