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
18#include "ASTResultSynthesizer.h"
19#include "ClangASTMetadata.h"
20#include "ClangDiagnostic.h"
21#include "ClangExpressionDeclMap.h"
22#include "ClangExpressionParser.h"
23#include "ClangModulesDeclVendor.h"
24#include "ClangPersistentVariables.h"
25#include "CppModuleConfiguration.h"
26
27#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
28#include "lldb/Core/Debugger.h"
29#include "lldb/Core/Module.h"
30#include "lldb/Core/ValueObjectConstResult.h"
31#include "lldb/Expression/ExpressionSourceCode.h"
32#include "lldb/Expression/IRExecutionUnit.h"
33#include "lldb/Expression/IRInterpreter.h"
34#include "lldb/Expression/Materializer.h"
35#include "lldb/Host/HostInfo.h"
36#include "lldb/Symbol/Block.h"
37#include "lldb/Symbol/CompileUnit.h"
38#include "lldb/Symbol/Function.h"
39#include "lldb/Symbol/ObjectFile.h"
40#include "lldb/Symbol/SymbolFile.h"
41#include "lldb/Symbol/SymbolVendor.h"
42#include "lldb/Symbol/Type.h"
43#include "lldb/Symbol/VariableList.h"
44#include "lldb/Target/ExecutionContext.h"
45#include "lldb/Target/Process.h"
46#include "lldb/Target/StackFrame.h"
47#include "lldb/Target/Target.h"
48#include "lldb/Target/ThreadPlan.h"
49#include "lldb/Target/ThreadPlanCallUserExpression.h"
50#include "lldb/Utility/ConstString.h"
51#include "lldb/Utility/LLDBLog.h"
52#include "lldb/Utility/Log.h"
53#include "lldb/Utility/StreamString.h"
54
55#include "clang/AST/DeclCXX.h"
56#include "clang/AST/DeclObjC.h"
57
58#include "llvm/ADT/ScopeExit.h"
59
60using namespace lldb_private;
61
62char ClangUserExpression::ID;
63
64ClangUserExpression::ClangUserExpression(
65 ExecutionContextScope &exe_scope, llvm::StringRef expr,
66 llvm::StringRef prefix, lldb::LanguageType language,
67 ResultType desired_type, const EvaluateExpressionOptions &options,
68 ValueObject *ctx_obj)
69 : LLVMUserExpression(exe_scope, expr, prefix, language, desired_type,
70 options),
71 m_type_system_helper(*m_target_wp.lock(), options.GetExecutionPolicy() ==
72 eExecutionPolicyTopLevel),
73 m_result_delegate(exe_scope.CalculateTarget()), m_ctx_obj(ctx_obj) {
74 switch (m_language) {
75 case lldb::eLanguageTypeC_plus_plus:
76 m_allow_cxx = true;
77 break;
78 case lldb::eLanguageTypeObjC:
79 m_allow_objc = true;
80 break;
81 case lldb::eLanguageTypeObjC_plus_plus:
82 default:
83 m_allow_cxx = true;
84 m_allow_objc = true;
85 break;
86 }
87}
88
89ClangUserExpression::~ClangUserExpression() = default;
90
91void ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Status &err) {
92 Log *log = GetLog(mask: LLDBLog::Expressions);
93
94 LLDB_LOGF(log, "ClangUserExpression::ScanContext()");
95
96 m_target = exe_ctx.GetTargetPtr();
97
98 if (!(m_allow_cxx || m_allow_objc)) {
99 LLDB_LOGF(log, " [CUE::SC] Settings inhibit C++ and Objective-C");
100 return;
101 }
102
103 StackFrame *frame = exe_ctx.GetFramePtr();
104 if (frame == nullptr) {
105 LLDB_LOGF(log, " [CUE::SC] Null stack frame");
106 return;
107 }
108
109 SymbolContext sym_ctx = frame->GetSymbolContext(resolve_scope: lldb::eSymbolContextFunction |
110 lldb::eSymbolContextBlock);
111
112 if (!sym_ctx.function) {
113 LLDB_LOGF(log, " [CUE::SC] Null function");
114 return;
115 }
116
117 // Find the block that defines the function represented by "sym_ctx"
118 Block *function_block = sym_ctx.GetFunctionBlock();
119
120 if (!function_block) {
121 LLDB_LOGF(log, " [CUE::SC] Null function block");
122 return;
123 }
124
125 CompilerDeclContext decl_context = function_block->GetDeclContext();
126
127 if (!decl_context) {
128 LLDB_LOGF(log, " [CUE::SC] Null decl context");
129 return;
130 }
131
132 if (m_ctx_obj) {
133 switch (m_ctx_obj->GetObjectRuntimeLanguage()) {
134 case lldb::eLanguageTypeC:
135 case lldb::eLanguageTypeC89:
136 case lldb::eLanguageTypeC99:
137 case lldb::eLanguageTypeC11:
138 case lldb::eLanguageTypeC_plus_plus:
139 case lldb::eLanguageTypeC_plus_plus_03:
140 case lldb::eLanguageTypeC_plus_plus_11:
141 case lldb::eLanguageTypeC_plus_plus_14:
142 m_in_cplusplus_method = true;
143 break;
144 case lldb::eLanguageTypeObjC:
145 case lldb::eLanguageTypeObjC_plus_plus:
146 m_in_objectivec_method = true;
147 break;
148 default:
149 break;
150 }
151 m_needs_object_ptr = true;
152 } else if (clang::CXXMethodDecl *method_decl =
153 TypeSystemClang::DeclContextGetAsCXXMethodDecl(dc: decl_context)) {
154 if (m_allow_cxx && method_decl->isInstance()) {
155 if (m_enforce_valid_object) {
156 lldb::VariableListSP variable_list_sp(
157 function_block->GetBlockVariableList(can_create: true));
158
159 const char *thisErrorString = "Stopped in a C++ method, but 'this' "
160 "isn't available; pretending we are in a "
161 "generic context";
162
163 if (!variable_list_sp) {
164 err.SetErrorString(thisErrorString);
165 return;
166 }
167
168 lldb::VariableSP this_var_sp(
169 variable_list_sp->FindVariable(name: ConstString("this")));
170
171 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
172 !this_var_sp->LocationIsValidForFrame(frame)) {
173 err.SetErrorString(thisErrorString);
174 return;
175 }
176 }
177
178 m_in_cplusplus_method = true;
179 m_needs_object_ptr = true;
180 }
181 } else if (clang::ObjCMethodDecl *method_decl =
182 TypeSystemClang::DeclContextGetAsObjCMethodDecl(
183 dc: decl_context)) {
184 if (m_allow_objc) {
185 if (m_enforce_valid_object) {
186 lldb::VariableListSP variable_list_sp(
187 function_block->GetBlockVariableList(can_create: true));
188
189 const char *selfErrorString = "Stopped in an Objective-C method, but "
190 "'self' isn't available; pretending we "
191 "are in a generic context";
192
193 if (!variable_list_sp) {
194 err.SetErrorString(selfErrorString);
195 return;
196 }
197
198 lldb::VariableSP self_variable_sp =
199 variable_list_sp->FindVariable(name: ConstString("self"));
200
201 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
202 !self_variable_sp->LocationIsValidForFrame(frame)) {
203 err.SetErrorString(selfErrorString);
204 return;
205 }
206 }
207
208 m_in_objectivec_method = true;
209 m_needs_object_ptr = true;
210
211 if (!method_decl->isInstanceMethod())
212 m_in_static_method = true;
213 }
214 } else if (clang::FunctionDecl *function_decl =
215 TypeSystemClang::DeclContextGetAsFunctionDecl(dc: decl_context)) {
216 // We might also have a function that said in the debug information that it
217 // captured an object pointer. The best way to deal with getting to the
218 // ivars at present is by pretending that this is a method of a class in
219 // whatever runtime the debug info says the object pointer belongs to. Do
220 // that here.
221
222 ClangASTMetadata *metadata =
223 TypeSystemClang::DeclContextGetMetaData(decl_context, function_decl);
224 if (metadata && metadata->HasObjectPtr()) {
225 lldb::LanguageType language = metadata->GetObjectPtrLanguage();
226 if (language == lldb::eLanguageTypeC_plus_plus) {
227 if (m_enforce_valid_object) {
228 lldb::VariableListSP variable_list_sp(
229 function_block->GetBlockVariableList(can_create: true));
230
231 const char *thisErrorString = "Stopped in a context claiming to "
232 "capture a C++ object pointer, but "
233 "'this' isn't available; pretending we "
234 "are in a generic context";
235
236 if (!variable_list_sp) {
237 err.SetErrorString(thisErrorString);
238 return;
239 }
240
241 lldb::VariableSP this_var_sp(
242 variable_list_sp->FindVariable(name: ConstString("this")));
243
244 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
245 !this_var_sp->LocationIsValidForFrame(frame)) {
246 err.SetErrorString(thisErrorString);
247 return;
248 }
249 }
250
251 m_in_cplusplus_method = true;
252 m_needs_object_ptr = true;
253 } else if (language == lldb::eLanguageTypeObjC) {
254 if (m_enforce_valid_object) {
255 lldb::VariableListSP variable_list_sp(
256 function_block->GetBlockVariableList(can_create: true));
257
258 const char *selfErrorString =
259 "Stopped in a context claiming to capture an Objective-C object "
260 "pointer, but 'self' isn't available; pretending we are in a "
261 "generic context";
262
263 if (!variable_list_sp) {
264 err.SetErrorString(selfErrorString);
265 return;
266 }
267
268 lldb::VariableSP self_variable_sp =
269 variable_list_sp->FindVariable(name: ConstString("self"));
270
271 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
272 !self_variable_sp->LocationIsValidForFrame(frame)) {
273 err.SetErrorString(selfErrorString);
274 return;
275 }
276
277 Type *self_type = self_variable_sp->GetType();
278
279 if (!self_type) {
280 err.SetErrorString(selfErrorString);
281 return;
282 }
283
284 CompilerType self_clang_type = self_type->GetForwardCompilerType();
285
286 if (!self_clang_type) {
287 err.SetErrorString(selfErrorString);
288 return;
289 }
290
291 if (TypeSystemClang::IsObjCClassType(type: self_clang_type)) {
292 return;
293 } else if (TypeSystemClang::IsObjCObjectPointerType(
294 type: self_clang_type)) {
295 m_in_objectivec_method = true;
296 m_needs_object_ptr = true;
297 } else {
298 err.SetErrorString(selfErrorString);
299 return;
300 }
301 } else {
302 m_in_objectivec_method = true;
303 m_needs_object_ptr = true;
304 }
305 }
306 }
307 }
308}
309
310// This is a really nasty hack, meant to fix Objective-C expressions of the
311// form (int)[myArray count]. Right now, because the type information for
312// count is not available, [myArray count] returns id, which can't be directly
313// cast to int without causing a clang error.
314static void ApplyObjcCastHack(std::string &expr) {
315 const std::string from = "(int)[";
316 const std::string to = "(int)(long long)[";
317
318 size_t offset;
319
320 while ((offset = expr.find(str: from)) != expr.npos)
321 expr.replace(pos: offset, n: from.size(), str: to);
322}
323
324bool ClangUserExpression::SetupPersistentState(DiagnosticManager &diagnostic_manager,
325 ExecutionContext &exe_ctx) {
326 if (Target *target = exe_ctx.GetTargetPtr()) {
327 if (PersistentExpressionState *persistent_state =
328 target->GetPersistentExpressionStateForLanguage(
329 language: lldb::eLanguageTypeC)) {
330 m_clang_state = llvm::cast<ClangPersistentVariables>(Val: persistent_state);
331 m_result_delegate.RegisterPersistentState(persistent_state);
332 } else {
333 diagnostic_manager.PutString(
334 severity: eDiagnosticSeverityError,
335 str: "couldn't start parsing (no persistent data)");
336 return false;
337 }
338 } else {
339 diagnostic_manager.PutString(severity: eDiagnosticSeverityError,
340 str: "error: couldn't start parsing (no target)");
341 return false;
342 }
343 return true;
344}
345
346static void SetupDeclVendor(ExecutionContext &exe_ctx, Target *target,
347 DiagnosticManager &diagnostic_manager) {
348 if (!target->GetEnableAutoImportClangModules())
349 return;
350
351 auto *persistent_state = llvm::cast<ClangPersistentVariables>(
352 Val: target->GetPersistentExpressionStateForLanguage(language: lldb::eLanguageTypeC));
353 if (!persistent_state)
354 return;
355
356 std::shared_ptr<ClangModulesDeclVendor> decl_vendor =
357 persistent_state->GetClangModulesDeclVendor();
358 if (!decl_vendor)
359 return;
360
361 StackFrame *frame = exe_ctx.GetFramePtr();
362 if (!frame)
363 return;
364
365 Block *block = frame->GetFrameBlock();
366 if (!block)
367 return;
368 SymbolContext sc;
369
370 block->CalculateSymbolContext(sc: &sc);
371
372 if (!sc.comp_unit)
373 return;
374 StreamString error_stream;
375
376 ClangModulesDeclVendor::ModuleVector modules_for_macros =
377 persistent_state->GetHandLoadedClangModules();
378 if (decl_vendor->AddModulesForCompileUnit(cu&: *sc.comp_unit, exported_modules&: modules_for_macros,
379 error_stream))
380 return;
381
382 // Failed to load some modules, so emit the error stream as a diagnostic.
383 if (!error_stream.Empty()) {
384 // The error stream already contains several Clang diagnostics that might
385 // be either errors or warnings, so just print them all as one remark
386 // diagnostic to prevent that the message starts with "error: error:".
387 diagnostic_manager.PutString(severity: eDiagnosticSeverityRemark,
388 str: error_stream.GetString());
389 return;
390 }
391
392 diagnostic_manager.PutString(severity: eDiagnosticSeverityError,
393 str: "Unknown error while loading modules needed for "
394 "current compilation unit.");
395}
396
397ClangExpressionSourceCode::WrapKind ClangUserExpression::GetWrapKind() const {
398 assert(m_options.GetExecutionPolicy() != eExecutionPolicyTopLevel &&
399 "Top level expressions aren't wrapped.");
400 using Kind = ClangExpressionSourceCode::WrapKind;
401 if (m_in_cplusplus_method)
402 return Kind::CppMemberFunction;
403 else if (m_in_objectivec_method) {
404 if (m_in_static_method)
405 return Kind::ObjCStaticMethod;
406 return Kind::ObjCInstanceMethod;
407 }
408 // Not in any kind of 'special' function, so just wrap it in a normal C
409 // function.
410 return Kind::Function;
411}
412
413void ClangUserExpression::CreateSourceCode(
414 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
415 std::vector<std::string> modules_to_import, bool for_completion) {
416
417 std::string prefix = m_expr_prefix;
418
419 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
420 m_transformed_text = m_expr_text;
421 } else {
422 m_source_code.reset(p: ClangExpressionSourceCode::CreateWrapped(
423 filename: m_filename, prefix, body: m_expr_text, wrap_kind: GetWrapKind()));
424
425 if (!m_source_code->GetText(text&: m_transformed_text, exe_ctx, add_locals: !m_ctx_obj,
426 force_add_all_locals: for_completion, modules: modules_to_import)) {
427 diagnostic_manager.PutString(severity: eDiagnosticSeverityError,
428 str: "couldn't construct expression body");
429 return;
430 }
431
432 // Find and store the start position of the original code inside the
433 // transformed code. We need this later for the code completion.
434 std::size_t original_start;
435 std::size_t original_end;
436 bool found_bounds = m_source_code->GetOriginalBodyBounds(
437 transformed_text: m_transformed_text, start_loc&: original_start, end_loc&: original_end);
438 if (found_bounds)
439 m_user_expression_start_pos = original_start;
440 }
441}
442
443static bool SupportsCxxModuleImport(lldb::LanguageType language) {
444 switch (language) {
445 case lldb::eLanguageTypeC_plus_plus:
446 case lldb::eLanguageTypeC_plus_plus_03:
447 case lldb::eLanguageTypeC_plus_plus_11:
448 case lldb::eLanguageTypeC_plus_plus_14:
449 case lldb::eLanguageTypeObjC_plus_plus:
450 return true;
451 default:
452 return false;
453 }
454}
455
456/// Utility method that puts a message into the expression log and
457/// returns an invalid module configuration.
458static CppModuleConfiguration LogConfigError(const std::string &msg) {
459 Log *log = GetLog(mask: LLDBLog::Expressions);
460 LLDB_LOG(log, "[C++ module config] {0}", msg);
461 return CppModuleConfiguration();
462}
463
464CppModuleConfiguration GetModuleConfig(lldb::LanguageType language,
465 ExecutionContext &exe_ctx) {
466 Log *log = GetLog(mask: LLDBLog::Expressions);
467
468 // Don't do anything if this is not a C++ module configuration.
469 if (!SupportsCxxModuleImport(language))
470 return LogConfigError(msg: "Language doesn't support C++ modules");
471
472 Target *target = exe_ctx.GetTargetPtr();
473 if (!target)
474 return LogConfigError(msg: "No target");
475
476 StackFrame *frame = exe_ctx.GetFramePtr();
477 if (!frame)
478 return LogConfigError(msg: "No frame");
479
480 Block *block = frame->GetFrameBlock();
481 if (!block)
482 return LogConfigError(msg: "No block");
483
484 SymbolContext sc;
485 block->CalculateSymbolContext(sc: &sc);
486 if (!sc.comp_unit)
487 return LogConfigError(msg: "Couldn't calculate symbol context");
488
489 // Build a list of files we need to analyze to build the configuration.
490 FileSpecList files;
491 for (auto &f : sc.comp_unit->GetSupportFiles())
492 files.AppendIfUnique(file: f->Materialize());
493 // We also need to look at external modules in the case of -gmodules as they
494 // contain the support files for libc++ and the C library.
495 llvm::DenseSet<SymbolFile *> visited_symbol_files;
496 sc.comp_unit->ForEachExternalModule(
497 visited_symbol_files, lambda: [&files](Module &module) {
498 for (std::size_t i = 0; i < module.GetNumCompileUnits(); ++i) {
499 const SupportFileList &support_files =
500 module.GetCompileUnitAtIndex(idx: i)->GetSupportFiles();
501 for (auto &f : support_files) {
502 files.AppendIfUnique(file: f->Materialize());
503 }
504 }
505 return false;
506 });
507
508 LLDB_LOG(log, "[C++ module config] Found {0} support files to analyze",
509 files.GetSize());
510 if (log && log->GetVerbose()) {
511 for (auto &f : files)
512 LLDB_LOGV(log, "[C++ module config] Analyzing support file: {0}",
513 f.GetPath());
514 }
515
516 // Try to create a configuration from the files. If there is no valid
517 // configuration possible with the files, this just returns an invalid
518 // configuration.
519 return CppModuleConfiguration(files, target->GetArchitecture().GetTriple());
520}
521
522bool ClangUserExpression::PrepareForParsing(
523 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
524 bool for_completion) {
525 InstallContext(exe_ctx);
526
527 if (!SetupPersistentState(diagnostic_manager, exe_ctx))
528 return false;
529
530 Status err;
531 ScanContext(exe_ctx, err);
532
533 if (!err.Success()) {
534 diagnostic_manager.PutString(severity: eDiagnosticSeverityWarning, str: err.AsCString());
535 }
536
537 ////////////////////////////////////
538 // Generate the expression
539 //
540
541 ApplyObjcCastHack(expr&: m_expr_text);
542
543 SetupDeclVendor(exe_ctx, target: m_target, diagnostic_manager);
544
545 m_filename = m_clang_state->GetNextExprFileName();
546
547 if (m_target->GetImportStdModule() == eImportStdModuleTrue)
548 SetupCppModuleImports(exe_ctx);
549
550 CreateSourceCode(diagnostic_manager, exe_ctx, modules_to_import: m_imported_cpp_modules,
551 for_completion);
552 return true;
553}
554
555bool ClangUserExpression::TryParse(
556 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
557 lldb_private::ExecutionPolicy execution_policy, bool keep_result_in_memory,
558 bool generate_debug_info) {
559 m_materializer_up = std::make_unique<Materializer>();
560
561 ResetDeclMap(exe_ctx, result_delegate&: m_result_delegate, keep_result_in_memory);
562
563 auto on_exit = llvm::make_scope_exit(F: [this]() { ResetDeclMap(); });
564
565 if (!DeclMap()->WillParse(exe_ctx, materializer: GetMaterializer())) {
566 diagnostic_manager.PutString(
567 severity: eDiagnosticSeverityError,
568 str: "current process state is unsuitable for expression parsing");
569 return false;
570 }
571
572 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
573 DeclMap()->SetLookupsEnabled(true);
574 }
575
576 m_parser = std::make_unique<ClangExpressionParser>(
577 args: exe_ctx.GetBestExecutionContextScope(), args&: *this, args&: generate_debug_info,
578 args&: m_include_directories, args&: 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 transformed_text: m_fixed_text, start_loc&: fixed_start, end_loc&: fixed_end))
594 m_fixed_text =
595 m_fixed_text.substr(pos: fixed_start, n: 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(
608 func_addr&: m_jit_start_addr, func_end&: m_jit_end_addr, execution_unit_sp&: m_execution_unit_sp, exe_ctx,
609 can_interpret&: 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(severity: eDiagnosticSeverityError, str: error_cstr);
615 else
616 diagnostic_manager.PutString(severity: eDiagnosticSeverityError,
617 str: "expression can't be interpreted or run");
618 return false;
619 }
620 }
621 return true;
622}
623
624void ClangUserExpression::SetupCppModuleImports(ExecutionContext &exe_ctx) {
625 Log *log = GetLog(mask: LLDBLog::Expressions);
626
627 CppModuleConfiguration module_config = GetModuleConfig(language: m_language, exe_ctx);
628 m_imported_cpp_modules = module_config.GetImportedModules();
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(),
633 m_imported_cpp_modules.end()));
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.
641 if (exe_policy == ExecutionPolicy::eExecutionPolicyTopLevel)
642 return false;
643 return target.GetImportStdModule() == eImportStdModuleFallback;
644}
645
646bool ClangUserExpression::Parse(DiagnosticManager &diagnostic_manager,
647 ExecutionContext &exe_ctx,
648 lldb_private::ExecutionPolicy execution_policy,
649 bool keep_result_in_memory,
650 bool generate_debug_info) {
651 Log *log = GetLog(mask: LLDBLog::Expressions);
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(severity: eDiagnosticSeverityError, str: "invalid target");
666 return false;
667 }
668
669 //////////////////////////
670 // Parse the expression
671 //
672
673 bool parse_success = TryParse(diagnostic_manager, exe_ctx, execution_policy,
674 keep_result_in_memory, generate_debug_info);
675 // If the expression failed to parse, check if retrying parsing with a loaded
676 // C++ module is possible.
677 if (!parse_success && shouldRetryWithCppModule(target&: *target, exe_policy: execution_policy)) {
678 // Load the loaded C++ modules.
679 SetupCppModuleImports(exe_ctx);
680 // If we did load any modules, then retry parsing.
681 if (!m_imported_cpp_modules.empty()) {
682 // Create a dedicated diagnostic manager for the second parse attempt.
683 // These diagnostics are only returned to the caller if using the fallback
684 // actually succeeded in getting the expression to parse. This prevents
685 // that module-specific issues regress diagnostic quality with the
686 // fallback mode.
687 DiagnosticManager retry_manager;
688 // The module imports are injected into the source code wrapper,
689 // so recreate those.
690 CreateSourceCode(diagnostic_manager&: retry_manager, exe_ctx, modules_to_import: m_imported_cpp_modules,
691 /*for_completion*/ false);
692 parse_success = TryParse(diagnostic_manager&: retry_manager, exe_ctx, execution_policy,
693 keep_result_in_memory, generate_debug_info);
694 // Return the parse diagnostics if we were successful.
695 if (parse_success)
696 diagnostic_manager = std::move(retry_manager);
697 }
698 }
699 if (!parse_success)
700 return false;
701
702 if (exe_ctx.GetProcessPtr() && execution_policy == eExecutionPolicyTopLevel) {
703 Status static_init_error =
704 m_parser->RunStaticInitializers(execution_unit_sp&: m_execution_unit_sp, exe_ctx);
705
706 if (!static_init_error.Success()) {
707 const char *error_cstr = static_init_error.AsCString();
708 if (error_cstr && error_cstr[0])
709 diagnostic_manager.Printf(severity: eDiagnosticSeverityError,
710 format: "%s\n",
711 error_cstr);
712 else
713 diagnostic_manager.PutString(severity: eDiagnosticSeverityError,
714 str: "couldn't run static initializers\n");
715 return false;
716 }
717 }
718
719 if (m_execution_unit_sp) {
720 bool register_execution_unit = false;
721
722 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
723 register_execution_unit = true;
724 }
725
726 // If there is more than one external function in the execution unit, it
727 // needs to keep living even if it's not top level, because the result
728 // could refer to that function.
729
730 if (m_execution_unit_sp->GetJittedFunctions().size() > 1) {
731 register_execution_unit = true;
732 }
733
734 if (register_execution_unit) {
735 if (auto *persistent_state =
736 exe_ctx.GetTargetPtr()->GetPersistentExpressionStateForLanguage(
737 language: m_language))
738 persistent_state->RegisterExecutionUnit(execution_unit_sp&: m_execution_unit_sp);
739 }
740 }
741
742 if (generate_debug_info) {
743 lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
744
745 if (jit_module_sp) {
746 ConstString const_func_name(FunctionName());
747 FileSpec jit_file;
748 jit_file.SetFilename(const_func_name);
749 jit_module_sp->SetFileSpecAndObjectName(file: jit_file, object_name: ConstString());
750 m_jit_module_wp = jit_module_sp;
751 target->GetImages().Append(module_sp: jit_module_sp);
752 }
753 }
754
755 Process *process = exe_ctx.GetProcessPtr();
756 if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS)
757 m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
758 return true;
759}
760
761/// Converts an absolute position inside a given code string into
762/// a column/line pair.
763///
764/// \param[in] abs_pos
765/// A absolute position in the code string that we want to convert
766/// to a column/line pair.
767///
768/// \param[in] code
769/// A multi-line string usually representing source code.
770///
771/// \param[out] line
772/// The line in the code that contains the given absolute position.
773/// The first line in the string is indexed as 1.
774///
775/// \param[out] column
776/// The column in the line that contains the absolute position.
777/// The first character in a line is indexed as 0.
778static void AbsPosToLineColumnPos(size_t abs_pos, llvm::StringRef code,
779 unsigned &line, unsigned &column) {
780 // Reset to code position to beginning of the file.
781 line = 0;
782 column = 0;
783
784 assert(abs_pos <= code.size() && "Absolute position outside code string?");
785
786 // We have to walk up to the position and count lines/columns.
787 for (std::size_t i = 0; i < abs_pos; ++i) {
788 // If we hit a line break, we go back to column 0 and enter a new line.
789 // We only handle \n because that's what we internally use to make new
790 // lines for our temporary code strings.
791 if (code[i] == '\n') {
792 ++line;
793 column = 0;
794 continue;
795 }
796 ++column;
797 }
798}
799
800bool ClangUserExpression::Complete(ExecutionContext &exe_ctx,
801 CompletionRequest &request,
802 unsigned complete_pos) {
803 Log *log = GetLog(mask: LLDBLog::Expressions);
804
805 // We don't want any visible feedback when completing an expression. Mostly
806 // because the results we get from an incomplete invocation are probably not
807 // correct.
808 DiagnosticManager diagnostic_manager;
809
810 if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ true))
811 return false;
812
813 LLDB_LOGF(log, "Parsing the following code:\n%s", m_transformed_text.c_str());
814
815 //////////////////////////
816 // Parse the expression
817 //
818
819 m_materializer_up = std::make_unique<Materializer>();
820
821 ResetDeclMap(exe_ctx, result_delegate&: m_result_delegate, /*keep result in memory*/ keep_result_in_memory: true);
822
823 auto on_exit = llvm::make_scope_exit(F: [this]() { ResetDeclMap(); });
824
825 if (!DeclMap()->WillParse(exe_ctx, materializer: GetMaterializer())) {
826 diagnostic_manager.PutString(
827 severity: eDiagnosticSeverityError,
828 str: "current process state is unsuitable for expression parsing");
829
830 return false;
831 }
832
833 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
834 DeclMap()->SetLookupsEnabled(true);
835 }
836
837 ClangExpressionParser parser(exe_ctx.GetBestExecutionContextScope(), *this,
838 false);
839
840 // We have to find the source code location where the user text is inside
841 // the transformed expression code. When creating the transformed text, we
842 // already stored the absolute position in the m_transformed_text string. The
843 // only thing left to do is to transform it into the line:column format that
844 // Clang expects.
845
846 // The line and column of the user expression inside the transformed source
847 // code.
848 unsigned user_expr_line, user_expr_column;
849 if (m_user_expression_start_pos)
850 AbsPosToLineColumnPos(abs_pos: *m_user_expression_start_pos, code: m_transformed_text,
851 line&: user_expr_line, column&: user_expr_column);
852 else
853 return false;
854
855 // The actual column where we have to complete is the start column of the
856 // user expression + the offset inside the user code that we were given.
857 const unsigned completion_column = user_expr_column + complete_pos;
858 parser.Complete(request, line: user_expr_line, pos: completion_column, typed_pos: complete_pos);
859
860 return true;
861}
862
863lldb::addr_t ClangUserExpression::GetCppObjectPointer(
864 lldb::StackFrameSP frame_sp, llvm::StringRef object_name, Status &err) {
865 auto valobj_sp =
866 GetObjectPointerValueObject(frame: std::move(frame_sp), object_name, err);
867
868 // We're inside a C++ class method. This could potentially be an unnamed
869 // lambda structure. If the lambda captured a "this", that should be
870 // the object pointer.
871 if (auto thisChildSP = valobj_sp->GetChildMemberWithName(name: "this")) {
872 valobj_sp = thisChildSP;
873 }
874
875 if (!err.Success() || !valobj_sp.get())
876 return LLDB_INVALID_ADDRESS;
877
878 lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
879
880 if (ret == LLDB_INVALID_ADDRESS) {
881 err.SetErrorStringWithFormatv(
882 format: "Couldn't load '{0}' because its value couldn't be evaluated",
883 args&: object_name);
884 return LLDB_INVALID_ADDRESS;
885 }
886
887 return ret;
888}
889
890bool ClangUserExpression::AddArguments(ExecutionContext &exe_ctx,
891 std::vector<lldb::addr_t> &args,
892 lldb::addr_t struct_address,
893 DiagnosticManager &diagnostic_manager) {
894 lldb::addr_t object_ptr = LLDB_INVALID_ADDRESS;
895 lldb::addr_t cmd_ptr = LLDB_INVALID_ADDRESS;
896
897 if (m_needs_object_ptr) {
898 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
899 if (!frame_sp)
900 return true;
901
902 if (!m_in_cplusplus_method && !m_in_objectivec_method) {
903 diagnostic_manager.PutString(
904 severity: eDiagnosticSeverityError,
905 str: "need object pointer but don't know the language");
906 return false;
907 }
908
909 static constexpr llvm::StringLiteral g_cplusplus_object_name("this");
910 static constexpr llvm::StringLiteral g_objc_object_name("self");
911 llvm::StringRef object_name =
912 m_in_cplusplus_method ? g_cplusplus_object_name : g_objc_object_name;
913
914 Status object_ptr_error;
915
916 if (m_ctx_obj) {
917 AddressType address_type;
918 object_ptr = m_ctx_obj->GetAddressOf(scalar_is_load_address: false, address_type: &address_type);
919 if (object_ptr == LLDB_INVALID_ADDRESS ||
920 address_type != eAddressTypeLoad)
921 object_ptr_error.SetErrorString("Can't get context object's "
922 "debuggee address");
923 } else {
924 if (m_in_cplusplus_method) {
925 object_ptr =
926 GetCppObjectPointer(frame_sp, object_name, err&: object_ptr_error);
927 } else {
928 object_ptr = GetObjectPointer(frame_sp, object_name, err&: object_ptr_error);
929 }
930 }
931
932 if (!object_ptr_error.Success()) {
933 exe_ctx.GetTargetRef().GetDebugger().GetAsyncOutputStream()->Format(
934 format: "warning: `{0}' is not accessible (substituting 0). {1}\n",
935 args&: object_name, args: object_ptr_error.AsCString());
936 object_ptr = 0;
937 }
938
939 if (m_in_objectivec_method) {
940 static constexpr llvm::StringLiteral cmd_name("_cmd");
941
942 cmd_ptr = GetObjectPointer(frame_sp, object_name: cmd_name, err&: object_ptr_error);
943
944 if (!object_ptr_error.Success()) {
945 diagnostic_manager.Printf(
946 severity: eDiagnosticSeverityWarning,
947 format: "couldn't get cmd pointer (substituting NULL): %s",
948 object_ptr_error.AsCString());
949 cmd_ptr = 0;
950 }
951 }
952
953 args.push_back(x: object_ptr);
954
955 if (m_in_objectivec_method)
956 args.push_back(x: cmd_ptr);
957
958 args.push_back(x: struct_address);
959 } else {
960 args.push_back(x: struct_address);
961 }
962 return true;
963}
964
965lldb::ExpressionVariableSP ClangUserExpression::GetResultAfterDematerialization(
966 ExecutionContextScope *exe_scope) {
967 return m_result_delegate.GetVariable();
968}
969
970char ClangUserExpression::ClangUserExpressionHelper::ID;
971
972void ClangUserExpression::ClangUserExpressionHelper::ResetDeclMap(
973 ExecutionContext &exe_ctx,
974 Materializer::PersistentVariableDelegate &delegate,
975 bool keep_result_in_memory,
976 ValueObject *ctx_obj) {
977 std::shared_ptr<ClangASTImporter> ast_importer;
978 auto *state = exe_ctx.GetTargetSP()->GetPersistentExpressionStateForLanguage(
979 language: lldb::eLanguageTypeC);
980 if (state) {
981 auto *persistent_vars = llvm::cast<ClangPersistentVariables>(Val: state);
982 ast_importer = persistent_vars->GetClangASTImporter();
983 }
984 m_expr_decl_map_up = std::make_unique<ClangExpressionDeclMap>(
985 args&: keep_result_in_memory, args: &delegate, args: exe_ctx.GetTargetSP(), args&: ast_importer,
986 args&: ctx_obj);
987}
988
989clang::ASTConsumer *
990ClangUserExpression::ClangUserExpressionHelper::ASTTransformer(
991 clang::ASTConsumer *passthrough) {
992 m_result_synthesizer_up = std::make_unique<ASTResultSynthesizer>(
993 args&: passthrough, args&: m_top_level, args&: m_target);
994
995 return m_result_synthesizer_up.get();
996}
997
998void ClangUserExpression::ClangUserExpressionHelper::CommitPersistentDecls() {
999 if (m_result_synthesizer_up) {
1000 m_result_synthesizer_up->CommitPersistentDecls();
1001 }
1002}
1003
1004ConstString ClangUserExpression::ResultDelegate::GetName() {
1005 return m_persistent_state->GetNextPersistentVariableName(is_error: false);
1006}
1007
1008void ClangUserExpression::ResultDelegate::DidDematerialize(
1009 lldb::ExpressionVariableSP &variable) {
1010 m_variable = variable;
1011}
1012
1013void ClangUserExpression::ResultDelegate::RegisterPersistentState(
1014 PersistentExpressionState *persistent_state) {
1015 m_persistent_state = persistent_state;
1016}
1017
1018lldb::ExpressionVariableSP &ClangUserExpression::ResultDelegate::GetVariable() {
1019 return m_variable;
1020}
1021

source code of lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.cpp