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 "lldb/Host/Config.h"
10 
11 #include <stdio.h>
12 #if HAVE_SYS_TYPES_H
13 #include <sys/types.h>
14 #endif
15 
16 #include <cstdlib>
17 #include <map>
18 #include <string>
19 
20 #include "ClangUserExpression.h"
21 
22 #include "ASTResultSynthesizer.h"
23 #include "ClangASTMetadata.h"
24 #include "ClangDiagnostic.h"
25 #include "ClangExpressionDeclMap.h"
26 #include "ClangExpressionParser.h"
27 #include "ClangModulesDeclVendor.h"
28 #include "ClangPersistentVariables.h"
29 #include "CppModuleConfiguration.h"
30 
31 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
32 #include "lldb/Core/Debugger.h"
33 #include "lldb/Core/Module.h"
34 #include "lldb/Core/StreamFile.h"
35 #include "lldb/Core/ValueObjectConstResult.h"
36 #include "lldb/Expression/ExpressionSourceCode.h"
37 #include "lldb/Expression/IRExecutionUnit.h"
38 #include "lldb/Expression/IRInterpreter.h"
39 #include "lldb/Expression/Materializer.h"
40 #include "lldb/Host/HostInfo.h"
41 #include "lldb/Symbol/Block.h"
42 #include "lldb/Symbol/CompileUnit.h"
43 #include "lldb/Symbol/Function.h"
44 #include "lldb/Symbol/ObjectFile.h"
45 #include "lldb/Symbol/SymbolFile.h"
46 #include "lldb/Symbol/SymbolVendor.h"
47 #include "lldb/Symbol/Type.h"
48 #include "lldb/Symbol/VariableList.h"
49 #include "lldb/Target/ExecutionContext.h"
50 #include "lldb/Target/Process.h"
51 #include "lldb/Target/StackFrame.h"
52 #include "lldb/Target/Target.h"
53 #include "lldb/Target/ThreadPlan.h"
54 #include "lldb/Target/ThreadPlanCallUserExpression.h"
55 #include "lldb/Utility/ConstString.h"
56 #include "lldb/Utility/Log.h"
57 #include "lldb/Utility/StreamString.h"
58 
59 #include "clang/AST/DeclCXX.h"
60 #include "clang/AST/DeclObjC.h"
61 
62 #include "llvm/ADT/ScopeExit.h"
63 
64 using namespace lldb_private;
65 
66 char ClangUserExpression::ID;
67 
68 ClangUserExpression::ClangUserExpression(
69     ExecutionContextScope &exe_scope, llvm::StringRef expr,
70     llvm::StringRef prefix, lldb::LanguageType language,
71     ResultType desired_type, const EvaluateExpressionOptions &options,
72     ValueObject *ctx_obj)
73     : LLVMUserExpression(exe_scope, expr, prefix, language, desired_type,
74                          options),
75       m_type_system_helper(*m_target_wp.lock(), options.GetExecutionPolicy() ==
76                                                     eExecutionPolicyTopLevel),
77       m_result_delegate(exe_scope.CalculateTarget()), m_ctx_obj(ctx_obj) {
78   switch (m_language) {
79   case lldb::eLanguageTypeC_plus_plus:
80     m_allow_cxx = true;
81     break;
82   case lldb::eLanguageTypeObjC:
83     m_allow_objc = true;
84     break;
85   case lldb::eLanguageTypeObjC_plus_plus:
86   default:
87     m_allow_cxx = true;
88     m_allow_objc = true;
89     break;
90   }
91 }
92 
93 ClangUserExpression::~ClangUserExpression() {}
94 
95 void ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Status &err) {
96   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
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()) {
138     case lldb::eLanguageTypeC:
139     case lldb::eLanguageTypeC89:
140     case lldb::eLanguageTypeC99:
141     case lldb::eLanguageTypeC11:
142     case lldb::eLanguageTypeC_plus_plus:
143     case lldb::eLanguageTypeC_plus_plus_03:
144     case lldb::eLanguageTypeC_plus_plus_11:
145     case lldb::eLanguageTypeC_plus_plus_14:
146       m_in_cplusplus_method = true;
147       break;
148     case lldb::eLanguageTypeObjC:
149     case lldb::eLanguageTypeObjC_plus_plus:
150       m_in_objectivec_method = true;
151       break;
152     default:
153       break;
154     }
155     m_needs_object_ptr = true;
156   } else if (clang::CXXMethodDecl *method_decl =
157           TypeSystemClang::DeclContextGetAsCXXMethodDecl(decl_context)) {
158     if (m_allow_cxx) {
159       if (method_decl->isInstance()) {
160         if (m_enforce_valid_object) {
161           lldb::VariableListSP variable_list_sp(
162               function_block->GetBlockVariableList(true));
163 
164           const char *thisErrorString =
165               "Stopped in a C++ method, but 'this' "
166               "isn't available; pretending we are in a "
167               "generic context";
168 
169           if (!variable_list_sp) {
170             err.SetErrorString(thisErrorString);
171             return;
172           }
173 
174           lldb::VariableSP this_var_sp(
175               variable_list_sp->FindVariable(ConstString("this")));
176 
177           if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
178               !this_var_sp->LocationIsValidForFrame(frame)) {
179             err.SetErrorString(thisErrorString);
180             return;
181           }
182         }
183         m_needs_object_ptr = true;
184       }
185       m_in_cplusplus_method = true;
186       m_in_static_method = !method_decl->isInstance();
187     }
188   } else if (clang::ObjCMethodDecl *method_decl =
189                  TypeSystemClang::DeclContextGetAsObjCMethodDecl(
190                      decl_context)) {
191     if (m_allow_objc) {
192       if (m_enforce_valid_object) {
193         lldb::VariableListSP variable_list_sp(
194             function_block->GetBlockVariableList(true));
195 
196         const char *selfErrorString = "Stopped in an Objective-C method, but "
197                                       "'self' isn't available; pretending we "
198                                       "are in a generic context";
199 
200         if (!variable_list_sp) {
201           err.SetErrorString(selfErrorString);
202           return;
203         }
204 
205         lldb::VariableSP self_variable_sp =
206             variable_list_sp->FindVariable(ConstString("self"));
207 
208         if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
209             !self_variable_sp->LocationIsValidForFrame(frame)) {
210           err.SetErrorString(selfErrorString);
211           return;
212         }
213       }
214 
215       m_in_objectivec_method = true;
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 =
222                  TypeSystemClang::DeclContextGetAsFunctionDecl(decl_context)) {
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     ClangASTMetadata *metadata =
230         TypeSystemClang::DeclContextGetMetaData(decl_context, function_decl);
231     if (metadata && metadata->HasObjectPtr()) {
232       lldb::LanguageType language = metadata->GetObjectPtrLanguage();
233       if (language == lldb::eLanguageTypeC_plus_plus) {
234         if (m_enforce_valid_object) {
235           lldb::VariableListSP variable_list_sp(
236               function_block->GetBlockVariableList(true));
237 
238           const char *thisErrorString = "Stopped in a context claiming to "
239                                         "capture a C++ object pointer, but "
240                                         "'this' isn't available; pretending we "
241                                         "are in a generic context";
242 
243           if (!variable_list_sp) {
244             err.SetErrorString(thisErrorString);
245             return;
246           }
247 
248           lldb::VariableSP this_var_sp(
249               variable_list_sp->FindVariable(ConstString("this")));
250 
251           if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
252               !this_var_sp->LocationIsValidForFrame(frame)) {
253             err.SetErrorString(thisErrorString);
254             return;
255           }
256         }
257 
258         m_in_cplusplus_method = true;
259         m_needs_object_ptr = true;
260       } else if (language == lldb::eLanguageTypeObjC) {
261         if (m_enforce_valid_object) {
262           lldb::VariableListSP variable_list_sp(
263               function_block->GetBlockVariableList(true));
264 
265           const char *selfErrorString =
266               "Stopped in a context claiming to capture an Objective-C object "
267               "pointer, but 'self' isn't available; pretending we are in a "
268               "generic context";
269 
270           if (!variable_list_sp) {
271             err.SetErrorString(selfErrorString);
272             return;
273           }
274 
275           lldb::VariableSP self_variable_sp =
276               variable_list_sp->FindVariable(ConstString("self"));
277 
278           if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
279               !self_variable_sp->LocationIsValidForFrame(frame)) {
280             err.SetErrorString(selfErrorString);
281             return;
282           }
283 
284           Type *self_type = self_variable_sp->GetType();
285 
286           if (!self_type) {
287             err.SetErrorString(selfErrorString);
288             return;
289           }
290 
291           CompilerType self_clang_type = self_type->GetForwardCompilerType();
292 
293           if (!self_clang_type) {
294             err.SetErrorString(selfErrorString);
295             return;
296           }
297 
298           if (TypeSystemClang::IsObjCClassType(self_clang_type)) {
299             return;
300           } else if (TypeSystemClang::IsObjCObjectPointerType(
301                          self_clang_type)) {
302             m_in_objectivec_method = true;
303             m_needs_object_ptr = true;
304           } else {
305             err.SetErrorString(selfErrorString);
306             return;
307           }
308         } else {
309           m_in_objectivec_method = true;
310           m_needs_object_ptr = true;
311         }
312       }
313     }
314   }
315 }
316 
317 // This is a really nasty hack, meant to fix Objective-C expressions of the
318 // form (int)[myArray count].  Right now, because the type information for
319 // count is not available, [myArray count] returns id, which can't be directly
320 // cast to int without causing a clang error.
321 static void ApplyObjcCastHack(std::string &expr) {
322   const std::string from = "(int)[";
323   const std::string to = "(int)(long long)[";
324 
325   size_t offset;
326 
327   while ((offset = expr.find(from)) != expr.npos)
328     expr.replace(offset, from.size(), to);
329 }
330 
331 bool ClangUserExpression::SetupPersistentState(DiagnosticManager &diagnostic_manager,
332                                  ExecutionContext &exe_ctx) {
333   if (Target *target = exe_ctx.GetTargetPtr()) {
334     if (PersistentExpressionState *persistent_state =
335             target->GetPersistentExpressionStateForLanguage(
336                 lldb::eLanguageTypeC)) {
337       m_clang_state = llvm::cast<ClangPersistentVariables>(persistent_state);
338       m_result_delegate.RegisterPersistentState(persistent_state);
339     } else {
340       diagnostic_manager.PutString(
341           eDiagnosticSeverityError,
342           "couldn't start parsing (no persistent data)");
343       return false;
344     }
345   } else {
346     diagnostic_manager.PutString(eDiagnosticSeverityError,
347                                  "error: couldn't start parsing (no target)");
348     return false;
349   }
350   return true;
351 }
352 
353 static void SetupDeclVendor(ExecutionContext &exe_ctx, Target *target,
354                             DiagnosticManager &diagnostic_manager) {
355   ClangModulesDeclVendor *decl_vendor = target->GetClangModulesDeclVendor();
356   if (!decl_vendor)
357     return;
358 
359   if (!target->GetEnableAutoImportClangModules())
360     return;
361 
362   auto *persistent_state = llvm::cast<ClangPersistentVariables>(
363       target->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC));
364   if (!persistent_state)
365     return;
366 
367   StackFrame *frame = exe_ctx.GetFramePtr();
368   if (!frame)
369     return;
370 
371   Block *block = frame->GetFrameBlock();
372   if (!block)
373     return;
374   SymbolContext sc;
375 
376   block->CalculateSymbolContext(&sc);
377 
378   if (!sc.comp_unit)
379     return;
380   StreamString error_stream;
381 
382   ClangModulesDeclVendor::ModuleVector modules_for_macros =
383       persistent_state->GetHandLoadedClangModules();
384   if (decl_vendor->AddModulesForCompileUnit(*sc.comp_unit, modules_for_macros,
385                                             error_stream))
386     return;
387 
388   // Failed to load some modules, so emit the error stream as a diagnostic.
389   if (!error_stream.Empty()) {
390     // The error stream already contains several Clang diagnostics that might
391     // be either errors or warnings, so just print them all as one remark
392     // diagnostic to prevent that the message starts with "error: error:".
393     diagnostic_manager.PutString(eDiagnosticSeverityRemark,
394                                  error_stream.GetString());
395     return;
396   }
397 
398   diagnostic_manager.PutString(eDiagnosticSeverityError,
399                                "Unknown error while loading modules needed for "
400                                "current compilation unit.");
401 }
402 
403 ClangExpressionSourceCode::WrapKind ClangUserExpression::GetWrapKind() const {
404   assert(m_options.GetExecutionPolicy() != eExecutionPolicyTopLevel &&
405          "Top level expressions aren't wrapped.");
406   using Kind = ClangExpressionSourceCode::WrapKind;
407   if (m_in_cplusplus_method) {
408     if (m_in_static_method)
409       return Kind::CppStaticMemberFunction;
410     return Kind::CppMemberFunction;
411   } else if (m_in_objectivec_method) {
412     if (m_in_static_method)
413       return Kind::ObjCStaticMethod;
414     return Kind::ObjCInstanceMethod;
415   }
416   // Not in any kind of 'special' function, so just wrap it in a normal C
417   // function.
418   return Kind::Function;
419 }
420 
421 void ClangUserExpression::CreateSourceCode(
422     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
423     std::vector<std::string> modules_to_import, bool for_completion) {
424 
425   std::string prefix = m_expr_prefix;
426 
427   if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
428     m_transformed_text = m_expr_text;
429   } else {
430     m_source_code.reset(ClangExpressionSourceCode::CreateWrapped(
431         m_filename, prefix, m_expr_text, GetWrapKind()));
432 
433     if (!m_source_code->GetText(m_transformed_text, exe_ctx, !m_ctx_obj,
434                                 for_completion, modules_to_import)) {
435       diagnostic_manager.PutString(eDiagnosticSeverityError,
436                                    "couldn't construct expression body");
437       return;
438     }
439 
440     // Find and store the start position of the original code inside the
441     // transformed code. We need this later for the code completion.
442     std::size_t original_start;
443     std::size_t original_end;
444     bool found_bounds = m_source_code->GetOriginalBodyBounds(
445         m_transformed_text, original_start, original_end);
446     if (found_bounds)
447       m_user_expression_start_pos = original_start;
448   }
449 }
450 
451 static bool SupportsCxxModuleImport(lldb::LanguageType language) {
452   switch (language) {
453   case lldb::eLanguageTypeC_plus_plus:
454   case lldb::eLanguageTypeC_plus_plus_03:
455   case lldb::eLanguageTypeC_plus_plus_11:
456   case lldb::eLanguageTypeC_plus_plus_14:
457   case lldb::eLanguageTypeObjC_plus_plus:
458     return true;
459   default:
460     return false;
461   }
462 }
463 
464 /// Utility method that puts a message into the expression log and
465 /// returns an invalid module configuration.
466 static CppModuleConfiguration LogConfigError(const std::string &msg) {
467   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
468   LLDB_LOG(log, "[C++ module config] {0}", msg);
469   return CppModuleConfiguration();
470 }
471 
472 CppModuleConfiguration GetModuleConfig(lldb::LanguageType language,
473                                        ExecutionContext &exe_ctx) {
474   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
475 
476   // Don't do anything if this is not a C++ module configuration.
477   if (!SupportsCxxModuleImport(language))
478     return LogConfigError("Language doesn't support C++ modules");
479 
480   Target *target = exe_ctx.GetTargetPtr();
481   if (!target)
482     return LogConfigError("No target");
483 
484   StackFrame *frame = exe_ctx.GetFramePtr();
485   if (!frame)
486     return LogConfigError("No frame");
487 
488   Block *block = frame->GetFrameBlock();
489   if (!block)
490     return LogConfigError("No block");
491 
492   SymbolContext sc;
493   block->CalculateSymbolContext(&sc);
494   if (!sc.comp_unit)
495     return LogConfigError("Couldn't calculate symbol context");
496 
497   // Build a list of files we need to analyze to build the configuration.
498   FileSpecList files;
499   for (const FileSpec &f : sc.comp_unit->GetSupportFiles())
500     files.AppendIfUnique(f);
501   // We also need to look at external modules in the case of -gmodules as they
502   // contain the support files for libc++ and the C library.
503   llvm::DenseSet<SymbolFile *> visited_symbol_files;
504   sc.comp_unit->ForEachExternalModule(
505       visited_symbol_files, [&files](Module &module) {
506         for (std::size_t i = 0; i < module.GetNumCompileUnits(); ++i) {
507           const FileSpecList &support_files =
508               module.GetCompileUnitAtIndex(i)->GetSupportFiles();
509           for (const FileSpec &f : support_files) {
510             files.AppendIfUnique(f);
511           }
512         }
513         return false;
514       });
515 
516   LLDB_LOG(log, "[C++ module config] Found {0} support files to analyze",
517            files.GetSize());
518   if (log && log->GetVerbose()) {
519     for (const FileSpec &f : files)
520       LLDB_LOGV(log, "[C++ module config] Analyzing support file: {0}",
521                 f.GetPath());
522   }
523 
524   // Try to create a configuration from the files. If there is no valid
525   // configuration possible with the files, this just returns an invalid
526   // configuration.
527   return CppModuleConfiguration(files);
528 }
529 
530 bool ClangUserExpression::PrepareForParsing(
531     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
532     bool for_completion) {
533   InstallContext(exe_ctx);
534 
535   if (!SetupPersistentState(diagnostic_manager, exe_ctx))
536     return false;
537 
538   Status err;
539   ScanContext(exe_ctx, err);
540 
541   if (!err.Success()) {
542     diagnostic_manager.PutString(eDiagnosticSeverityWarning, err.AsCString());
543   }
544 
545   ////////////////////////////////////
546   // Generate the expression
547   //
548 
549   ApplyObjcCastHack(m_expr_text);
550 
551   SetupDeclVendor(exe_ctx, m_target, diagnostic_manager);
552 
553   m_filename = m_clang_state->GetNextExprFileName();
554 
555   if (m_target->GetImportStdModule() == eImportStdModuleTrue)
556     SetupCppModuleImports(exe_ctx);
557 
558   CreateSourceCode(diagnostic_manager, exe_ctx, m_imported_cpp_modules,
559                    for_completion);
560   return true;
561 }
562 
563 bool ClangUserExpression::TryParse(
564     DiagnosticManager &diagnostic_manager, ExecutionContextScope *exe_scope,
565     ExecutionContext &exe_ctx, lldb_private::ExecutionPolicy execution_policy,
566     bool keep_result_in_memory, bool generate_debug_info) {
567   m_materializer_up = std::make_unique<Materializer>();
568 
569   ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory);
570 
571   auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); });
572 
573   if (!DeclMap()->WillParse(exe_ctx, GetMaterializer())) {
574     diagnostic_manager.PutString(
575         eDiagnosticSeverityError,
576         "current process state is unsuitable for expression parsing");
577     return false;
578   }
579 
580   if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
581     DeclMap()->SetLookupsEnabled(true);
582   }
583 
584   m_parser = std::make_unique<ClangExpressionParser>(
585       exe_scope, *this, generate_debug_info, m_include_directories, m_filename);
586 
587   unsigned num_errors = m_parser->Parse(diagnostic_manager);
588 
589   // Check here for FixItHints.  If there are any try to apply the fixits and
590   // set the fixed text in m_fixed_text before returning an error.
591   if (num_errors) {
592     if (diagnostic_manager.HasFixIts()) {
593       if (m_parser->RewriteExpression(diagnostic_manager)) {
594         size_t fixed_start;
595         size_t fixed_end;
596         m_fixed_text = diagnostic_manager.GetFixedExpression();
597         // Retrieve the original expression in case we don't have a top level
598         // expression (which has no surrounding source code).
599         if (m_source_code && m_source_code->GetOriginalBodyBounds(
600                                  m_fixed_text, fixed_start, fixed_end))
601           m_fixed_text =
602               m_fixed_text.substr(fixed_start, fixed_end - fixed_start);
603       }
604     }
605     return false;
606   }
607 
608   //////////////////////////////////////////////////////////////////////////////
609   // Prepare the output of the parser for execution, evaluating it statically
610   // if possible
611   //
612 
613   {
614     Status jit_error = m_parser->PrepareForExecution(
615         m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
616         m_can_interpret, execution_policy);
617 
618     if (!jit_error.Success()) {
619       const char *error_cstr = jit_error.AsCString();
620       if (error_cstr && error_cstr[0])
621         diagnostic_manager.PutString(eDiagnosticSeverityError, error_cstr);
622       else
623         diagnostic_manager.PutString(eDiagnosticSeverityError,
624                                      "expression can't be interpreted or run");
625       return false;
626     }
627   }
628   return true;
629 }
630 
631 void ClangUserExpression::SetupCppModuleImports(ExecutionContext &exe_ctx) {
632   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
633 
634   CppModuleConfiguration module_config = GetModuleConfig(m_language, exe_ctx);
635   m_imported_cpp_modules = module_config.GetImportedModules();
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(),
640                             m_imported_cpp_modules.end()));
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 
646 static bool shouldRetryWithCppModule(Target &target, ExecutionPolicy exe_policy) {
647   // Top-level expression don't yet support importing C++ modules.
648   if (exe_policy == ExecutionPolicy::eExecutionPolicyTopLevel)
649     return false;
650   return target.GetImportStdModule() == eImportStdModuleFallback;
651 }
652 
653 bool ClangUserExpression::Parse(DiagnosticManager &diagnostic_manager,
654                                 ExecutionContext &exe_ctx,
655                                 lldb_private::ExecutionPolicy execution_policy,
656                                 bool keep_result_in_memory,
657                                 bool generate_debug_info) {
658   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
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(eDiagnosticSeverityError, "invalid target");
673     return false;
674   }
675 
676   //////////////////////////
677   // Parse the expression
678   //
679 
680   Process *process = exe_ctx.GetProcessPtr();
681   ExecutionContextScope *exe_scope = process;
682 
683   if (!exe_scope)
684     exe_scope = exe_ctx.GetTargetPtr();
685 
686   bool parse_success = TryParse(diagnostic_manager, exe_scope, exe_ctx,
687                                 execution_policy, keep_result_in_memory,
688                                 generate_debug_info);
689   // If the expression failed to parse, check if retrying parsing with a loaded
690   // C++ module is possible.
691   if (!parse_success && shouldRetryWithCppModule(*target, execution_policy)) {
692     // Load the loaded C++ modules.
693     SetupCppModuleImports(exe_ctx);
694     // If we did load any modules, then retry parsing.
695     if (!m_imported_cpp_modules.empty()) {
696       // The module imports are injected into the source code wrapper,
697       // so recreate those.
698       CreateSourceCode(diagnostic_manager, exe_ctx, m_imported_cpp_modules,
699                        /*for_completion*/ false);
700       // Clear the error diagnostics from the previous parse attempt.
701       diagnostic_manager.Clear();
702       parse_success = TryParse(diagnostic_manager, exe_scope, exe_ctx,
703                                execution_policy, keep_result_in_memory,
704                                generate_debug_info);
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 
727   if (m_execution_unit_sp) {
728     bool register_execution_unit = false;
729 
730     if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
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 =
744               exe_ctx.GetTargetPtr()->GetPersistentExpressionStateForLanguage(
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.GetFilename() = 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.
785 static 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 
807 bool ClangUserExpression::Complete(ExecutionContext &exe_ctx,
808                                    CompletionRequest &request,
809                                    unsigned complete_pos) {
810   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
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(
834         eDiagnosticSeverityError,
835         "current process state is unsuitable for expression parsing");
836 
837     return false;
838   }
839 
840   if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
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;
861   if (m_user_expression_start_pos.hasValue())
862     AbsPosToLineColumnPos(*m_user_expression_start_pos, m_transformed_text,
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 
875 bool ClangUserExpression::AddArguments(ExecutionContext &exe_ctx,
876                                        std::vector<lldb::addr_t> &args,
877                                        lldb::addr_t struct_address,
878                                        DiagnosticManager &diagnostic_manager) {
879   lldb::addr_t object_ptr = LLDB_INVALID_ADDRESS;
880   lldb::addr_t cmd_ptr = LLDB_INVALID_ADDRESS;
881 
882   if (m_needs_object_ptr) {
883     lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
884     if (!frame_sp)
885       return true;
886 
887     ConstString object_name;
888 
889     if (m_in_cplusplus_method) {
890       object_name.SetCString("this");
891     } else if (m_in_objectivec_method) {
892       object_name.SetCString("self");
893     } else {
894       diagnostic_manager.PutString(
895           eDiagnosticSeverityError,
896           "need object pointer but don't know the language");
897       return false;
898     }
899 
900     Status object_ptr_error;
901 
902     if (m_ctx_obj) {
903       AddressType address_type;
904       object_ptr = m_ctx_obj->GetAddressOf(false, &address_type);
905       if (object_ptr == LLDB_INVALID_ADDRESS ||
906           address_type != eAddressTypeLoad)
907         object_ptr_error.SetErrorString("Can't get context object's "
908                                         "debuggee address");
909     } else
910       object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error);
911 
912     if (!object_ptr_error.Success()) {
913       exe_ctx.GetTargetRef().GetDebugger().GetAsyncOutputStream()->Printf(
914           "warning: `%s' is not accessible (substituting 0)\n",
915           object_name.AsCString());
916       object_ptr = 0;
917     }
918 
919     if (m_in_objectivec_method) {
920       ConstString cmd_name("_cmd");
921 
922       cmd_ptr = GetObjectPointer(frame_sp, cmd_name, object_ptr_error);
923 
924       if (!object_ptr_error.Success()) {
925         diagnostic_manager.Printf(
926             eDiagnosticSeverityWarning,
927             "couldn't get cmd pointer (substituting NULL): %s",
928             object_ptr_error.AsCString());
929         cmd_ptr = 0;
930       }
931     }
932 
933     args.push_back(object_ptr);
934 
935     if (m_in_objectivec_method)
936       args.push_back(cmd_ptr);
937 
938     args.push_back(struct_address);
939   } else {
940     args.push_back(struct_address);
941   }
942   return true;
943 }
944 
945 lldb::ExpressionVariableSP ClangUserExpression::GetResultAfterDematerialization(
946     ExecutionContextScope *exe_scope) {
947   return m_result_delegate.GetVariable();
948 }
949 
950 void ClangUserExpression::ClangUserExpressionHelper::ResetDeclMap(
951     ExecutionContext &exe_ctx,
952     Materializer::PersistentVariableDelegate &delegate,
953     bool keep_result_in_memory,
954     ValueObject *ctx_obj) {
955   std::shared_ptr<ClangASTImporter> ast_importer;
956   auto *state = exe_ctx.GetTargetSP()->GetPersistentExpressionStateForLanguage(
957       lldb::eLanguageTypeC);
958   if (state) {
959     auto *persistent_vars = llvm::cast<ClangPersistentVariables>(state);
960     ast_importer = persistent_vars->GetClangASTImporter();
961   }
962   m_expr_decl_map_up = std::make_unique<ClangExpressionDeclMap>(
963       keep_result_in_memory, &delegate, exe_ctx.GetTargetSP(), ast_importer,
964       ctx_obj);
965 }
966 
967 clang::ASTConsumer *
968 ClangUserExpression::ClangUserExpressionHelper::ASTTransformer(
969     clang::ASTConsumer *passthrough) {
970   m_result_synthesizer_up = std::make_unique<ASTResultSynthesizer>(
971       passthrough, m_top_level, m_target);
972 
973   return m_result_synthesizer_up.get();
974 }
975 
976 void ClangUserExpression::ClangUserExpressionHelper::CommitPersistentDecls() {
977   if (m_result_synthesizer_up) {
978     m_result_synthesizer_up->CommitPersistentDecls();
979   }
980 }
981 
982 ConstString ClangUserExpression::ResultDelegate::GetName() {
983   return m_persistent_state->GetNextPersistentVariableName(false);
984 }
985 
986 void ClangUserExpression::ResultDelegate::DidDematerialize(
987     lldb::ExpressionVariableSP &variable) {
988   m_variable = variable;
989 }
990 
991 void ClangUserExpression::ResultDelegate::RegisterPersistentState(
992     PersistentExpressionState *persistent_state) {
993   m_persistent_state = persistent_state;
994 }
995 
996 lldb::ExpressionVariableSP &ClangUserExpression::ResultDelegate::GetVariable() {
997   return m_variable;
998 }
999