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"
35#include "lldb/Host/HostInfo.h"
36#include "lldb/Symbol/Block.h"
42#include "lldb/Symbol/Type.h"
45#include "lldb/Target/Process.h"
47#include "lldb/Target/Target.h"
52#include "lldb/Utility/Log.h"
55
56#include "clang/AST/DeclCXX.h"
57#include "clang/AST/DeclObjC.h"
58
59#include "clang/Basic/DiagnosticSema.h"
60#include "llvm/ADT/STLExtras.h"
61#include "llvm/ADT/ScopeExit.h"
62#include "llvm/BinaryFormat/Dwarf.h"
63
64using namespace lldb_private;
65
67
69 ExecutionContextScope &exe_scope, llvm::StringRef expr,
70 llvm::StringRef prefix, SourceLanguage language, ResultType desired_type,
71 const EvaluateExpressionOptions &options, ValueObject *ctx_obj)
72 : LLVMUserExpression(exe_scope, expr, prefix, language, desired_type,
73 options),
74 m_type_system_helper(*m_target_wp.lock(), options.GetExecutionPolicy() ==
76 m_result_delegate(exe_scope.CalculateTarget()), m_ctx_obj(ctx_obj) {
77 switch (m_language.name) {
78 case llvm::dwarf::DW_LNAME_C_plus_plus:
79 m_allow_cxx = true;
80 break;
81 case llvm::dwarf::DW_LNAME_ObjC:
82 m_allow_objc = true;
83 break;
84 case llvm::dwarf::DW_LNAME_ObjC_plus_plus:
85 default:
86 m_allow_cxx = true;
87 m_allow_objc = true;
88 break;
89 }
90}
91
93
95 ExecutionContext &exe_ctx) {
97
98 LLDB_LOGF(log, "ClangUserExpression::ScanContext()");
99
100 m_target = exe_ctx.GetTargetPtr();
101
102 if (!(m_allow_cxx || m_allow_objc)) {
103 LLDB_LOGF(log, " [CUE::SC] Settings inhibit C++ and Objective-C");
104 return;
105 }
106
107 StackFrame *frame = exe_ctx.GetFramePtr();
108 if (frame == nullptr) {
109 LLDB_LOGF(log, " [CUE::SC] Null stack frame");
110 return;
111 }
112
113 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
114 lldb::eSymbolContextBlock);
115
116 if (!sym_ctx.function) {
117 LLDB_LOGF(log, " [CUE::SC] Null function");
118 return;
119 }
120
121 // Find the block that defines the function represented by "sym_ctx"
122 Block *function_block = sym_ctx.GetFunctionBlock();
123
124 if (!function_block) {
125 LLDB_LOGF(log, " [CUE::SC] Null function block");
126 return;
127 }
128
129 CompilerDeclContext decl_context = function_block->GetDeclContext();
130
131 if (!decl_context) {
132 LLDB_LOGF(log, " [CUE::SC] Null decl context");
133 return;
134 }
135
136 if (m_ctx_obj) {
137 switch (m_ctx_obj->GetObjectRuntimeLanguage()) {
148 break;
152 break;
153 default:
154 break;
155 }
156 m_needs_object_ptr = true;
157 } else if (clang::CXXMethodDecl *method_decl =
159 if (m_allow_cxx && method_decl->isInstance()) {
161 lldb::VariableListSP variable_list_sp(
162 function_block->GetBlockVariableList(true));
163
164 const char *msg = "Stopped in a C++ method, but 'this' isn't "
165 "available; pretending we are in a generic context";
166
167 if (!variable_list_sp) {
168 diagnostic_manager.AddDiagnostic(msg, lldb::eSeverityWarning,
170 return;
171 }
172
173 lldb::VariableSP this_var_sp(
174 variable_list_sp->FindVariable(ConstString("this")));
175
176 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
177 !this_var_sp->LocationIsValidForFrame(frame)) {
178 diagnostic_manager.AddDiagnostic(msg, lldb::eSeverityWarning,
180 return;
181 }
182 }
183
185 m_needs_object_ptr = true;
186 }
187 } else if (clang::ObjCMethodDecl *method_decl =
189 decl_context)) {
190 if (m_allow_objc) {
192 lldb::VariableListSP variable_list_sp(
193 function_block->GetBlockVariableList(true));
194
195 const char *msg = "Stopped in an Objective-C method, but 'self' isn't "
196 "available; pretending we are in a generic context";
197
198 if (!variable_list_sp) {
199 diagnostic_manager.AddDiagnostic(msg, lldb::eSeverityWarning,
201 return;
202 }
203
204 lldb::VariableSP self_variable_sp =
205 variable_list_sp->FindVariable(ConstString("self"));
206
207 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
208 !self_variable_sp->LocationIsValidForFrame(frame)) {
209 diagnostic_manager.AddDiagnostic(msg, lldb::eSeverityWarning,
211 return;
212 }
213 }
214
216 m_needs_object_ptr = true;
217
218 if (!method_decl->isInstanceMethod())
219 m_in_static_method = true;
220 }
221 } else if (clang::FunctionDecl *function_decl =
223 // We might also have a function that said in the debug information that it
224 // captured an object pointer. The best way to deal with getting to the
225 // ivars at present is by pretending that this is a method of a class in
226 // whatever runtime the debug info says the object pointer belongs to. Do
227 // that here.
228
229 if (std::optional<ClangASTMetadata> metadata =
231 function_decl);
232 metadata && metadata->HasObjectPtr()) {
233 lldb::LanguageType language = metadata->GetObjectPtrLanguage();
234 if (language == lldb::eLanguageTypeC_plus_plus) {
236 lldb::VariableListSP variable_list_sp(
237 function_block->GetBlockVariableList(true));
238
239 const char *msg = "Stopped in a context claiming to capture a C++ "
240 "object pointer, but 'this' isn't available; "
241 "pretending we are in a generic context";
242
243 if (!variable_list_sp) {
244 diagnostic_manager.AddDiagnostic(msg, lldb::eSeverityWarning,
246 return;
247 }
248
249 lldb::VariableSP this_var_sp(
250 variable_list_sp->FindVariable(ConstString("this")));
251
252 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
253 !this_var_sp->LocationIsValidForFrame(frame)) {
254 diagnostic_manager.AddDiagnostic(msg, lldb::eSeverityWarning,
256 return;
257 }
258 }
259
261 m_needs_object_ptr = true;
262 } else if (language == lldb::eLanguageTypeObjC) {
264 lldb::VariableListSP variable_list_sp(
265 function_block->GetBlockVariableList(true));
266
267 const char *msg = "Stopped in a context claiming to capture an "
268 "Objective-C object pointer, but 'self' isn't "
269 "available; pretending we are in a generic context";
270
271 if (!variable_list_sp) {
272 diagnostic_manager.AddDiagnostic(msg, lldb::eSeverityWarning,
274 return;
275 }
276
277 lldb::VariableSP self_variable_sp =
278 variable_list_sp->FindVariable(ConstString("self"));
279
280 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
281 !self_variable_sp->LocationIsValidForFrame(frame)) {
282 diagnostic_manager.AddDiagnostic(msg, lldb::eSeverityWarning,
284 return;
285 }
286
287 Type *self_type = self_variable_sp->GetType();
288
289 if (!self_type) {
290 diagnostic_manager.AddDiagnostic(msg, lldb::eSeverityWarning,
292 return;
293 }
294
295 CompilerType self_clang_type = self_type->GetForwardCompilerType();
296
297 if (!self_clang_type) {
298 diagnostic_manager.AddDiagnostic(msg, lldb::eSeverityWarning,
300 return;
301 }
302
303 if (TypeSystemClang::IsObjCClassType(self_clang_type)) {
304 return;
306 self_clang_type)) {
308 m_needs_object_ptr = true;
309 } else {
310 diagnostic_manager.AddDiagnostic(msg, lldb::eSeverityWarning,
312 return;
313 }
314 } else {
316 m_needs_object_ptr = true;
317 }
318 }
319 }
320 }
321}
322
323// This is a really nasty hack, meant to fix Objective-C expressions of the
324// form (int)[myArray count]. Right now, because the type information for
325// count is not available, [myArray count] returns id, which can't be directly
326// cast to int without causing a clang error.
327static void ApplyObjcCastHack(std::string &expr) {
328 const std::string from = "(int)[";
329 const std::string to = "(int)(long long)[";
330
331 size_t offset;
332
333 while ((offset = expr.find(from)) != expr.npos)
334 expr.replace(offset, from.size(), to);
335}
336
338 ExecutionContext &exe_ctx) {
339 if (Target *target = exe_ctx.GetTargetPtr()) {
340 if (PersistentExpressionState *persistent_state =
341 target->GetPersistentExpressionStateForLanguage(
343 m_clang_state = llvm::cast<ClangPersistentVariables>(persistent_state);
344 m_result_delegate.RegisterPersistentState(persistent_state);
345 } else {
346 diagnostic_manager.PutString(
347 lldb::eSeverityError, "couldn't start parsing (no persistent data)");
348 return false;
349 }
350 } else {
351 diagnostic_manager.PutString(lldb::eSeverityError,
352 "error: couldn't start parsing (no target)");
353 return false;
354 }
355 return true;
356}
357
358static void SetupDeclVendor(ExecutionContext &exe_ctx, Target *target,
359 DiagnosticManager &diagnostic_manager) {
360 if (!target->GetEnableAutoImportClangModules())
361 return;
362
363 auto *persistent_state = llvm::cast<ClangPersistentVariables>(
365 if (!persistent_state)
366 return;
367
368 std::shared_ptr<ClangModulesDeclVendor> decl_vendor =
369 persistent_state->GetClangModulesDeclVendor();
370 if (!decl_vendor)
371 return;
372
373 StackFrame *frame = exe_ctx.GetFramePtr();
374 if (!frame)
375 return;
376
377 Block *block = frame->GetFrameBlock();
378 if (!block)
379 return;
380 SymbolContext sc;
381
382 block->CalculateSymbolContext(&sc);
383
384 if (!sc.comp_unit)
385 return;
386 ClangModulesDeclVendor::ModuleVector modules_for_macros =
387 persistent_state->GetHandLoadedClangModules();
388
389 auto err =
390 decl_vendor->AddModulesForCompileUnit(*sc.comp_unit, modules_for_macros);
391 if (!err)
392 return;
393
394 // Module load errors aren't fatal to the expression evaluator. Printing
395 // them as diagnostics to the console would be too noisy and misleading
396 // Hence just print them to the expression log.
397 llvm::handleAllErrors(std::move(err), [](const llvm::StringError &e) {
398 LLDB_LOG(GetLog(LLDBLog::Expressions), "{0}", e.getMessage());
399 });
400}
401
403 assert(m_options.GetExecutionPolicy() != eExecutionPolicyTopLevel &&
404 "Top level expressions aren't wrapped.");
407 return Kind::CppMemberFunction;
408 else if (m_in_objectivec_method) {
410 return Kind::ObjCStaticMethod;
411 return Kind::ObjCInstanceMethod;
412 }
413 // Not in any kind of 'special' function, so just wrap it in a normal C
414 // function.
415 return Kind::Function;
416}
417
419 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
420 std::vector<std::string> modules_to_import, bool for_completion) {
421
422 std::string prefix = m_expr_prefix;
423
424 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
426 } else {
428 m_filename, prefix, m_expr_text, GetWrapKind()));
429
430 if (!m_source_code->GetText(m_transformed_text, exe_ctx, !m_ctx_obj,
431 for_completion, modules_to_import,
432 m_options.GetCppIgnoreContextQualifiers())) {
433 diagnostic_manager.PutString(lldb::eSeverityError,
434 "couldn't construct expression body");
435 return;
436 }
437
438 // Find and store the start position of the original code inside the
439 // transformed code. We need this later for the code completion.
440 std::size_t original_start;
441 std::size_t original_end;
442 bool found_bounds = m_source_code->GetOriginalBodyBounds(
443 m_transformed_text, original_start, original_end);
444 if (found_bounds)
445 m_user_expression_start_pos = original_start;
446 }
447}
448
450 switch (language) {
456 return true;
457 default:
458 return false;
459 }
460}
461
462/// Utility method that puts a message into the expression log and
463/// returns an invalid module configuration.
464static CppModuleConfiguration LogConfigError(const std::string &msg) {
466 LLDB_LOG(log, "[C++ module config] {0}", msg);
467 return CppModuleConfiguration();
468}
469
471 ExecutionContext &exe_ctx) {
473
474 // Don't do anything if this is not a C++ module configuration.
475 if (!SupportsCxxModuleImport(language))
476 return LogConfigError("Language doesn't support C++ modules");
477
478 Target *target = exe_ctx.GetTargetPtr();
479 if (!target)
480 return LogConfigError("No target");
481
482 StackFrame *frame = exe_ctx.GetFramePtr();
483 if (!frame)
484 return LogConfigError("No frame");
485
486 Block *block = frame->GetFrameBlock();
487 if (!block)
488 return LogConfigError("No block");
489
490 SymbolContext sc;
491 block->CalculateSymbolContext(&sc);
492 if (!sc.comp_unit)
493 return LogConfigError("Couldn't calculate symbol context");
494
495 // Build a list of files we need to analyze to build the configuration.
496 FileSpecList files;
497 for (auto &f : sc.comp_unit->GetSupportFiles())
498 files.AppendIfUnique(f->Materialize());
499 // We also need to look at external modules in the case of -gmodules as they
500 // contain the support files for libc++ and the C library.
501 llvm::DenseSet<SymbolFile *> visited_symbol_files;
503 visited_symbol_files, [&files](Module &module) {
504 for (std::size_t i = 0; i < module.GetNumCompileUnits(); ++i) {
505 const SupportFileList &support_files =
506 module.GetCompileUnitAtIndex(i)->GetSupportFiles();
507 for (auto &f : support_files) {
508 files.AppendIfUnique(f->Materialize());
509 }
510 }
511 return false;
512 });
513
514 LLDB_LOG(log, "[C++ module config] Found {0} support files to analyze",
515 files.GetSize());
516 if (log && log->GetVerbose()) {
517 for (auto &f : files)
518 LLDB_LOG_VERBOSE(log, "[C++ module config] Analyzing support file: {0}",
519 f.GetPath());
520 }
521
522 // Try to create a configuration from the files. If there is no valid
523 // configuration possible with the files, this just returns an invalid
524 // configuration.
525 return CppModuleConfiguration(files, target->GetArchitecture().GetTriple());
526}
527
529 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
530 bool for_completion) {
531 InstallContext(exe_ctx);
532
533 if (!SetupPersistentState(diagnostic_manager, exe_ctx))
534 return false;
535
536 Status err;
537 ScanContext(diagnostic_manager, exe_ctx);
538
539 if (!err.Success()) {
540 diagnostic_manager.PutString(lldb::eSeverityWarning, err.AsCString());
541 }
542
543 ////////////////////////////////////
544 // Generate the expression
545 //
546
548
549 SetupDeclVendor(exe_ctx, m_target, diagnostic_manager);
550
551 m_filename = m_clang_state->GetNextExprFileName();
552
553 if (m_target->GetImportStdModule() == eImportStdModuleTrue)
554 SetupCppModuleImports(exe_ctx);
555
556 CreateSourceCode(diagnostic_manager, exe_ctx, m_imported_cpp_modules,
557 for_completion);
558 return true;
559}
560
562 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
563 lldb_private::ExecutionPolicy execution_policy, bool keep_result_in_memory,
564 bool generate_debug_info) {
565 m_materializer_up = std::make_unique<Materializer>();
566
567 ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory);
568
569 llvm::scope_exit on_exit([this]() { ResetDeclMap(); });
570
571 if (!DeclMap()->WillParse(exe_ctx, GetMaterializer())) {
572 diagnostic_manager.PutString(
574 "current process state is unsuitable for expression parsing");
575 return false;
576 }
577
578 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
579 DeclMap()->SetLookupsEnabled(true);
580 }
581
582 m_parser = std::make_unique<ClangExpressionParser>(
583 exe_ctx.GetBestExecutionContextScope(), *this, generate_debug_info,
584 diagnostic_manager, m_include_directories, m_filename);
585
586 unsigned num_errors = m_parser->Parse(diagnostic_manager);
587
588 // Check here for FixItHints. If there are any try to apply the fixits and
589 // set the fixed text in m_fixed_text before returning an error.
590 if (num_errors) {
591 if (diagnostic_manager.HasFixIts()) {
592 if (m_parser->RewriteExpression(diagnostic_manager)) {
593 size_t fixed_start;
594 size_t fixed_end;
595 m_fixed_text = diagnostic_manager.GetFixedExpression();
596 // Retrieve the original expression in case we don't have a top level
597 // expression (which has no surrounding source code).
598 if (m_source_code && m_source_code->GetOriginalBodyBounds(
599 m_fixed_text, fixed_start, fixed_end))
601 m_fixed_text.substr(fixed_start, fixed_end - fixed_start);
602 }
603 }
604 return false;
605 }
606
607 //////////////////////////////////////////////////////////////////////////////
608 // Prepare the output of the parser for execution, evaluating it statically
609 // if possible
610 //
611
612 {
613 Status jit_error = m_parser->PrepareForExecution(
615 m_can_interpret, execution_policy);
616
617 if (!jit_error.Success()) {
618 const char *error_cstr = jit_error.AsCString();
619 if (error_cstr && error_cstr[0])
620 diagnostic_manager.PutString(lldb::eSeverityError, error_cstr);
621 else
622 diagnostic_manager.PutString(lldb::eSeverityError,
623 "expression can't be interpreted or run");
624 return false;
625 }
626 }
627 return true;
628}
629
632
633 CppModuleConfiguration module_config =
634 GetModuleConfig(m_language.AsLanguageType(), exe_ctx);
636 m_include_directories = module_config.GetIncludeDirs();
637
638 LLDB_LOG(log, "List of imported modules in expression: {0}",
639 llvm::make_range(m_imported_cpp_modules.begin(),
641 LLDB_LOG(log, "List of include directories gathered for modules: {0}",
642 llvm::make_range(m_include_directories.begin(),
643 m_include_directories.end()));
644}
645
646static bool shouldRetryWithCppModule(Target &target, ExecutionPolicy exe_policy) {
647 // Top-level expression don't yet support importing C++ modules.
649 return false;
651}
652
654 ExecutionContext &exe_ctx,
655 lldb_private::ExecutionPolicy execution_policy,
656 bool keep_result_in_memory,
657 bool generate_debug_info) {
659
660 if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ false))
661 return false;
662
663 LLDB_LOGF(log, "Parsing the following code:\n%s", m_transformed_text.c_str());
664
665 ////////////////////////////////////
666 // Set up the target and compiler
667 //
668
669 Target *target = exe_ctx.GetTargetPtr();
670
671 if (!target) {
672 diagnostic_manager.PutString(lldb::eSeverityError, "invalid target");
673 return false;
674 }
675
676 //////////////////////////
677 // Parse the expression
678 //
679
680 bool parse_success = TryParse(diagnostic_manager, exe_ctx, execution_policy,
681 keep_result_in_memory, 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_ctx, execution_policy,
700 keep_result_in_memory, generate_debug_info);
701 // Return the parse diagnostics if we were successful.
702 if (parse_success)
703 diagnostic_manager = std::move(retry_manager);
704 }
705 }
706 if (!parse_success)
707 return false;
708
710 bool register_execution_unit = false;
711
712 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
713 register_execution_unit = true;
714 }
715
716 // If there is more than one external function in the execution unit, it
717 // needs to keep living even if it's not top level, because the result
718 // could refer to that function.
719
720 if (m_execution_unit_sp->GetJittedFunctions().size() > 1) {
721 register_execution_unit = true;
722 }
723
724 if (register_execution_unit) {
725 if (auto *persistent_state =
727 m_language.AsLanguageType()))
728 persistent_state->RegisterExecutionUnit(m_execution_unit_sp);
729 }
730 }
731
732 if (generate_debug_info) {
733 lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
734
735 if (jit_module_sp) {
736 ConstString const_func_name(FunctionName());
737 FileSpec jit_file;
738 jit_file.SetFilename(const_func_name);
739 jit_module_sp->SetFileSpecAndObjectName(jit_file, std::string());
740 m_jit_module_wp = jit_module_sp;
741 target->GetImages().Append(jit_module_sp);
742 }
743 }
744
745 Process *process = exe_ctx.GetProcessPtr();
746 if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS)
747 m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
748 return true;
749}
750
751/// Converts an absolute position inside a given code string into
752/// a column/line pair.
753///
754/// \param[in] abs_pos
755/// A absolute position in the code string that we want to convert
756/// to a column/line pair.
757///
758/// \param[in] code
759/// A multi-line string usually representing source code.
760///
761/// \param[out] line
762/// The line in the code that contains the given absolute position.
763/// The first line in the string is indexed as 1.
764///
765/// \param[out] column
766/// The column in the line that contains the absolute position.
767/// The first character in a line is indexed as 0.
768static void AbsPosToLineColumnPos(size_t abs_pos, llvm::StringRef code,
769 unsigned &line, unsigned &column) {
770 // Reset to code position to beginning of the file.
771 line = 0;
772 column = 0;
773
774 assert(abs_pos <= code.size() && "Absolute position outside code string?");
775
776 // We have to walk up to the position and count lines/columns.
777 for (std::size_t i = 0; i < abs_pos; ++i) {
778 // If we hit a line break, we go back to column 0 and enter a new line.
779 // We only handle \n because that's what we internally use to make new
780 // lines for our temporary code strings.
781 if (code[i] == '\n') {
782 ++line;
783 column = 0;
784 continue;
785 }
786 ++column;
787 }
788}
789
791 CompletionRequest &request,
792 unsigned complete_pos) {
794
795 // We don't want any visible feedback when completing an expression. Mostly
796 // because the results we get from an incomplete invocation are probably not
797 // correct.
798 DiagnosticManager diagnostic_manager;
799
800 if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ true))
801 return false;
802
803 LLDB_LOGF(log, "Parsing the following code:\n%s", m_transformed_text.c_str());
804
805 //////////////////////////
806 // Parse the expression
807 //
808
809 m_materializer_up = std::make_unique<Materializer>();
810
811 ResetDeclMap(exe_ctx, m_result_delegate, /*keep result in memory*/ true);
812
813 llvm::scope_exit on_exit([this]() { ResetDeclMap(); });
814
815 if (!DeclMap()->WillParse(exe_ctx, GetMaterializer())) {
816 diagnostic_manager.PutString(
818 "current process state is unsuitable for expression parsing");
819
820 return false;
821 }
822
823 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
824 DeclMap()->SetLookupsEnabled(true);
825 }
826
828 false, diagnostic_manager);
829
830 // We have to find the source code location where the user text is inside
831 // the transformed expression code. When creating the transformed text, we
832 // already stored the absolute position in the m_transformed_text string. The
833 // only thing left to do is to transform it into the line:column format that
834 // Clang expects.
835
836 // The line and column of the user expression inside the transformed source
837 // code.
838 unsigned user_expr_line, user_expr_column;
841 user_expr_line, user_expr_column);
842 else
843 return false;
844
845 // The actual column where we have to complete is the start column of the
846 // user expression + the offset inside the user code that we were given.
847 const unsigned completion_column = user_expr_column + complete_pos;
848 parser.Complete(request, user_expr_line, completion_column, complete_pos);
849
850 return true;
851}
852
854 lldb::StackFrameSP frame_sp, llvm::StringRef object_name, Status &err) {
855 auto valobj_sp =
856 GetObjectPointerValueObject(std::move(frame_sp), object_name, err);
857
858 if (!err.Success() || !valobj_sp)
860
861 // We're inside a C++ class method. This could potentially be an unnamed
862 // lambda structure. If the lambda captured a "this", that should be
863 // the object pointer.
864 if (auto thisChildSP = valobj_sp->GetChildMemberWithName("this"))
865 valobj_sp = thisChildSP;
866 else if (auto cv_this_child_sp = valobj_sp->GetChildMemberWithName("__this"))
867 valobj_sp = cv_this_child_sp;
868
869 lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
870
871 if (ret == LLDB_INVALID_ADDRESS) {
873 "Couldn't load '{0}' because its value couldn't be evaluated",
874 object_name);
876 }
877
878 return ret;
879}
880
882 std::vector<lldb::addr_t> &args,
883 lldb::addr_t struct_address,
884 DiagnosticManager &diagnostic_manager) {
887
888 if (m_needs_object_ptr) {
889 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
890 if (!frame_sp)
891 return true;
892
894 diagnostic_manager.PutString(
896 "need object pointer but don't know the language");
897 return false;
898 }
899
900 static constexpr llvm::StringLiteral g_cplusplus_object_name("this");
901 static constexpr llvm::StringLiteral g_objc_object_name("self");
902 llvm::StringRef object_name =
903 m_in_cplusplus_method ? g_cplusplus_object_name : g_objc_object_name;
904
905 Status object_ptr_error;
906
907 if (m_ctx_obj) {
908 ValueObject::AddrAndType address = m_ctx_obj->GetAddressOf(false);
909 if (address.address == LLDB_INVALID_ADDRESS ||
910 address.type != eAddressTypeLoad)
911 object_ptr_error = Status::FromErrorString("Can't get context object's "
912 "debuggee address");
913 else
914 object_ptr = address.address;
915 } else {
917 object_ptr =
918 GetCppObjectPointer(frame_sp, object_name, object_ptr_error);
919 } else {
920 object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error);
921 }
922 }
923
924 if (!object_ptr_error.Success()) {
925 exe_ctx.GetTargetRef().GetDebugger().GetAsyncOutputStream()->Format(
926 "warning: `{0}' is not accessible (substituting 0). {1}\n",
927 object_name, object_ptr_error.AsCString());
928 object_ptr = 0;
929 }
930
932 static constexpr llvm::StringLiteral cmd_name("_cmd");
933
934 cmd_ptr = GetObjectPointer(frame_sp, cmd_name, object_ptr_error);
935
936 if (!object_ptr_error.Success()) {
937 diagnostic_manager.Printf(
939 "couldn't get cmd pointer (substituting NULL): %s",
940 object_ptr_error.AsCString());
941 cmd_ptr = 0;
942 }
943 }
944
945 args.push_back(object_ptr);
946
948 args.push_back(cmd_ptr);
949
950 args.push_back(struct_address);
951 } else {
952 args.push_back(struct_address);
953 }
954 return true;
955}
956
961
963 DiagnosticManager &diagnostic_manager) const {
964 const bool is_fixable_cvr_error = llvm::any_of(
965 diagnostic_manager.Diagnostics(),
966 [](std::unique_ptr<Diagnostic> const &diag) {
967 switch (diag->GetCompilerID()) {
968 case clang::diag::err_member_function_call_bad_cvr:
969 case clang::diag::err_typecheck_assign_const_method:
970 return true;
971 default:
972 return false;
973 }
974 });
975
976 // Nothing to report.
977 if (!is_fixable_cvr_error)
978 return;
979
980 // If the user already tried ignoring function qualifiers but
981 // the expression still failed, we don't want to suggest the hint again.
982 if (m_options.GetCppIgnoreContextQualifiers()) {
983 // Hard to prove that we don't get here so don't emit a diagnostic n
984 // non-asserts builds. But we do want a signal in asserts builds.
985 assert(false &&
986 "CppIgnoreContextQualifiers didn't resolve compiler diagnostic.");
987 return;
988 }
989
990 diagnostic_manager.Printf(
992 "Possibly trying to mutate object in a const context. Try "
993 "running the expression with: expression --c++-ignore-context-qualifiers "
994 "-- %s",
995 !m_fixed_text.empty() ? m_fixed_text.c_str() : m_expr_text.c_str());
996}
997
999 DiagnosticManager &diagnostic_manager) const {
1000 if (llvm::none_of(diagnostic_manager.Diagnostics(),
1001 [](std::unique_ptr<Diagnostic> const &diag) {
1002 switch (diag->GetCompilerID()) {
1003 // FIXME: should we also be checking
1004 // clang::diag::err_no_member_template?
1005 case clang::diag::err_no_template:
1006 case clang::diag::err_non_template_in_template_id:
1007 return true;
1008 default:
1009 return false;
1010 }
1011 }))
1012 return;
1013
1014 diagnostic_manager.AddDiagnostic(
1015 "Naming template instantiation not yet supported. Template functions "
1016 "can be invoked via their mangled name. For example, using "
1017 "`_Z3fooIiEvi(123)` for `foo<int>(123)`",
1019}
1020
1022 DiagnosticManager &diagnostic_manager) const {
1023 FixupCVRParseErrorDiagnostics(diagnostic_manager);
1024 FixupTemplateLookupDiagnostics(diagnostic_manager);
1025}
1026
1028
1030 ExecutionContext &exe_ctx,
1032 bool keep_result_in_memory, ValueObject *ctx_obj,
1033 bool ignore_context_qualifiers) {
1034 std::shared_ptr<ClangASTImporter> ast_importer;
1035 auto *state = exe_ctx.GetTargetSP()->GetPersistentExpressionStateForLanguage(
1037 if (state) {
1038 auto *persistent_vars = llvm::cast<ClangPersistentVariables>(state);
1039 ast_importer = persistent_vars->GetClangASTImporter();
1040 }
1041 m_expr_decl_map_up = std::make_unique<ClangExpressionDeclMap>(
1042 keep_result_in_memory, &delegate, exe_ctx.GetTargetSP(), ast_importer,
1043 ctx_obj, ignore_context_qualifiers);
1044}
1045
1046clang::ASTConsumer *
1048 clang::ASTConsumer *passthrough) {
1049 m_result_synthesizer_up = std::make_unique<ASTResultSynthesizer>(
1050 passthrough, m_top_level, m_target);
1051
1052 return m_result_synthesizer_up.get();
1053}
1054
1060
1062 return m_persistent_state->GetNextPersistentVariableName(false);
1063}
1064
1069
1074
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:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:382
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:465
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:382
void CalculateSymbolContext(SymbolContext *sc) override
Reconstruct the object's symbol context into sc.
Definition Block.cpp:137
CompilerDeclContext GetDeclContext()
Definition Block.cpp:463
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)
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
void RegisterPersistentState(PersistentExpressionState *persistent_state)
void DidDematerialize(lldb::ExpressionVariableSP &variable) override
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)
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
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.
Definition ConstString.h:40
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.
Definition Expression.h:95
lldb::ProcessWP m_jit_process_wp
Expression's always have to have a target...
Definition Expression.h:89
lldb::addr_t m_jit_start_addr
An expression might have a process, but it doesn't need to (e.g.
Definition Expression.h:92
lldb::TargetWP m_target_wp
Definition Expression.h:88
A file collection class.
size_t GetSize() const
Get the number of files in the file list.
bool AppendIfUnique(const FileSpec &file)
Append a FileSpec object if unique.
A file utility class.
Definition FileSpec.h:56
void SetFilename(llvm::StringRef filename)
Filename string set accessor.
Definition FileSpec.cpp:363
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.
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.
bool GetVerbose() const
Definition Log.cpp:329
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:92
size_t GetNumCompileUnits()
Get the number of compile units for this module.
Definition Module.cpp:430
A plug-in interface definition class for debugging a process.
Definition Process.h:370
This base class provides an interface to stack frames.
Definition StackFrame.h:44
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.
An error handling class.
Definition Status.h:118
static Status FromErrorString(const char *str)
Definition Status.h:141
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
bool Success() const
Test for success condition.
Definition Status.cpp:303
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
Definition Target.cpp:5712
bool GetEnableAutoImportClangModules() const
Definition Target.cpp:5706
Debugger & GetDebugger() const
Definition Target.h:1378
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition Target.cpp:2865
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1295
const ArchSpec & GetArchitecture() const
Definition Target.h:1337
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.
Definition Log.h:338
ExecutionPolicy
Expression execution policies.
@ eImportStdModuleFallback
Definition Target.h:83
@ eImportStdModuleTrue
Definition Target.h:84
@ 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.
@ eLanguageTypeRust
Rust.
@ 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
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Module > ModuleSP
A type-erased pair of llvm::dwarf::SourceLanguageName and version.