56#include "clang/AST/DeclCXX.h"
57#include "clang/AST/DeclObjC.h"
59#include "clang/Basic/DiagnosticSema.h"
60#include "llvm/ADT/STLExtras.h"
61#include "llvm/ADT/ScopeExit.h"
62#include "llvm/BinaryFormat/Dwarf.h"
78 case llvm::dwarf::DW_LNAME_C_plus_plus:
81 case llvm::dwarf::DW_LNAME_ObjC:
84 case llvm::dwarf::DW_LNAME_ObjC_plus_plus:
98 LLDB_LOGF(log,
"ClangUserExpression::ScanContext()");
103 LLDB_LOGF(log,
" [CUE::SC] Settings inhibit C++ and Objective-C");
108 if (frame ==
nullptr) {
109 LLDB_LOGF(log,
" [CUE::SC] Null stack frame");
114 lldb::eSymbolContextBlock);
117 LLDB_LOGF(log,
" [CUE::SC] Null function");
124 if (!function_block) {
125 LLDB_LOGF(log,
" [CUE::SC] Null function block");
132 LLDB_LOGF(log,
" [CUE::SC] Null decl context");
137 switch (
m_ctx_obj->GetObjectRuntimeLanguage()) {
156 }
else if (clang::CXXMethodDecl *method_decl =
163 const char *msg =
"Stopped in a C++ method, but 'this' isn't "
164 "available; pretending we are in a generic context";
166 if (!variable_list_sp) {
173 variable_list_sp->FindVariable(
ConstString(
"this")));
175 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
176 !this_var_sp->LocationIsValidForFrame(frame)) {
186 }
else if (clang::ObjCMethodDecl *method_decl =
194 const char *msg =
"Stopped in an Objective-C method, but 'self' isn't "
195 "available; pretending we are in a generic context";
197 if (!variable_list_sp) {
204 variable_list_sp->FindVariable(
ConstString(
"self"));
206 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
207 !self_variable_sp->LocationIsValidForFrame(frame)) {
217 if (!method_decl->isInstanceMethod())
220 }
else if (clang::FunctionDecl *function_decl =
228 if (std::optional<ClangASTMetadata> metadata =
231 metadata && metadata->HasObjectPtr()) {
238 const char *msg =
"Stopped in a context claiming to capture a C++ "
239 "object pointer, but 'this' isn't available; "
240 "pretending we are in a generic context";
242 if (!variable_list_sp) {
249 variable_list_sp->FindVariable(
ConstString(
"this")));
251 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
252 !this_var_sp->LocationIsValidForFrame(frame)) {
266 const char *msg =
"Stopped in a context claiming to capture an "
267 "Objective-C object pointer, but 'self' isn't "
268 "available; pretending we are in a generic context";
270 if (!variable_list_sp) {
277 variable_list_sp->FindVariable(
ConstString(
"self"));
279 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
280 !self_variable_sp->LocationIsValidForFrame(frame)) {
286 Type *self_type = self_variable_sp->GetType();
296 if (!self_clang_type) {
327 const std::string from =
"(int)[";
328 const std::string to =
"(int)(long long)[";
332 while ((offset = expr.find(from)) != expr.npos)
333 expr.replace(offset, from.size(), to);
340 target->GetPersistentExpressionStateForLanguage(
342 m_clang_state = llvm::cast<ClangPersistentVariables>(persistent_state);
351 "error: couldn't start parsing (no target)");
362 auto *persistent_state = llvm::cast<ClangPersistentVariables>(
364 if (!persistent_state)
367 std::shared_ptr<ClangModulesDeclVendor> decl_vendor =
368 persistent_state->GetClangModulesDeclVendor();
386 persistent_state->GetHandLoadedClangModules();
389 decl_vendor->AddModulesForCompileUnit(*sc.
comp_unit, modules_for_macros);
396 llvm::handleAllErrors(std::move(err), [](
const llvm::StringError &e) {
403 "Top level expressions aren't wrapped.");
406 return Kind::CppMemberFunction;
409 return Kind::ObjCStaticMethod;
410 return Kind::ObjCInstanceMethod;
414 return Kind::Function;
419 std::vector<std::string> modules_to_import,
bool for_completion) {
430 for_completion, modules_to_import,
431 m_options.GetCppIgnoreContextQualifiers())) {
433 "couldn't construct expression body");
439 std::size_t original_start;
440 std::size_t original_end;
465 LLDB_LOG(log,
"[C++ module config] {0}", msg);
500 llvm::DenseSet<SymbolFile *> visited_symbol_files;
502 visited_symbol_files, [&files](
Module &module) {
505 module.GetCompileUnitAtIndex(i)->GetSupportFiles();
506 for (
auto &f : support_files) {
513 LLDB_LOG(log,
"[C++ module config] Found {0} support files to analyze",
516 for (
auto &f : files)
529 bool for_completion) {
563 bool generate_debug_info) {
573 "current process state is unsuitable for expression parsing");
581 m_parser = std::make_unique<ClangExpressionParser>(
585 unsigned num_errors =
m_parser->Parse(diagnostic_manager);
591 if (
m_parser->RewriteExpression(diagnostic_manager)) {
600 m_fixed_text.substr(fixed_start, fixed_end - fixed_start);
617 const char *error_cstr = jit_error.
AsCString();
618 if (error_cstr && error_cstr[0])
622 "expression can't be interpreted or run");
637 LLDB_LOG(log,
"List of imported modules in expression: {0}",
640 LLDB_LOG(log,
"List of include directories gathered for modules: {0}",
655 bool keep_result_in_memory,
656 bool generate_debug_info) {
679 bool parse_success =
TryParse(diagnostic_manager, exe_ctx, execution_policy,
680 keep_result_in_memory, generate_debug_info);
698 parse_success =
TryParse(retry_manager, exe_ctx, execution_policy,
699 keep_result_in_memory, generate_debug_info);
702 diagnostic_manager = std::move(retry_manager);
709 bool register_execution_unit =
false;
712 register_execution_unit =
true;
720 register_execution_unit =
true;
723 if (register_execution_unit) {
724 if (
auto *persistent_state =
731 if (generate_debug_info) {
738 jit_module_sp->SetFileSpecAndObjectName(jit_file,
ConstString());
768 unsigned &line,
unsigned &column) {
773 assert(abs_pos <= code.size() &&
"Absolute position outside code string?");
776 for (std::size_t i = 0; i < abs_pos; ++i) {
780 if (code[i] ==
'\n') {
791 unsigned complete_pos) {
817 "current process state is unsuitable for expression parsing");
827 false, diagnostic_manager);
837 unsigned user_expr_line, user_expr_column;
840 user_expr_line, user_expr_column);
846 const unsigned completion_column = user_expr_column + complete_pos;
847 parser.
Complete(request, user_expr_line, completion_column, complete_pos);
860 if (
auto thisChildSP = valobj_sp->GetChildMemberWithName(
"this")) {
861 valobj_sp = thisChildSP;
864 if (!err.
Success() || !valobj_sp.get())
871 "Couldn't load '{0}' because its value couldn't be evaluated",
880 std::vector<lldb::addr_t> &args,
894 "need object pointer but don't know the language");
898 static constexpr llvm::StringLiteral g_cplusplus_object_name(
"this");
899 static constexpr llvm::StringLiteral g_objc_object_name(
"self");
900 llvm::StringRef object_name =
922 if (!object_ptr_error.
Success()) {
924 "warning: `{0}' is not accessible (substituting 0). {1}\n",
925 object_name, object_ptr_error.
AsCString());
930 static constexpr llvm::StringLiteral cmd_name(
"_cmd");
934 if (!object_ptr_error.
Success()) {
935 diagnostic_manager.
Printf(
937 "couldn't get cmd pointer (substituting NULL): %s",
943 args.push_back(object_ptr);
946 args.push_back(cmd_ptr);
948 args.push_back(struct_address);
950 args.push_back(struct_address);
962 const bool is_fixable_cvr_error = llvm::any_of(
964 [](std::unique_ptr<Diagnostic>
const &diag) {
965 switch (diag->GetCompilerID()) {
966 case clang::diag::err_member_function_call_bad_cvr:
967 case clang::diag::err_typecheck_assign_const_method:
975 if (!is_fixable_cvr_error)
980 if (m_options.GetCppIgnoreContextQualifiers()) {
984 "CppIgnoreContextQualifiers didn't resolve compiler diagnostic.");
988 diagnostic_manager.Printf(
990 "Possibly trying to mutate object in a const context. Try "
991 "running the expression with: expression --c++-ignore-context-qualifiers "
993 !m_fixed_text.empty() ? m_fixed_text.c_str() : m_expr_text.c_str());
998 if (llvm::none_of(diagnostic_manager.
Diagnostics(),
999 [](std::unique_ptr<Diagnostic>
const &diag) {
1000 switch (diag->GetCompilerID()) {
1003 case clang::diag::err_no_template:
1004 case clang::diag::err_non_template_in_template_id:
1012 diagnostic_manager.AddDiagnostic(
1013 "Naming template instantiation not yet supported. Template functions "
1014 "can be invoked via their mangled name. For example, using "
1015 "`_Z3fooIiEvi(123)` for `foo<int>(123)`",
1031 bool ignore_context_qualifiers) {
1032 std::shared_ptr<ClangASTImporter> ast_importer;
1033 auto *state = exe_ctx.
GetTargetSP()->GetPersistentExpressionStateForLanguage(
1036 auto *persistent_vars = llvm::cast<ClangPersistentVariables>(state);
1037 ast_importer = persistent_vars->GetClangASTImporter();
1040 keep_result_in_memory, &delegate, exe_ctx.
GetTargetSP(), ast_importer,
1041 ctx_obj, ignore_context_qualifiers);
1046 clang::ASTConsumer *passthrough) {
static bool shouldRetryWithCppModule(Target &target, ExecutionPolicy exe_policy)
CppModuleConfiguration GetModuleConfig(lldb::LanguageType language, ExecutionContext &exe_ctx)
static CppModuleConfiguration LogConfigError(const std::string &msg)
Utility method that puts a message into the expression log and returns an invalid module configuratio...
static void AbsPosToLineColumnPos(size_t abs_pos, llvm::StringRef code, unsigned &line, unsigned &column)
Converts an absolute position inside a given code string into a column/line pair.
static void SetupDeclVendor(ExecutionContext &exe_ctx, Target *target, DiagnosticManager &diagnostic_manager)
static bool SupportsCxxModuleImport(lldb::LanguageType language)
static void ApplyObjcCastHack(std::string &expr)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
#define LLDB_LOGF(log,...)
#define LLDB_LOG_VERBOSE(log,...)
llvm::Triple & GetTriple()
Architecture triple accessor.
A class that describes a single lexical block.
lldb::VariableListSP GetBlockVariableList(bool can_create)
Get the variable list for this block only.
void CalculateSymbolContext(SymbolContext *sc) override
Reconstruct the object's symbol context into sc.
CompilerDeclContext GetDeclContext()
void SetLookupsEnabled(bool lookups_enabled)
"lldb/Expression/ClangExpressionParser.h" Encapsulates an instance of Clang that can parse expression...
bool Complete(CompletionRequest &request, unsigned line, unsigned pos, unsigned typed_pos) override
Attempts to find possible command line completions for the given expression.
WrapKind
The possible ways an expression can be wrapped.
static ClangExpressionSourceCode * CreateWrapped(llvm::StringRef filename, llvm::StringRef prefix, llvm::StringRef body, WrapKind wrap_kind)
std::vector< ModuleID > ModuleVector
void CommitPersistentDecls() override
clang::ASTConsumer * ASTTransformer(clang::ASTConsumer *passthrough) override
Return the object that the parser should allow to access ASTs.
std::unique_ptr< ClangExpressionDeclMap > m_expr_decl_map_up
std::unique_ptr< ASTResultSynthesizer > m_result_synthesizer_up
PersistentExpressionState * m_persistent_state
void RegisterPersistentState(PersistentExpressionState *persistent_state)
lldb::ExpressionVariableSP & GetVariable()
void DidDematerialize(lldb::ExpressionVariableSP &variable) override
ConstString GetName() override
lldb::ExpressionVariableSP m_variable
void FixupTemplateLookupDiagnostics(DiagnosticManager &diagnostic_manager) const
bool m_enforce_valid_object
True if the expression parser should enforce the presence of a valid class pointer in order to genera...
std::string m_filename
File name used for the expression.
lldb::ExpressionVariableSP GetResultAfterDematerialization(ExecutionContextScope *exe_scope) override
ClangUserExpression(ExecutionContextScope &exe_scope, llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language, ResultType desired_type, const EvaluateExpressionOptions &options, ValueObject *ctx_obj)
Constructor.
bool m_in_objectivec_method
True if the expression is compiled as an Objective-C method (true if it was parsed when exe_ctx was i...
void CreateSourceCode(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, std::vector< std::string > modules_to_import, bool for_completion)
bool Complete(ExecutionContext &exe_ctx, CompletionRequest &request, unsigned complete_pos) override
Attempts to find possible command line completions for the given (possible incomplete) user expressio...
ClangExpressionSourceCode::WrapKind GetWrapKind() const
Defines how the current expression should be wrapped.
std::unique_ptr< ClangExpressionParser > m_parser
The parser instance we used to parse the expression.
void SetupCppModuleImports(ExecutionContext &exe_ctx)
~ClangUserExpression() override
void FixupParseErrorDiagnostics(DiagnosticManager &diagnostic_manager) const override
Called by expression evaluator when a parse error occurs.
bool PrepareForParsing(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, bool for_completion)
bool m_needs_object_ptr
True if "this" or "self" must be looked up and passed in.
ClangExpressionDeclMap * DeclMap()
bool SetupPersistentState(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx)
bool m_in_static_method
True if the expression is compiled as a static (or class) method (currently true if it was parsed whe...
bool Parse(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, lldb_private::ExecutionPolicy execution_policy, bool keep_result_in_memory, bool generate_debug_info) override
Parse the expression.
bool TryParse(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, lldb_private::ExecutionPolicy execution_policy, bool keep_result_in_memory, bool generate_debug_info)
Populate m_in_cplusplus_method and m_in_objectivec_method based on the environment.
std::optional< size_t > m_user_expression_start_pos
The absolute character position in the transformed source code where the user code (as typed by the u...
bool AddArguments(ExecutionContext &exe_ctx, std::vector< lldb::addr_t > &args, lldb::addr_t struct_address, DiagnosticManager &diagnostic_manager) override
void ScanContext(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx)
lldb::addr_t GetCppObjectPointer(lldb::StackFrameSP frame, llvm::StringRef object_name, Status &err)
std::unique_ptr< ClangExpressionSourceCode > m_source_code
ResultDelegate m_result_delegate
std::vector< std::string > m_imported_cpp_modules
A list of module names that should be imported when parsing.
ClangUserExpressionHelper m_type_system_helper
ClangPersistentVariables * m_clang_state
void FixupCVRParseErrorDiagnostics(DiagnosticManager &diagnostic_manager) const
bool m_in_cplusplus_method
True if the expression is compiled as a C++ member function (true if it was parsed when exe_ctx was i...
std::vector< std::string > m_include_directories
The include directories that should be used when parsing the expression.
ValueObject * m_ctx_obj
The object (if any) in which context the expression is evaluated.
const SupportFileList & GetSupportFiles()
Get the compile unit's support file list.
virtual bool ForEachExternalModule(llvm::DenseSet< lldb_private::SymbolFile * > &visited_symbol_files, llvm::function_ref< bool(Module &)> lambda)
Apply a lambda to each external lldb::Module referenced by this compilation unit.
Represents a generic declaration context in a program.
Generic representation of a type in a programming language.
"lldb/Utility/ArgCompletionRequest.h"
A uniqued constant string class.
A Clang configuration when importing C++ modules.
llvm::ArrayRef< std::string > GetIncludeDirs() const
Returns a list of include directories that should be used when using this configuration (e....
llvm::ArrayRef< std::string > GetImportedModules() const
Returns a list of (top level) modules that should be imported when using this configuration (e....
lldb::StreamUP GetAsyncOutputStream()
size_t void PutString(lldb::Severity severity, llvm::StringRef str)
const DiagnosticList & Diagnostics() const
void AddDiagnostic(llvm::StringRef message, lldb::Severity severity, DiagnosticOrigin origin, uint32_t compiler_id=LLDB_INVALID_COMPILER_ID)
size_t Printf(lldb::Severity severity, const char *format,...) __attribute__((format(printf
const std::string & GetFixedExpression()
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
ExecutionContextScope * GetBestExecutionContextScope() const
const lldb::TargetSP & GetTargetSP() const
Get accessor to get the target shared pointer.
StackFrame * GetFramePtr() const
Returns a pointer to the frame object.
const lldb::StackFrameSP & GetFrameSP() const
Get accessor to get the frame shared pointer.
Target * GetTargetPtr() const
Returns a pointer to the target object.
Target & GetTargetRef() const
Returns a reference to the target object.
Process * GetProcessPtr() const
Returns a pointer to the process object.
lldb::addr_t m_jit_end_addr
The address of the JITted function within the JIT allocation.
lldb::ProcessWP m_jit_process_wp
Expression's always have to have a target...
lldb::addr_t m_jit_start_addr
An expression might have a process, but it doesn't need to (e.g.
lldb::TargetWP m_target_wp
size_t GetSize() const
Get the number of files in the file list.
bool AppendIfUnique(const FileSpec &file)
Append a FileSpec object if unique.
void SetFilename(ConstString filename)
Filename string set accessor.
std::string m_transformed_text
The text of the expression, as send to the parser.
bool m_can_interpret
True if the expression could be evaluated statically; false otherwise.
Materializer * GetMaterializer() override
Return the Materializer that the parser should use when registering external values.
std::unique_ptr< Materializer > m_materializer_up
The materializer to use when running the expression.
bool m_allow_cxx
True if the language allows C++.
Target * m_target
The target for storing persistent data like types and variables.
lldb::ModuleWP m_jit_module_wp
LLVMUserExpression(ExecutionContextScope &exe_scope, llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language, ResultType desired_type, const EvaluateExpressionOptions &options)
std::shared_ptr< IRExecutionUnit > m_execution_unit_sp
The execution unit the expression is stored in.
bool m_allow_objc
True if the language allows Objective-C.
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
A class that describes an executable image and its associated object and symbol files.
size_t GetNumCompileUnits()
Get the number of compile units for this module.
A plug-in interface definition class for debugging a process.
This base class provides an interface to stack frames.
virtual const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
virtual Block * GetFrameBlock()
Get the current lexical scope block for this StackFrame, if possible.
static Status FromErrorString(const char *str)
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
bool Success() const
Test for success condition.
A list of support files for a CompileUnit.
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
Block * GetFunctionBlock()
Find a block that defines the function represented by this symbol context.
CompileUnit * comp_unit
The CompileUnit for a given query.
ImportStdModule GetImportStdModule() const
bool GetEnableAutoImportClangModules() const
Debugger & GetDebugger() const
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
const ModuleList & GetImages() const
Get accessor for the images for this process.
const ArchSpec & GetArchitecture() const
static clang::CXXMethodDecl * DeclContextGetAsCXXMethodDecl(const CompilerDeclContext &dc)
static clang::ObjCMethodDecl * DeclContextGetAsObjCMethodDecl(const CompilerDeclContext &dc)
static clang::FunctionDecl * DeclContextGetAsFunctionDecl(const CompilerDeclContext &dc)
static bool IsObjCClassType(const CompilerType &type)
static std::optional< ClangASTMetadata > DeclContextGetMetaData(const CompilerDeclContext &dc, const clang::Decl *object)
static bool IsObjCObjectPointerType(const CompilerType &type, CompilerType *target_type=nullptr)
CompilerType GetForwardCompilerType()
static lldb::ValueObjectSP GetObjectPointerValueObject(lldb::StackFrameSP frame, llvm::StringRef object_name, Status &err)
Return ValueObject for a given variable name in the current stack frame.
SourceLanguage m_language
The language to use when parsing (unknown means use defaults).
std::string m_fixed_text
The text of the expression with fix-its applied this won't be set if the fixed text doesn't parse.
void InstallContext(ExecutionContext &exe_ctx)
Populate m_in_cplusplus_method and m_in_objectivec_method based on the environment.
std::string m_expr_prefix
The text of the translation-level definitions, as provided by the user.
const char * FunctionName() override
Return the function name that should be used for executing the expression.
std::string m_expr_text
The text of the expression, as typed by the user.
EvaluateExpressionOptions m_options
Additional options provided by the user.
static lldb::addr_t GetObjectPointer(lldb::StackFrameSP frame_sp, llvm::StringRef object_name, Status &err)
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
ExecutionPolicy
Expression execution policies.
@ eExecutionPolicyTopLevel
@ eImportStdModuleFallback
@ eAddressTypeLoad
Address is an address as in the current target inferior process.
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::ExpressionVariable > ExpressionVariableSP
LanguageType
Programming language type.
@ eLanguageTypeC_plus_plus_14
ISO C++:2014.
@ eLanguageTypeC11
ISO C:2011.
@ eLanguageTypeC99
ISO C:1999.
@ eLanguageTypeC_plus_plus_03
ISO C++:2003.
@ eLanguageTypeObjC_plus_plus
Objective-C++.
@ eLanguageTypeC_plus_plus_11
ISO C++:2011.
@ eLanguageTypeC89
ISO C:1989.
@ eLanguageTypeC
Non-standardized C, such as K&R.
@ eLanguageTypeObjC
Objective-C.
@ eLanguageTypeC_plus_plus
ISO C++:1998.
std::shared_ptr< lldb_private::VariableList > VariableListSP
std::weak_ptr< lldb_private::Process > ProcessWP
std::shared_ptr< lldb_private::Variable > VariableSP
std::shared_ptr< lldb_private::Module > ModuleSP
A type-erased pair of llvm::dwarf::SourceLanguageName and version.