56#include "clang/AST/DeclCXX.h"
57#include "clang/AST/DeclObjC.h"
59#include "llvm/ADT/ScopeExit.h"
72 m_type_system_helper(*m_target_wp.lock(), options.GetExecutionPolicy() ==
74 m_result_delegate(exe_scope.CalculateTarget()), m_ctx_obj(ctx_obj) {
95 LLDB_LOGF(log,
"ClangUserExpression::ScanContext()");
100 LLDB_LOGF(log,
" [CUE::SC] Settings inhibit C++ and Objective-C");
105 if (frame ==
nullptr) {
106 LLDB_LOGF(log,
" [CUE::SC] Null stack frame");
111 lldb::eSymbolContextBlock);
114 LLDB_LOGF(log,
" [CUE::SC] Null function");
121 if (!function_block) {
122 LLDB_LOGF(log,
" [CUE::SC] Null function block");
129 LLDB_LOGF(log,
" [CUE::SC] Null decl context");
153 }
else if (clang::CXXMethodDecl *method_decl =
157 lldb::VariableListSP variable_list_sp(
160 const char *thisErrorString =
"Stopped in a C++ method, but 'this' "
161 "isn't available; pretending we are in a "
164 if (!variable_list_sp) {
169 lldb::VariableSP this_var_sp(
170 variable_list_sp->FindVariable(
ConstString(
"this")));
172 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
173 !this_var_sp->LocationIsValidForFrame(frame)) {
182 }
else if (clang::ObjCMethodDecl *method_decl =
187 lldb::VariableListSP variable_list_sp(
190 const char *selfErrorString =
"Stopped in an Objective-C method, but "
191 "'self' isn't available; pretending we "
192 "are in a generic context";
194 if (!variable_list_sp) {
199 lldb::VariableSP self_variable_sp =
200 variable_list_sp->FindVariable(
ConstString(
"self"));
202 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
203 !self_variable_sp->LocationIsValidForFrame(frame)) {
212 if (!method_decl->isInstanceMethod())
215 }
else if (clang::FunctionDecl *function_decl =
229 lldb::VariableListSP variable_list_sp(
232 const char *thisErrorString =
"Stopped in a context claiming to "
233 "capture a C++ object pointer, but "
234 "'this' isn't available; pretending we "
235 "are in a generic context";
237 if (!variable_list_sp) {
242 lldb::VariableSP this_var_sp(
243 variable_list_sp->FindVariable(
ConstString(
"this")));
245 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
246 !this_var_sp->LocationIsValidForFrame(frame)) {
256 lldb::VariableListSP variable_list_sp(
259 const char *selfErrorString =
260 "Stopped in a context claiming to capture an Objective-C object "
261 "pointer, but 'self' isn't available; pretending we are in a "
264 if (!variable_list_sp) {
269 lldb::VariableSP self_variable_sp =
270 variable_list_sp->FindVariable(
ConstString(
"self"));
272 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
273 !self_variable_sp->LocationIsValidForFrame(frame)) {
278 Type *self_type = self_variable_sp->GetType();
287 if (!self_clang_type) {
316 const std::string from =
"(int)[";
317 const std::string to =
"(int)(long long)[";
321 while ((offset = expr.find(from)) != expr.npos)
322 expr.replace(offset, from.size(), to);
329 target->GetPersistentExpressionStateForLanguage(
331 m_clang_state = llvm::cast<ClangPersistentVariables>(persistent_state);
336 "couldn't start parsing (no persistent data)");
341 "error: couldn't start parsing (no target)");
352 auto *persistent_state = llvm::cast<ClangPersistentVariables>(
354 if (!persistent_state)
357 std::shared_ptr<ClangModulesDeclVendor> decl_vendor =
358 persistent_state->GetClangModulesDeclVendor();
378 persistent_state->GetHandLoadedClangModules();
379 if (decl_vendor->AddModulesForCompileUnit(*sc.
comp_unit, modules_for_macros,
384 if (!error_stream.
Empty()) {
394 "Unknown error while loading modules needed for "
395 "current compilation unit.");
400 "Top level expressions aren't wrapped.");
403 return Kind::CppMemberFunction;
406 return Kind::ObjCStaticMethod;
407 return Kind::ObjCInstanceMethod;
411 return Kind::Function;
416 std::vector<std::string> modules_to_import,
bool for_completion) {
427 for_completion, modules_to_import)) {
429 "couldn't construct expression body");
435 std::size_t original_start;
436 std::size_t original_end;
461 LLDB_LOG(log,
"[C++ module config] {0}", msg);
496 llvm::DenseSet<SymbolFile *> visited_symbol_files;
498 visited_symbol_files, [&files](
Module &module) {
502 for (
const FileSpec &f : support_files) {
509 LLDB_LOG(log,
"[C++ module config] Found {0} support files to analyze",
513 LLDB_LOGV(log,
"[C++ module config] Analyzing support file: {0}",
525 bool for_completion) {
559 bool keep_result_in_memory,
bool generate_debug_info) {
564 auto on_exit = llvm::make_scope_exit([
this]() {
ResetDeclMap(); });
569 "current process state is unsuitable for expression parsing");
577 m_parser = std::make_unique<ClangExpressionParser>(
580 unsigned num_errors =
m_parser->Parse(diagnostic_manager);
586 if (
m_parser->RewriteExpression(diagnostic_manager)) {
595 m_fixed_text.substr(fixed_start, fixed_end - fixed_start);
612 const char *error_cstr = jit_error.
AsCString();
613 if (error_cstr && error_cstr[0])
617 "expression can't be interpreted or run");
631 LLDB_LOG(log,
"List of imported modules in expression: {0}",
634 LLDB_LOG(log,
"List of include directories gathered for modules: {0}",
649 bool keep_result_in_memory,
650 bool generate_debug_info) {
679 bool parse_success =
TryParse(diagnostic_manager, exe_scope, exe_ctx,
680 execution_policy, keep_result_in_memory,
681 generate_debug_info);
699 parse_success =
TryParse(retry_manager, exe_scope, exe_ctx,
700 execution_policy, keep_result_in_memory,
701 generate_debug_info);
704 diagnostic_manager = std::move(retry_manager);
711 Status static_init_error =
714 if (!static_init_error.
Success()) {
715 const char *error_cstr = static_init_error.
AsCString();
716 if (error_cstr && error_cstr[0])
722 "couldn't run static initializers\n");
728 bool register_execution_unit =
false;
731 register_execution_unit =
true;
739 register_execution_unit =
true;
742 if (register_execution_unit) {
743 if (
auto *persistent_state =
750 if (generate_debug_info) {
757 jit_module_sp->SetFileSpecAndObjectName(jit_file,
ConstString());
786 unsigned &line,
unsigned &column) {
791 assert(abs_pos <= code.size() &&
"Absolute position outside code string?");
794 for (std::size_t i = 0; i < abs_pos; ++i) {
798 if (code[i] ==
'\n') {
809 unsigned complete_pos) {
830 auto on_exit = llvm::make_scope_exit([
this]() {
ResetDeclMap(); });
835 "current process state is unsuitable for expression parsing");
860 unsigned user_expr_line, user_expr_column;
863 user_expr_line, user_expr_column);
869 const unsigned completion_column = user_expr_column + complete_pos;
870 parser.
Complete(request, user_expr_line, completion_column, complete_pos);
883 if (
auto thisChildSP = valobj_sp->GetChildMemberWithName(
"this",
true)) {
884 valobj_sp = thisChildSP;
887 if (!err.
Success() || !valobj_sp.get())
894 "Couldn't load '%s' because its value couldn't be evaluated",
903 std::vector<lldb::addr_t> &args,
910 lldb::StackFrameSP frame_sp = exe_ctx.
GetFrameSP();
923 "need object pointer but don't know the language");
945 if (!object_ptr_error.
Success()) {
947 "warning: `%s' is not accessible (substituting 0). %s\n",
957 if (!object_ptr_error.
Success()) {
958 diagnostic_manager.
Printf(
960 "couldn't get cmd pointer (substituting NULL): %s",
966 args.push_back(object_ptr);
969 args.push_back(cmd_ptr);
971 args.push_back(struct_address);
973 args.push_back(struct_address);
988 bool keep_result_in_memory,
990 std::shared_ptr<ClangASTImporter> ast_importer;
991 auto *state = exe_ctx.
GetTargetSP()->GetPersistentExpressionStateForLanguage(
994 auto *persistent_vars = llvm::cast<ClangPersistentVariables>(state);
995 ast_importer = persistent_vars->GetClangASTImporter();
998 keep_result_in_memory, &delegate, exe_ctx.
GetTargetSP(), ast_importer,
1004 clang::ASTConsumer *passthrough) {
1005 m_result_synthesizer_up = std::make_unique<ASTResultSynthesizer>(
1006 passthrough, m_top_level,
m_target);
1008 return m_result_synthesizer_up.get();
1012 if (m_result_synthesizer_up) {
1013 m_result_synthesizer_up->CommitPersistentDecls();
1018 return m_persistent_state->GetNextPersistentVariableName(
false);
1022 lldb::ExpressionVariableSP &variable) {
1023 m_variable = variable;
1028 m_persistent_state = persistent_state;
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_LOGV(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)
bool WillParse(ExecutionContext &exe_ctx, Materializer *materializer)
Enable the state needed for parsing and IR transformation.
"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
std::string GetNextExprFileName()
Returns the next file name that should be used for user expressions.
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
void RegisterPersistentState(PersistentExpressionState *persistent_state)
lldb::ExpressionVariableSP & GetVariable()
void DidDematerialize(lldb::ExpressionVariableSP &variable) override
ConstString GetName() override
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
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)
lldb::addr_t GetCppObjectPointer(lldb::StackFrameSP frame, ConstString &object_name, Status &err)
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.
bool TryParse(DiagnosticManager &diagnostic_manager, ExecutionContextScope *exe_scope, 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::unique_ptr< ClangExpressionParser > m_parser
The parser instance we used to parse the expression.
void SetupCppModuleImports(ExecutionContext &exe_ctx)
~ClangUserExpression() override
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.
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
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.
ClangPersistentVariables * m_clang_state
ClangUserExpression(ExecutionContextScope &exe_scope, llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, ResultType desired_type, const EvaluateExpressionOptions &options, ValueObject *ctx_obj)
Constructor.
void ScanContext(ExecutionContext &exe_ctx, lldb_private::Status &err) override
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.
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.
const FileSpecList & GetSupportFiles()
Get the compile unit's support file list.
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.
void SetCString(const char *cstr)
Set the C string value.
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
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::StreamSP GetAsyncOutputStream()
size_t Printf(DiagnosticSeverity severity, const char *format,...) __attribute__((format(printf
size_t void PutString(DiagnosticSeverity severity, llvm::StringRef str)
const std::string & GetFixedExpression()
ExecutionPolicy GetExecutionPolicy() const
"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.
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.
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.
"lldb/Expression/LLVMUserExpression.h" Encapsulates a one-time expression for use in lldb.
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
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.
lldb::CompUnitSP GetCompileUnitAtIndex(size_t idx)
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.
const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
Block * GetFrameBlock()
Get the current lexical scope block for this StackFrame, if possible.
int SetErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Set the current error string to a formatted error string.
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
void SetErrorString(llvm::StringRef err_str)
Set the current error string to err_str.
bool Success() const
Test for success condition.
llvm::StringRef GetString() const
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
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 ClangASTMetadata * DeclContextGetMetaData(const CompilerDeclContext &dc, const clang::Decl *object)
static bool IsObjCObjectPointerType(const CompilerType &type, CompilerType *target_type=nullptr)
CompilerType GetForwardCompilerType()
std::string m_fixed_text
The text of the expression with fix-its applied.
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, ConstString &object_name, Status &err)
lldb::LanguageType m_language
The language to use when parsing (eLanguageTypeUnknown means use defaults)
static lldb::ValueObjectSP GetObjectPointerValueObject(lldb::StackFrameSP frame, ConstString const &object_name, Status &err)
Return ValueObject for a given variable name in the current stack frame.
virtual lldb::addr_t GetAddressOf(bool scalar_is_load_address=true, AddressType *address_type=nullptr)
virtual lldb::LanguageType GetObjectRuntimeLanguage()
#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.
@ eDiagnosticSeverityError
@ eDiagnosticSeverityWarning
@ eDiagnosticSeverityRemark
ExecutionPolicy
Expression execution policies.
@ eExecutionPolicyTopLevel
@ eImportStdModuleFallback
@ eAddressTypeLoad
Address is an address as in the current target inferior process.
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.