LLDB mainline
ClangUserExpression.cpp
Go to the documentation of this file.
1//===-- ClangUserExpression.cpp -------------------------------------------===//
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 <cstdio>
10#include <sys/types.h>
11
12#include <cstdlib>
13#include <map>
14#include <string>
15
16#include "ClangUserExpression.h"
17
19#include "ClangASTMetadata.h"
20#include "ClangDiagnostic.h"
26
28#include "lldb/Core/Debugger.h"
29#include "lldb/Core/Module.h"
36#include "lldb/Host/HostInfo.h"
37#include "lldb/Symbol/Block.h"
43#include "lldb/Symbol/Type.h"
46#include "lldb/Target/Process.h"
48#include "lldb/Target/Target.h"
53#include "lldb/Utility/Log.h"
55
56#include "clang/AST/DeclCXX.h"
57#include "clang/AST/DeclObjC.h"
58
59#include "llvm/ADT/ScopeExit.h"
60
61using namespace lldb_private;
62
64
66 ExecutionContextScope &exe_scope, llvm::StringRef expr,
67 llvm::StringRef prefix, lldb::LanguageType language,
68 ResultType desired_type, const EvaluateExpressionOptions &options,
69 ValueObject *ctx_obj)
70 : LLVMUserExpression(exe_scope, expr, prefix, language, desired_type,
71 options),
72 m_type_system_helper(*m_target_wp.lock(), options.GetExecutionPolicy() ==
74 m_result_delegate(exe_scope.CalculateTarget()), m_ctx_obj(ctx_obj) {
75 switch (m_language) {
77 m_allow_cxx = true;
78 break;
80 m_allow_objc = true;
81 break;
83 default:
84 m_allow_cxx = true;
85 m_allow_objc = true;
86 break;
87 }
88}
89
91
94
95 LLDB_LOGF(log, "ClangUserExpression::ScanContext()");
96
97 m_target = exe_ctx.GetTargetPtr();
98
99 if (!(m_allow_cxx || m_allow_objc)) {
100 LLDB_LOGF(log, " [CUE::SC] Settings inhibit C++ and Objective-C");
101 return;
102 }
103
104 StackFrame *frame = exe_ctx.GetFramePtr();
105 if (frame == nullptr) {
106 LLDB_LOGF(log, " [CUE::SC] Null stack frame");
107 return;
108 }
109
110 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
111 lldb::eSymbolContextBlock);
112
113 if (!sym_ctx.function) {
114 LLDB_LOGF(log, " [CUE::SC] Null function");
115 return;
116 }
117
118 // Find the block that defines the function represented by "sym_ctx"
119 Block *function_block = sym_ctx.GetFunctionBlock();
120
121 if (!function_block) {
122 LLDB_LOGF(log, " [CUE::SC] Null function block");
123 return;
124 }
125
126 CompilerDeclContext decl_context = function_block->GetDeclContext();
127
128 if (!decl_context) {
129 LLDB_LOGF(log, " [CUE::SC] Null decl context");
130 return;
131 }
132
133 if (m_ctx_obj) {
144 break;
148 break;
149 default:
150 break;
151 }
152 m_needs_object_ptr = true;
153 } else if (clang::CXXMethodDecl *method_decl =
155 if (m_allow_cxx && method_decl->isInstance()) {
157 lldb::VariableListSP variable_list_sp(
158 function_block->GetBlockVariableList(true));
159
160 const char *thisErrorString = "Stopped in a C++ method, but 'this' "
161 "isn't available; pretending we are in a "
162 "generic context";
163
164 if (!variable_list_sp) {
165 err.SetErrorString(thisErrorString);
166 return;
167 }
168
169 lldb::VariableSP this_var_sp(
170 variable_list_sp->FindVariable(ConstString("this")));
171
172 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
173 !this_var_sp->LocationIsValidForFrame(frame)) {
174 err.SetErrorString(thisErrorString);
175 return;
176 }
177 }
178
180 m_needs_object_ptr = true;
181 }
182 } else if (clang::ObjCMethodDecl *method_decl =
184 decl_context)) {
185 if (m_allow_objc) {
187 lldb::VariableListSP variable_list_sp(
188 function_block->GetBlockVariableList(true));
189
190 const char *selfErrorString = "Stopped in an Objective-C method, but "
191 "'self' isn't available; pretending we "
192 "are in a generic context";
193
194 if (!variable_list_sp) {
195 err.SetErrorString(selfErrorString);
196 return;
197 }
198
199 lldb::VariableSP self_variable_sp =
200 variable_list_sp->FindVariable(ConstString("self"));
201
202 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
203 !self_variable_sp->LocationIsValidForFrame(frame)) {
204 err.SetErrorString(selfErrorString);
205 return;
206 }
207 }
208
210 m_needs_object_ptr = true;
211
212 if (!method_decl->isInstanceMethod())
213 m_in_static_method = true;
214 }
215 } else if (clang::FunctionDecl *function_decl =
217 // We might also have a function that said in the debug information that it
218 // captured an object pointer. The best way to deal with getting to the
219 // ivars at present is by pretending that this is a method of a class in
220 // whatever runtime the debug info says the object pointer belongs to. Do
221 // that here.
222
223 ClangASTMetadata *metadata =
224 TypeSystemClang::DeclContextGetMetaData(decl_context, function_decl);
225 if (metadata && metadata->HasObjectPtr()) {
226 lldb::LanguageType language = metadata->GetObjectPtrLanguage();
227 if (language == lldb::eLanguageTypeC_plus_plus) {
229 lldb::VariableListSP variable_list_sp(
230 function_block->GetBlockVariableList(true));
231
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";
236
237 if (!variable_list_sp) {
238 err.SetErrorString(thisErrorString);
239 return;
240 }
241
242 lldb::VariableSP this_var_sp(
243 variable_list_sp->FindVariable(ConstString("this")));
244
245 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
246 !this_var_sp->LocationIsValidForFrame(frame)) {
247 err.SetErrorString(thisErrorString);
248 return;
249 }
250 }
251
253 m_needs_object_ptr = true;
254 } else if (language == lldb::eLanguageTypeObjC) {
256 lldb::VariableListSP variable_list_sp(
257 function_block->GetBlockVariableList(true));
258
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 "
262 "generic context";
263
264 if (!variable_list_sp) {
265 err.SetErrorString(selfErrorString);
266 return;
267 }
268
269 lldb::VariableSP self_variable_sp =
270 variable_list_sp->FindVariable(ConstString("self"));
271
272 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
273 !self_variable_sp->LocationIsValidForFrame(frame)) {
274 err.SetErrorString(selfErrorString);
275 return;
276 }
277
278 Type *self_type = self_variable_sp->GetType();
279
280 if (!self_type) {
281 err.SetErrorString(selfErrorString);
282 return;
283 }
284
285 CompilerType self_clang_type = self_type->GetForwardCompilerType();
286
287 if (!self_clang_type) {
288 err.SetErrorString(selfErrorString);
289 return;
290 }
291
292 if (TypeSystemClang::IsObjCClassType(self_clang_type)) {
293 return;
295 self_clang_type)) {
297 m_needs_object_ptr = true;
298 } else {
299 err.SetErrorString(selfErrorString);
300 return;
301 }
302 } else {
304 m_needs_object_ptr = true;
305 }
306 }
307 }
308 }
309}
310
311// This is a really nasty hack, meant to fix Objective-C expressions of the
312// form (int)[myArray count]. Right now, because the type information for
313// count is not available, [myArray count] returns id, which can't be directly
314// cast to int without causing a clang error.
315static void ApplyObjcCastHack(std::string &expr) {
316 const std::string from = "(int)[";
317 const std::string to = "(int)(long long)[";
318
319 size_t offset;
320
321 while ((offset = expr.find(from)) != expr.npos)
322 expr.replace(offset, from.size(), to);
323}
324
326 ExecutionContext &exe_ctx) {
327 if (Target *target = exe_ctx.GetTargetPtr()) {
328 if (PersistentExpressionState *persistent_state =
329 target->GetPersistentExpressionStateForLanguage(
331 m_clang_state = llvm::cast<ClangPersistentVariables>(persistent_state);
333 } else {
334 diagnostic_manager.PutString(
336 "couldn't start parsing (no persistent data)");
337 return false;
338 }
339 } else {
340 diagnostic_manager.PutString(eDiagnosticSeverityError,
341 "error: couldn't start parsing (no target)");
342 return false;
343 }
344 return true;
345}
346
347static void SetupDeclVendor(ExecutionContext &exe_ctx, Target *target,
348 DiagnosticManager &diagnostic_manager) {
349 if (!target->GetEnableAutoImportClangModules())
350 return;
351
352 auto *persistent_state = llvm::cast<ClangPersistentVariables>(
354 if (!persistent_state)
355 return;
356
357 std::shared_ptr<ClangModulesDeclVendor> decl_vendor =
358 persistent_state->GetClangModulesDeclVendor();
359 if (!decl_vendor)
360 return;
361
362 StackFrame *frame = exe_ctx.GetFramePtr();
363 if (!frame)
364 return;
365
366 Block *block = frame->GetFrameBlock();
367 if (!block)
368 return;
369 SymbolContext sc;
370
371 block->CalculateSymbolContext(&sc);
372
373 if (!sc.comp_unit)
374 return;
375 StreamString error_stream;
376
377 ClangModulesDeclVendor::ModuleVector modules_for_macros =
378 persistent_state->GetHandLoadedClangModules();
379 if (decl_vendor->AddModulesForCompileUnit(*sc.comp_unit, modules_for_macros,
380 error_stream))
381 return;
382
383 // Failed to load some modules, so emit the error stream as a diagnostic.
384 if (!error_stream.Empty()) {
385 // The error stream already contains several Clang diagnostics that might
386 // be either errors or warnings, so just print them all as one remark
387 // diagnostic to prevent that the message starts with "error: error:".
388 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
389 error_stream.GetString());
390 return;
391 }
392
393 diagnostic_manager.PutString(eDiagnosticSeverityError,
394 "Unknown error while loading modules needed for "
395 "current compilation unit.");
396}
397
400 "Top level expressions aren't wrapped.");
403 return Kind::CppMemberFunction;
404 else if (m_in_objectivec_method) {
406 return Kind::ObjCStaticMethod;
407 return Kind::ObjCInstanceMethod;
408 }
409 // Not in any kind of 'special' function, so just wrap it in a normal C
410 // function.
411 return Kind::Function;
412}
413
415 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
416 std::vector<std::string> modules_to_import, bool for_completion) {
417
418 std::string prefix = m_expr_prefix;
419
422 } else {
424 m_filename, prefix, m_expr_text, GetWrapKind()));
425
426 if (!m_source_code->GetText(m_transformed_text, exe_ctx, !m_ctx_obj,
427 for_completion, modules_to_import)) {
428 diagnostic_manager.PutString(eDiagnosticSeverityError,
429 "couldn't construct expression body");
430 return;
431 }
432
433 // Find and store the start position of the original code inside the
434 // transformed code. We need this later for the code completion.
435 std::size_t original_start;
436 std::size_t original_end;
437 bool found_bounds = m_source_code->GetOriginalBodyBounds(
438 m_transformed_text, original_start, original_end);
439 if (found_bounds)
440 m_user_expression_start_pos = original_start;
441 }
442}
443
445 switch (language) {
451 return true;
452 default:
453 return false;
454 }
455}
456
457/// Utility method that puts a message into the expression log and
458/// returns an invalid module configuration.
459static CppModuleConfiguration LogConfigError(const std::string &msg) {
461 LLDB_LOG(log, "[C++ module config] {0}", msg);
462 return CppModuleConfiguration();
463}
464
466 ExecutionContext &exe_ctx) {
468
469 // Don't do anything if this is not a C++ module configuration.
470 if (!SupportsCxxModuleImport(language))
471 return LogConfigError("Language doesn't support C++ modules");
472
473 Target *target = exe_ctx.GetTargetPtr();
474 if (!target)
475 return LogConfigError("No target");
476
477 StackFrame *frame = exe_ctx.GetFramePtr();
478 if (!frame)
479 return LogConfigError("No frame");
480
481 Block *block = frame->GetFrameBlock();
482 if (!block)
483 return LogConfigError("No block");
484
485 SymbolContext sc;
486 block->CalculateSymbolContext(&sc);
487 if (!sc.comp_unit)
488 return LogConfigError("Couldn't calculate symbol context");
489
490 // Build a list of files we need to analyze to build the configuration.
491 FileSpecList files;
492 for (const FileSpec &f : sc.comp_unit->GetSupportFiles())
493 files.AppendIfUnique(f);
494 // We also need to look at external modules in the case of -gmodules as they
495 // contain the support files for libc++ and the C library.
496 llvm::DenseSet<SymbolFile *> visited_symbol_files;
498 visited_symbol_files, [&files](Module &module) {
499 for (std::size_t i = 0; i < module.GetNumCompileUnits(); ++i) {
500 const FileSpecList &support_files =
501 module.GetCompileUnitAtIndex(i)->GetSupportFiles();
502 for (const FileSpec &f : support_files) {
503 files.AppendIfUnique(f);
504 }
505 }
506 return false;
507 });
508
509 LLDB_LOG(log, "[C++ module config] Found {0} support files to analyze",
510 files.GetSize());
511 if (log && log->GetVerbose()) {
512 for (const FileSpec &f : files)
513 LLDB_LOGV(log, "[C++ module config] Analyzing support file: {0}",
514 f.GetPath());
515 }
516
517 // Try to create a configuration from the files. If there is no valid
518 // configuration possible with the files, this just returns an invalid
519 // configuration.
520 return CppModuleConfiguration(files, target->GetArchitecture().GetTriple());
521}
522
524 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
525 bool for_completion) {
526 InstallContext(exe_ctx);
527
528 if (!SetupPersistentState(diagnostic_manager, exe_ctx))
529 return false;
530
531 Status err;
532 ScanContext(exe_ctx, err);
533
534 if (!err.Success()) {
535 diagnostic_manager.PutString(eDiagnosticSeverityWarning, err.AsCString());
536 }
537
538 ////////////////////////////////////
539 // Generate the expression
540 //
541
543
544 SetupDeclVendor(exe_ctx, m_target, diagnostic_manager);
545
547
549 SetupCppModuleImports(exe_ctx);
550
551 CreateSourceCode(diagnostic_manager, exe_ctx, m_imported_cpp_modules,
552 for_completion);
553 return true;
554}
555
557 DiagnosticManager &diagnostic_manager, ExecutionContextScope *exe_scope,
558 ExecutionContext &exe_ctx, lldb_private::ExecutionPolicy execution_policy,
559 bool keep_result_in_memory, bool generate_debug_info) {
560 m_materializer_up = std::make_unique<Materializer>();
561
562 ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory);
563
564 auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); });
565
566 if (!DeclMap()->WillParse(exe_ctx, GetMaterializer())) {
567 diagnostic_manager.PutString(
569 "current process state is unsuitable for expression parsing");
570 return false;
571 }
572
574 DeclMap()->SetLookupsEnabled(true);
575 }
576
577 m_parser = std::make_unique<ClangExpressionParser>(
578 exe_scope, *this, generate_debug_info, m_include_directories, m_filename);
579
580 unsigned num_errors = m_parser->Parse(diagnostic_manager);
581
582 // Check here for FixItHints. If there are any try to apply the fixits and
583 // set the fixed text in m_fixed_text before returning an error.
584 if (num_errors) {
585 if (diagnostic_manager.HasFixIts()) {
586 if (m_parser->RewriteExpression(diagnostic_manager)) {
587 size_t fixed_start;
588 size_t fixed_end;
589 m_fixed_text = diagnostic_manager.GetFixedExpression();
590 // Retrieve the original expression in case we don't have a top level
591 // expression (which has no surrounding source code).
592 if (m_source_code && m_source_code->GetOriginalBodyBounds(
593 m_fixed_text, fixed_start, fixed_end))
595 m_fixed_text.substr(fixed_start, fixed_end - fixed_start);
596 }
597 }
598 return false;
599 }
600
601 //////////////////////////////////////////////////////////////////////////////
602 // Prepare the output of the parser for execution, evaluating it statically
603 // if possible
604 //
605
606 {
607 Status jit_error = m_parser->PrepareForExecution(
609 m_can_interpret, execution_policy);
610
611 if (!jit_error.Success()) {
612 const char *error_cstr = jit_error.AsCString();
613 if (error_cstr && error_cstr[0])
614 diagnostic_manager.PutString(eDiagnosticSeverityError, error_cstr);
615 else
616 diagnostic_manager.PutString(eDiagnosticSeverityError,
617 "expression can't be interpreted or run");
618 return false;
619 }
620 }
621 return true;
622}
623
626
627 CppModuleConfiguration module_config = GetModuleConfig(m_language, exe_ctx);
629 m_include_directories = module_config.GetIncludeDirs();
630
631 LLDB_LOG(log, "List of imported modules in expression: {0}",
632 llvm::make_range(m_imported_cpp_modules.begin(),
634 LLDB_LOG(log, "List of include directories gathered for modules: {0}",
635 llvm::make_range(m_include_directories.begin(),
636 m_include_directories.end()));
637}
638
639static bool shouldRetryWithCppModule(Target &target, ExecutionPolicy exe_policy) {
640 // Top-level expression don't yet support importing C++ modules.
642 return false;
644}
645
647 ExecutionContext &exe_ctx,
648 lldb_private::ExecutionPolicy execution_policy,
649 bool keep_result_in_memory,
650 bool generate_debug_info) {
652
653 if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ false))
654 return false;
655
656 LLDB_LOGF(log, "Parsing the following code:\n%s", m_transformed_text.c_str());
657
658 ////////////////////////////////////
659 // Set up the target and compiler
660 //
661
662 Target *target = exe_ctx.GetTargetPtr();
663
664 if (!target) {
665 diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid target");
666 return false;
667 }
668
669 //////////////////////////
670 // Parse the expression
671 //
672
673 Process *process = exe_ctx.GetProcessPtr();
674 ExecutionContextScope *exe_scope = process;
675
676 if (!exe_scope)
677 exe_scope = exe_ctx.GetTargetPtr();
678
679 bool parse_success = TryParse(diagnostic_manager, exe_scope, exe_ctx,
680 execution_policy, keep_result_in_memory,
681 generate_debug_info);
682 // If the expression failed to parse, check if retrying parsing with a loaded
683 // C++ module is possible.
684 if (!parse_success && shouldRetryWithCppModule(*target, execution_policy)) {
685 // Load the loaded C++ modules.
686 SetupCppModuleImports(exe_ctx);
687 // If we did load any modules, then retry parsing.
688 if (!m_imported_cpp_modules.empty()) {
689 // Create a dedicated diagnostic manager for the second parse attempt.
690 // These diagnostics are only returned to the caller if using the fallback
691 // actually succeeded in getting the expression to parse. This prevents
692 // that module-specific issues regress diagnostic quality with the
693 // fallback mode.
694 DiagnosticManager retry_manager;
695 // The module imports are injected into the source code wrapper,
696 // so recreate those.
697 CreateSourceCode(retry_manager, exe_ctx, m_imported_cpp_modules,
698 /*for_completion*/ false);
699 parse_success = TryParse(retry_manager, exe_scope, exe_ctx,
700 execution_policy, keep_result_in_memory,
701 generate_debug_info);
702 // Return the parse diagnostics if we were successful.
703 if (parse_success)
704 diagnostic_manager = std::move(retry_manager);
705 }
706 }
707 if (!parse_success)
708 return false;
709
710 if (exe_ctx.GetProcessPtr() && execution_policy == eExecutionPolicyTopLevel) {
711 Status static_init_error =
712 m_parser->RunStaticInitializers(m_execution_unit_sp, exe_ctx);
713
714 if (!static_init_error.Success()) {
715 const char *error_cstr = static_init_error.AsCString();
716 if (error_cstr && error_cstr[0])
717 diagnostic_manager.Printf(eDiagnosticSeverityError,
718 "%s\n",
719 error_cstr);
720 else
721 diagnostic_manager.PutString(eDiagnosticSeverityError,
722 "couldn't run static initializers\n");
723 return false;
724 }
725 }
726
728 bool register_execution_unit = false;
729
731 register_execution_unit = true;
732 }
733
734 // If there is more than one external function in the execution unit, it
735 // needs to keep living even if it's not top level, because the result
736 // could refer to that function.
737
738 if (m_execution_unit_sp->GetJittedFunctions().size() > 1) {
739 register_execution_unit = true;
740 }
741
742 if (register_execution_unit) {
743 if (auto *persistent_state =
745 m_language))
746 persistent_state->RegisterExecutionUnit(m_execution_unit_sp);
747 }
748 }
749
750 if (generate_debug_info) {
751 lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
752
753 if (jit_module_sp) {
754 ConstString const_func_name(FunctionName());
755 FileSpec jit_file;
756 jit_file.SetFilename(const_func_name);
757 jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
758 m_jit_module_wp = jit_module_sp;
759 target->GetImages().Append(jit_module_sp);
760 }
761 }
762
763 if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS)
764 m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
765 return true;
766}
767
768/// Converts an absolute position inside a given code string into
769/// a column/line pair.
770///
771/// \param[in] abs_pos
772/// A absolute position in the code string that we want to convert
773/// to a column/line pair.
774///
775/// \param[in] code
776/// A multi-line string usually representing source code.
777///
778/// \param[out] line
779/// The line in the code that contains the given absolute position.
780/// The first line in the string is indexed as 1.
781///
782/// \param[out] column
783/// The column in the line that contains the absolute position.
784/// The first character in a line is indexed as 0.
785static void AbsPosToLineColumnPos(size_t abs_pos, llvm::StringRef code,
786 unsigned &line, unsigned &column) {
787 // Reset to code position to beginning of the file.
788 line = 0;
789 column = 0;
790
791 assert(abs_pos <= code.size() && "Absolute position outside code string?");
792
793 // We have to walk up to the position and count lines/columns.
794 for (std::size_t i = 0; i < abs_pos; ++i) {
795 // If we hit a line break, we go back to column 0 and enter a new line.
796 // We only handle \n because that's what we internally use to make new
797 // lines for our temporary code strings.
798 if (code[i] == '\n') {
799 ++line;
800 column = 0;
801 continue;
802 }
803 ++column;
804 }
805}
806
808 CompletionRequest &request,
809 unsigned complete_pos) {
811
812 // We don't want any visible feedback when completing an expression. Mostly
813 // because the results we get from an incomplete invocation are probably not
814 // correct.
815 DiagnosticManager diagnostic_manager;
816
817 if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ true))
818 return false;
819
820 LLDB_LOGF(log, "Parsing the following code:\n%s", m_transformed_text.c_str());
821
822 //////////////////////////
823 // Parse the expression
824 //
825
826 m_materializer_up = std::make_unique<Materializer>();
827
828 ResetDeclMap(exe_ctx, m_result_delegate, /*keep result in memory*/ true);
829
830 auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); });
831
832 if (!DeclMap()->WillParse(exe_ctx, GetMaterializer())) {
833 diagnostic_manager.PutString(
835 "current process state is unsuitable for expression parsing");
836
837 return false;
838 }
839
841 DeclMap()->SetLookupsEnabled(true);
842 }
843
844 Process *process = exe_ctx.GetProcessPtr();
845 ExecutionContextScope *exe_scope = process;
846
847 if (!exe_scope)
848 exe_scope = exe_ctx.GetTargetPtr();
849
850 ClangExpressionParser parser(exe_scope, *this, false);
851
852 // We have to find the source code location where the user text is inside
853 // the transformed expression code. When creating the transformed text, we
854 // already stored the absolute position in the m_transformed_text string. The
855 // only thing left to do is to transform it into the line:column format that
856 // Clang expects.
857
858 // The line and column of the user expression inside the transformed source
859 // code.
860 unsigned user_expr_line, user_expr_column;
863 user_expr_line, user_expr_column);
864 else
865 return false;
866
867 // The actual column where we have to complete is the start column of the
868 // user expression + the offset inside the user code that we were given.
869 const unsigned completion_column = user_expr_column + complete_pos;
870 parser.Complete(request, user_expr_line, completion_column, complete_pos);
871
872 return true;
873}
874
876 lldb::StackFrameSP frame_sp, ConstString &object_name, Status &err) {
877 auto valobj_sp =
878 GetObjectPointerValueObject(std::move(frame_sp), object_name, err);
879
880 // We're inside a C++ class method. This could potentially be an unnamed
881 // lambda structure. If the lambda captured a "this", that should be
882 // the object pointer.
883 if (auto thisChildSP =
884 valobj_sp->GetChildMemberWithName(ConstString("this"), true)) {
885 valobj_sp = thisChildSP;
886 }
887
888 if (!err.Success() || !valobj_sp.get())
890
891 lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
892
893 if (ret == LLDB_INVALID_ADDRESS) {
895 "Couldn't load '%s' because its value couldn't be evaluated",
896 object_name.AsCString());
898 }
899
900 return ret;
901}
902
904 std::vector<lldb::addr_t> &args,
905 lldb::addr_t struct_address,
906 DiagnosticManager &diagnostic_manager) {
909
910 if (m_needs_object_ptr) {
911 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
912 if (!frame_sp)
913 return true;
914
915 ConstString object_name;
916
918 object_name.SetCString("this");
919 } else if (m_in_objectivec_method) {
920 object_name.SetCString("self");
921 } else {
922 diagnostic_manager.PutString(
924 "need object pointer but don't know the language");
925 return false;
926 }
927
928 Status object_ptr_error;
929
930 if (m_ctx_obj) {
931 AddressType address_type;
932 object_ptr = m_ctx_obj->GetAddressOf(false, &address_type);
933 if (object_ptr == LLDB_INVALID_ADDRESS ||
934 address_type != eAddressTypeLoad)
935 object_ptr_error.SetErrorString("Can't get context object's "
936 "debuggee address");
937 } else {
939 object_ptr =
940 GetCppObjectPointer(frame_sp, object_name, object_ptr_error);
941 } else {
942 object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error);
943 }
944 }
945
946 if (!object_ptr_error.Success()) {
947 exe_ctx.GetTargetRef().GetDebugger().GetAsyncOutputStream()->Printf(
948 "warning: `%s' is not accessible (substituting 0). %s\n",
949 object_name.AsCString(), object_ptr_error.AsCString());
950 object_ptr = 0;
951 }
952
954 ConstString cmd_name("_cmd");
955
956 cmd_ptr = GetObjectPointer(frame_sp, cmd_name, object_ptr_error);
957
958 if (!object_ptr_error.Success()) {
959 diagnostic_manager.Printf(
961 "couldn't get cmd pointer (substituting NULL): %s",
962 object_ptr_error.AsCString());
963 cmd_ptr = 0;
964 }
965 }
966
967 args.push_back(object_ptr);
968
970 args.push_back(cmd_ptr);
971
972 args.push_back(struct_address);
973 } else {
974 args.push_back(struct_address);
975 }
976 return true;
977}
978
980 ExecutionContextScope *exe_scope) {
982}
983
985 ExecutionContext &exe_ctx,
987 bool keep_result_in_memory,
988 ValueObject *ctx_obj) {
989 std::shared_ptr<ClangASTImporter> ast_importer;
990 auto *state = exe_ctx.GetTargetSP()->GetPersistentExpressionStateForLanguage(
992 if (state) {
993 auto *persistent_vars = llvm::cast<ClangPersistentVariables>(state);
994 ast_importer = persistent_vars->GetClangASTImporter();
995 }
996 m_expr_decl_map_up = std::make_unique<ClangExpressionDeclMap>(
997 keep_result_in_memory, &delegate, exe_ctx.GetTargetSP(), ast_importer,
998 ctx_obj);
999}
1000
1001clang::ASTConsumer *
1003 clang::ASTConsumer *passthrough) {
1004 m_result_synthesizer_up = std::make_unique<ASTResultSynthesizer>(
1005 passthrough, m_top_level, m_target);
1006
1007 return m_result_synthesizer_up.get();
1008}
1009
1011 if (m_result_synthesizer_up) {
1012 m_result_synthesizer_up->CommitPersistentDecls();
1013 }
1014}
1015
1017 return m_persistent_state->GetNextPersistentVariableName(false);
1018}
1019
1021 lldb::ExpressionVariableSP &variable) {
1022 m_variable = variable;
1023}
1024
1026 PersistentExpressionState *persistent_state) {
1027 m_persistent_state = persistent_state;
1028}
1029
1031 return m_variable;
1032}
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.
Definition: Log.h:337
#define LLDB_LOGF(log,...)
Definition: Log.h:344
#define LLDB_LOGV(log,...)
Definition: Log.h:351
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition: ArchSpec.h:463
A class that describes a single lexical block.
Definition: Block.h:41
lldb::VariableListSP GetBlockVariableList(bool can_create)
Get the variable list for this block only.
Definition: Block.cpp:399
void CalculateSymbolContext(SymbolContext *sc) override
Reconstruct the object's symbol context into sc.
Definition: Block.cpp:136
CompilerDeclContext GetDeclContext()
Definition: Block.cpp:480
lldb::LanguageType GetObjectPtrLanguage() const
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::string GetNextExprFileName()
Returns the next file name that should be used for user expressions.
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)
void DidDematerialize(lldb::ExpressionVariableSP &variable) 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)
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
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.
Definition: CompilerType.h:36
"lldb/Utility/ArgCompletionRequest.h"
A uniqued constant string class.
Definition: ConstString.h:39
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.
Definition: ConstString.h:192
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()
Definition: Debugger.cpp:1193
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
Definition: Target.h:297
"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.
Definition: Expression.h:99
lldb::ProcessWP m_jit_process_wp
Expression's always have to have a target...
Definition: Expression.h:93
lldb::addr_t m_jit_start_addr
An expression might have a process, but it doesn't need to (e.g.
Definition: Expression.h:96
A file utility class.
Definition: FileSpec.h:56
void SetFilename(ConstString filename)
Filename string set accessor.
Definition: FileSpec.cpp:344
"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.
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.
bool GetVerbose() const
Definition: Log.cpp:301
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.
Definition: Module.h:88
lldb::CompUnitSP GetCompileUnitAtIndex(size_t idx)
Definition: Module.cpp:428
size_t GetNumCompileUnits()
Get the number of compile units for this module.
Definition: Module.cpp:421
A plug-in interface definition class for debugging a process.
Definition: Process.h:342
This base class provides an interface to stack frames.
Definition: StackFrame.h:41
const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
Definition: StackFrame.cpp:300
Block * GetFrameBlock()
Get the current lexical scope block for this StackFrame, if possible.
Definition: StackFrame.cpp:275
An error handling class.
Definition: Status.h:44
int SetErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Set the current error string to a formatted error string.
Definition: Status.cpp:255
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:130
void SetErrorString(llvm::StringRef err_str)
Set the current error string to err_str.
Definition: Status.cpp:241
bool Success() const
Test for success condition.
Definition: Status.cpp:287
llvm::StringRef GetString() const
Defines a symbol context baton that can be handed other debug core functions.
Definition: SymbolContext.h:33
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
Definition: Target.cpp:4413
bool GetEnableAutoImportClangModules() const
Definition: Target.cpp:4407
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition: Target.cpp:2397
Debugger & GetDebugger()
Definition: Target.h:1029
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition: Target.h:946
const ArchSpec & GetArchitecture() const
Definition: Target.h:988
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()
Definition: Type.cpp:667
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()
Definition: ValueObject.h:373
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:74
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.
Definition: Log.h:309
ExecutionPolicy
Expression execution policies.
@ eImportStdModuleFallback
Definition: Target.h:64
@ eImportStdModuleTrue
Definition: Target.h:65
@ 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.
uint64_t addr_t
Definition: lldb-types.h:83