1 //===-- ClangUserExpression.cpp ---------------------------------*- C++ -*-===//
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 "ClangDiagnostic.h"
24 #include "ClangExpressionDeclMap.h"
25 #include "ClangExpressionParser.h"
26 #include "ClangModulesDeclVendor.h"
27 #include "ClangPersistentVariables.h"
28 #include "CppModuleConfiguration.h"
29 
30 #include "lldb/Core/Debugger.h"
31 #include "lldb/Core/Module.h"
32 #include "lldb/Core/StreamFile.h"
33 #include "lldb/Core/ValueObjectConstResult.h"
34 #include "lldb/Expression/ExpressionSourceCode.h"
35 #include "lldb/Expression/IRExecutionUnit.h"
36 #include "lldb/Expression/IRInterpreter.h"
37 #include "lldb/Expression/Materializer.h"
38 #include "lldb/Host/HostInfo.h"
39 #include "lldb/Symbol/Block.h"
40 #include "lldb/Symbol/ClangASTContext.h"
41 #include "lldb/Symbol/ClangExternalASTSourceCommon.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           ClangASTContext::DeclContextGetAsCXXMethodDecl(decl_context)) {
158     if (m_allow_cxx && method_decl->isInstance()) {
159       if (m_enforce_valid_object) {
160         lldb::VariableListSP variable_list_sp(
161             function_block->GetBlockVariableList(true));
162 
163         const char *thisErrorString = "Stopped in a C++ method, but 'this' "
164                                       "isn't available; pretending we are in a "
165                                       "generic context";
166 
167         if (!variable_list_sp) {
168           err.SetErrorString(thisErrorString);
169           return;
170         }
171 
172         lldb::VariableSP this_var_sp(
173             variable_list_sp->FindVariable(ConstString("this")));
174 
175         if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
176             !this_var_sp->LocationIsValidForFrame(frame)) {
177           err.SetErrorString(thisErrorString);
178           return;
179         }
180       }
181 
182       m_in_cplusplus_method = true;
183       m_needs_object_ptr = true;
184     }
185   } else if (clang::ObjCMethodDecl *method_decl =
186                  ClangASTContext::DeclContextGetAsObjCMethodDecl(
187                      decl_context)) {
188     if (m_allow_objc) {
189       if (m_enforce_valid_object) {
190         lldb::VariableListSP variable_list_sp(
191             function_block->GetBlockVariableList(true));
192 
193         const char *selfErrorString = "Stopped in an Objective-C method, but "
194                                       "'self' isn't available; pretending we "
195                                       "are in a generic context";
196 
197         if (!variable_list_sp) {
198           err.SetErrorString(selfErrorString);
199           return;
200         }
201 
202         lldb::VariableSP self_variable_sp =
203             variable_list_sp->FindVariable(ConstString("self"));
204 
205         if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
206             !self_variable_sp->LocationIsValidForFrame(frame)) {
207           err.SetErrorString(selfErrorString);
208           return;
209         }
210       }
211 
212       m_in_objectivec_method = true;
213       m_needs_object_ptr = true;
214 
215       if (!method_decl->isInstanceMethod())
216         m_in_static_method = true;
217     }
218   } else if (clang::FunctionDecl *function_decl =
219                  ClangASTContext::DeclContextGetAsFunctionDecl(decl_context)) {
220     // We might also have a function that said in the debug information that it
221     // captured an object pointer.  The best way to deal with getting to the
222     // ivars at present is by pretending that this is a method of a class in
223     // whatever runtime the debug info says the object pointer belongs to.  Do
224     // that here.
225 
226     ClangASTMetadata *metadata =
227         ClangASTContext::DeclContextGetMetaData(decl_context, function_decl);
228     if (metadata && metadata->HasObjectPtr()) {
229       lldb::LanguageType language = metadata->GetObjectPtrLanguage();
230       if (language == lldb::eLanguageTypeC_plus_plus) {
231         if (m_enforce_valid_object) {
232           lldb::VariableListSP variable_list_sp(
233               function_block->GetBlockVariableList(true));
234 
235           const char *thisErrorString = "Stopped in a context claiming to "
236                                         "capture a C++ object pointer, but "
237                                         "'this' isn't available; pretending we "
238                                         "are in a generic context";
239 
240           if (!variable_list_sp) {
241             err.SetErrorString(thisErrorString);
242             return;
243           }
244 
245           lldb::VariableSP this_var_sp(
246               variable_list_sp->FindVariable(ConstString("this")));
247 
248           if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
249               !this_var_sp->LocationIsValidForFrame(frame)) {
250             err.SetErrorString(thisErrorString);
251             return;
252           }
253         }
254 
255         m_in_cplusplus_method = true;
256         m_needs_object_ptr = true;
257       } else if (language == lldb::eLanguageTypeObjC) {
258         if (m_enforce_valid_object) {
259           lldb::VariableListSP variable_list_sp(
260               function_block->GetBlockVariableList(true));
261 
262           const char *selfErrorString =
263               "Stopped in a context claiming to capture an Objective-C object "
264               "pointer, but 'self' isn't available; pretending we are in a "
265               "generic context";
266 
267           if (!variable_list_sp) {
268             err.SetErrorString(selfErrorString);
269             return;
270           }
271 
272           lldb::VariableSP self_variable_sp =
273               variable_list_sp->FindVariable(ConstString("self"));
274 
275           if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
276               !self_variable_sp->LocationIsValidForFrame(frame)) {
277             err.SetErrorString(selfErrorString);
278             return;
279           }
280 
281           Type *self_type = self_variable_sp->GetType();
282 
283           if (!self_type) {
284             err.SetErrorString(selfErrorString);
285             return;
286           }
287 
288           CompilerType self_clang_type = self_type->GetForwardCompilerType();
289 
290           if (!self_clang_type) {
291             err.SetErrorString(selfErrorString);
292             return;
293           }
294 
295           if (ClangASTContext::IsObjCClassType(self_clang_type)) {
296             return;
297           } else if (ClangASTContext::IsObjCObjectPointerType(
298                          self_clang_type)) {
299             m_in_objectivec_method = true;
300             m_needs_object_ptr = true;
301           } else {
302             err.SetErrorString(selfErrorString);
303             return;
304           }
305         } else {
306           m_in_objectivec_method = true;
307           m_needs_object_ptr = true;
308         }
309       }
310     }
311   }
312 }
313 
314 // This is a really nasty hack, meant to fix Objective-C expressions of the
315 // form (int)[myArray count].  Right now, because the type information for
316 // count is not available, [myArray count] returns id, which can't be directly
317 // cast to int without causing a clang error.
318 static void ApplyObjcCastHack(std::string &expr) {
319   const std::string from = "(int)[";
320   const std::string to = "(int)(long long)[";
321 
322   size_t offset;
323 
324   while ((offset = expr.find(from)) != expr.npos)
325     expr.replace(offset, from.size(), to);
326 }
327 
328 bool ClangUserExpression::SetupPersistentState(DiagnosticManager &diagnostic_manager,
329                                  ExecutionContext &exe_ctx) {
330   if (Target *target = exe_ctx.GetTargetPtr()) {
331     if (PersistentExpressionState *persistent_state =
332             target->GetPersistentExpressionStateForLanguage(
333                 lldb::eLanguageTypeC)) {
334       m_clang_state = llvm::cast<ClangPersistentVariables>(persistent_state);
335       m_result_delegate.RegisterPersistentState(persistent_state);
336     } else {
337       diagnostic_manager.PutString(
338           eDiagnosticSeverityError,
339           "couldn't start parsing (no persistent data)");
340       return false;
341     }
342   } else {
343     diagnostic_manager.PutString(eDiagnosticSeverityError,
344                                  "error: couldn't start parsing (no target)");
345     return false;
346   }
347   return true;
348 }
349 
350 static void SetupDeclVendor(ExecutionContext &exe_ctx, Target *target) {
351   if (ClangModulesDeclVendor *decl_vendor =
352           target->GetClangModulesDeclVendor()) {
353     const ClangModulesDeclVendor::ModuleVector &hand_imported_modules =
354         llvm::cast<ClangPersistentVariables>(
355             target->GetPersistentExpressionStateForLanguage(
356                 lldb::eLanguageTypeC))
357             ->GetHandLoadedClangModules();
358     ClangModulesDeclVendor::ModuleVector modules_for_macros;
359 
360     for (ClangModulesDeclVendor::ModuleID module : hand_imported_modules) {
361       modules_for_macros.push_back(module);
362     }
363 
364     if (target->GetEnableAutoImportClangModules()) {
365       if (StackFrame *frame = exe_ctx.GetFramePtr()) {
366         if (Block *block = frame->GetFrameBlock()) {
367           SymbolContext sc;
368 
369           block->CalculateSymbolContext(&sc);
370 
371           if (sc.comp_unit) {
372             StreamString error_stream;
373 
374             decl_vendor->AddModulesForCompileUnit(
375                 *sc.comp_unit, modules_for_macros, error_stream);
376           }
377         }
378       }
379     }
380   }
381 }
382 
383 void ClangUserExpression::UpdateLanguageForExpr() {
384   m_expr_lang = lldb::LanguageType::eLanguageTypeUnknown;
385   if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel)
386     return;
387   if (m_in_cplusplus_method)
388     m_expr_lang = lldb::eLanguageTypeC_plus_plus;
389   else if (m_in_objectivec_method)
390     m_expr_lang = lldb::eLanguageTypeObjC;
391   else
392     m_expr_lang = lldb::eLanguageTypeC;
393 }
394 
395 void ClangUserExpression::CreateSourceCode(
396     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
397     std::vector<std::string> modules_to_import, bool for_completion) {
398 
399   m_filename = m_clang_state->GetNextExprFileName();
400   std::string prefix = m_expr_prefix;
401 
402   if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
403     m_transformed_text = m_expr_text;
404   } else {
405     m_source_code.reset(ClangExpressionSourceCode::CreateWrapped(
406         m_filename, prefix.c_str(), m_expr_text.c_str()));
407 
408     if (!m_source_code->GetText(m_transformed_text, m_expr_lang,
409                                 m_in_static_method, exe_ctx, !m_ctx_obj,
410                                 for_completion, modules_to_import)) {
411       diagnostic_manager.PutString(eDiagnosticSeverityError,
412                                    "couldn't construct expression body");
413       return;
414     }
415 
416     // Find and store the start position of the original code inside the
417     // transformed code. We need this later for the code completion.
418     std::size_t original_start;
419     std::size_t original_end;
420     bool found_bounds = m_source_code->GetOriginalBodyBounds(
421         m_transformed_text, m_expr_lang, original_start, original_end);
422     if (found_bounds)
423       m_user_expression_start_pos = original_start;
424   }
425 }
426 
427 static bool SupportsCxxModuleImport(lldb::LanguageType language) {
428   switch (language) {
429   case lldb::eLanguageTypeC_plus_plus:
430   case lldb::eLanguageTypeC_plus_plus_03:
431   case lldb::eLanguageTypeC_plus_plus_11:
432   case lldb::eLanguageTypeC_plus_plus_14:
433   case lldb::eLanguageTypeObjC_plus_plus:
434     return true;
435   default:
436     return false;
437   }
438 }
439 
440 /// Utility method that puts a message into the expression log and
441 /// returns an invalid module configuration.
442 static CppModuleConfiguration LogConfigError(const std::string &msg) {
443   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
444   LLDB_LOG(log, "[C++ module config] {0}", msg);
445   return CppModuleConfiguration();
446 }
447 
448 CppModuleConfiguration GetModuleConfig(lldb::LanguageType language,
449                                        ExecutionContext &exe_ctx) {
450   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
451 
452   // Don't do anything if this is not a C++ module configuration.
453   if (!SupportsCxxModuleImport(language))
454     return LogConfigError("Language doesn't support C++ modules");
455 
456   Target *target = exe_ctx.GetTargetPtr();
457   if (!target)
458     return LogConfigError("No target");
459 
460   if (!target->GetEnableImportStdModule())
461     return LogConfigError("Importing std module not enabled in settings");
462 
463   StackFrame *frame = exe_ctx.GetFramePtr();
464   if (!frame)
465     return LogConfigError("No frame");
466 
467   Block *block = frame->GetFrameBlock();
468   if (!block)
469     return LogConfigError("No block");
470 
471   SymbolContext sc;
472   block->CalculateSymbolContext(&sc);
473   if (!sc.comp_unit)
474     return LogConfigError("Couldn't calculate symbol context");
475 
476   // Build a list of files we need to analyze to build the configuration.
477   FileSpecList files;
478   for (const FileSpec &f : sc.comp_unit->GetSupportFiles())
479     files.AppendIfUnique(f);
480   // We also need to look at external modules in the case of -gmodules as they
481   // contain the support files for libc++ and the C library.
482   llvm::DenseSet<SymbolFile *> visited_symbol_files;
483   sc.comp_unit->ForEachExternalModule(
484       visited_symbol_files, [&files](Module &module) {
485         for (std::size_t i = 0; i < module.GetNumCompileUnits(); ++i) {
486           const FileSpecList &support_files =
487               module.GetCompileUnitAtIndex(i)->GetSupportFiles();
488           for (const FileSpec &f : support_files) {
489             files.AppendIfUnique(f);
490           }
491         }
492         return false;
493       });
494 
495   LLDB_LOG(log, "[C++ module config] Found {0} support files to analyze",
496            files.GetSize());
497   if (log && log->GetVerbose()) {
498     for (const FileSpec &f : files)
499       LLDB_LOGV(log, "[C++ module config] Analyzing support file: {0}",
500                 f.GetPath());
501   }
502 
503   // Try to create a configuration from the files. If there is no valid
504   // configuration possible with the files, this just returns an invalid
505   // configuration.
506   return CppModuleConfiguration(files);
507 }
508 
509 bool ClangUserExpression::PrepareForParsing(
510     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
511     bool for_completion) {
512   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
513 
514   InstallContext(exe_ctx);
515 
516   if (!SetupPersistentState(diagnostic_manager, exe_ctx))
517     return false;
518 
519   Status err;
520   ScanContext(exe_ctx, err);
521 
522   if (!err.Success()) {
523     diagnostic_manager.PutString(eDiagnosticSeverityWarning, err.AsCString());
524   }
525 
526   ////////////////////////////////////
527   // Generate the expression
528   //
529 
530   ApplyObjcCastHack(m_expr_text);
531 
532   SetupDeclVendor(exe_ctx, m_target);
533 
534   CppModuleConfiguration module_config = GetModuleConfig(m_language, exe_ctx);
535   llvm::ArrayRef<std::string> imported_modules =
536       module_config.GetImportedModules();
537   m_imported_cpp_modules = !imported_modules.empty();
538   m_include_directories = module_config.GetIncludeDirs();
539 
540   LLDB_LOG(log, "List of imported modules in expression: {0}",
541            llvm::make_range(imported_modules.begin(), imported_modules.end()));
542   LLDB_LOG(log, "List of include directories gathered for modules: {0}",
543            llvm::make_range(m_include_directories.begin(),
544                             m_include_directories.end()));
545 
546   UpdateLanguageForExpr();
547   CreateSourceCode(diagnostic_manager, exe_ctx, imported_modules,
548                    for_completion);
549   return true;
550 }
551 
552 bool ClangUserExpression::Parse(DiagnosticManager &diagnostic_manager,
553                                 ExecutionContext &exe_ctx,
554                                 lldb_private::ExecutionPolicy execution_policy,
555                                 bool keep_result_in_memory,
556                                 bool generate_debug_info) {
557   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
558 
559   if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ false))
560     return false;
561 
562   LLDB_LOGF(log, "Parsing the following code:\n%s", m_transformed_text.c_str());
563 
564   ////////////////////////////////////
565   // Set up the target and compiler
566   //
567 
568   Target *target = exe_ctx.GetTargetPtr();
569 
570   if (!target) {
571     diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid target");
572     return false;
573   }
574 
575   //////////////////////////
576   // Parse the expression
577   //
578 
579   m_materializer_up.reset(new Materializer());
580 
581   ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory);
582 
583   auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); });
584 
585   if (!DeclMap()->WillParse(exe_ctx, GetMaterializer())) {
586     diagnostic_manager.PutString(
587         eDiagnosticSeverityError,
588         "current process state is unsuitable for expression parsing");
589     return false;
590   }
591 
592   if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
593     DeclMap()->SetLookupsEnabled(true);
594   }
595 
596   Process *process = exe_ctx.GetProcessPtr();
597   ExecutionContextScope *exe_scope = process;
598 
599   if (!exe_scope)
600     exe_scope = exe_ctx.GetTargetPtr();
601 
602   // We use a shared pointer here so we can use the original parser - if it
603   // succeeds or the rewrite parser we might make if it fails.  But the
604   // parser_sp will never be empty.
605 
606   ClangExpressionParser parser(exe_scope, *this, generate_debug_info,
607                                m_include_directories, m_filename);
608 
609   unsigned num_errors = parser.Parse(diagnostic_manager);
610 
611   // Check here for FixItHints.  If there are any try to apply the fixits and
612   // set the fixed text in m_fixed_text before returning an error.
613   if (num_errors) {
614     if (diagnostic_manager.HasFixIts()) {
615       if (parser.RewriteExpression(diagnostic_manager)) {
616         size_t fixed_start;
617         size_t fixed_end;
618         const std::string &fixed_expression =
619             diagnostic_manager.GetFixedExpression();
620         // Retrieve the original expression in case we don't have a top level
621         // expression (which has no surrounding source code).
622         if (m_source_code &&
623             m_source_code->GetOriginalBodyBounds(fixed_expression, m_expr_lang,
624                                                  fixed_start, fixed_end))
625           m_fixed_text =
626               fixed_expression.substr(fixed_start, fixed_end - fixed_start);
627       }
628     }
629     return false;
630   }
631 
632   //////////////////////////////////////////////////////////////////////////////
633   // Prepare the output of the parser for execution, evaluating it statically
634   // if possible
635   //
636 
637   {
638     Status jit_error = parser.PrepareForExecution(
639         m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
640         m_can_interpret, execution_policy);
641 
642     if (!jit_error.Success()) {
643       const char *error_cstr = jit_error.AsCString();
644       if (error_cstr && error_cstr[0])
645         diagnostic_manager.PutString(eDiagnosticSeverityError, error_cstr);
646       else
647         diagnostic_manager.PutString(eDiagnosticSeverityError,
648                                      "expression can't be interpreted or run");
649       return false;
650     }
651   }
652 
653   if (exe_ctx.GetProcessPtr() && execution_policy == eExecutionPolicyTopLevel) {
654     Status static_init_error =
655         parser.RunStaticInitializers(m_execution_unit_sp, exe_ctx);
656 
657     if (!static_init_error.Success()) {
658       const char *error_cstr = static_init_error.AsCString();
659       if (error_cstr && error_cstr[0])
660         diagnostic_manager.Printf(eDiagnosticSeverityError,
661                                   "couldn't run static initializers: %s\n",
662                                   error_cstr);
663       else
664         diagnostic_manager.PutString(eDiagnosticSeverityError,
665                                      "couldn't run static initializers\n");
666       return false;
667     }
668   }
669 
670   if (m_execution_unit_sp) {
671     bool register_execution_unit = false;
672 
673     if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
674       register_execution_unit = true;
675     }
676 
677     // If there is more than one external function in the execution unit, it
678     // needs to keep living even if it's not top level, because the result
679     // could refer to that function.
680 
681     if (m_execution_unit_sp->GetJittedFunctions().size() > 1) {
682       register_execution_unit = true;
683     }
684 
685     if (register_execution_unit)
686       exe_ctx.GetTargetPtr()
687           ->GetPersistentExpressionStateForLanguage(m_language)
688           ->RegisterExecutionUnit(m_execution_unit_sp);
689   }
690 
691   if (generate_debug_info) {
692     lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
693 
694     if (jit_module_sp) {
695       ConstString const_func_name(FunctionName());
696       FileSpec jit_file;
697       jit_file.GetFilename() = const_func_name;
698       jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
699       m_jit_module_wp = jit_module_sp;
700       target->GetImages().Append(jit_module_sp);
701     }
702   }
703 
704   if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS)
705     m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
706   return true;
707 }
708 
709 /// Converts an absolute position inside a given code string into
710 /// a column/line pair.
711 ///
712 /// \param[in] abs_pos
713 ///     A absolute position in the code string that we want to convert
714 ///     to a column/line pair.
715 ///
716 /// \param[in] code
717 ///     A multi-line string usually representing source code.
718 ///
719 /// \param[out] line
720 ///     The line in the code that contains the given absolute position.
721 ///     The first line in the string is indexed as 1.
722 ///
723 /// \param[out] column
724 ///     The column in the line that contains the absolute position.
725 ///     The first character in a line is indexed as 0.
726 static void AbsPosToLineColumnPos(size_t abs_pos, llvm::StringRef code,
727                                   unsigned &line, unsigned &column) {
728   // Reset to code position to beginning of the file.
729   line = 0;
730   column = 0;
731 
732   assert(abs_pos <= code.size() && "Absolute position outside code string?");
733 
734   // We have to walk up to the position and count lines/columns.
735   for (std::size_t i = 0; i < abs_pos; ++i) {
736     // If we hit a line break, we go back to column 0 and enter a new line.
737     // We only handle \n because that's what we internally use to make new
738     // lines for our temporary code strings.
739     if (code[i] == '\n') {
740       ++line;
741       column = 0;
742       continue;
743     }
744     ++column;
745   }
746 }
747 
748 bool ClangUserExpression::Complete(ExecutionContext &exe_ctx,
749                                    CompletionRequest &request,
750                                    unsigned complete_pos) {
751   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
752 
753   // We don't want any visible feedback when completing an expression. Mostly
754   // because the results we get from an incomplete invocation are probably not
755   // correct.
756   DiagnosticManager diagnostic_manager;
757 
758   if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ true))
759     return false;
760 
761   LLDB_LOGF(log, "Parsing the following code:\n%s", m_transformed_text.c_str());
762 
763   //////////////////////////
764   // Parse the expression
765   //
766 
767   m_materializer_up.reset(new Materializer());
768 
769   ResetDeclMap(exe_ctx, m_result_delegate, /*keep result in memory*/ true);
770 
771   auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); });
772 
773   if (!DeclMap()->WillParse(exe_ctx, GetMaterializer())) {
774     diagnostic_manager.PutString(
775         eDiagnosticSeverityError,
776         "current process state is unsuitable for expression parsing");
777 
778     return false;
779   }
780 
781   if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
782     DeclMap()->SetLookupsEnabled(true);
783   }
784 
785   Process *process = exe_ctx.GetProcessPtr();
786   ExecutionContextScope *exe_scope = process;
787 
788   if (!exe_scope)
789     exe_scope = exe_ctx.GetTargetPtr();
790 
791   ClangExpressionParser parser(exe_scope, *this, false);
792 
793   // We have to find the source code location where the user text is inside
794   // the transformed expression code. When creating the transformed text, we
795   // already stored the absolute position in the m_transformed_text string. The
796   // only thing left to do is to transform it into the line:column format that
797   // Clang expects.
798 
799   // The line and column of the user expression inside the transformed source
800   // code.
801   unsigned user_expr_line, user_expr_column;
802   if (m_user_expression_start_pos.hasValue())
803     AbsPosToLineColumnPos(*m_user_expression_start_pos, m_transformed_text,
804                           user_expr_line, user_expr_column);
805   else
806     return false;
807 
808   // The actual column where we have to complete is the start column of the
809   // user expression + the offset inside the user code that we were given.
810   const unsigned completion_column = user_expr_column + complete_pos;
811   parser.Complete(request, user_expr_line, completion_column, complete_pos);
812 
813   return true;
814 }
815 
816 bool ClangUserExpression::AddArguments(ExecutionContext &exe_ctx,
817                                        std::vector<lldb::addr_t> &args,
818                                        lldb::addr_t struct_address,
819                                        DiagnosticManager &diagnostic_manager) {
820   lldb::addr_t object_ptr = LLDB_INVALID_ADDRESS;
821   lldb::addr_t cmd_ptr = LLDB_INVALID_ADDRESS;
822 
823   if (m_needs_object_ptr) {
824     lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
825     if (!frame_sp)
826       return true;
827 
828     ConstString object_name;
829 
830     if (m_in_cplusplus_method) {
831       object_name.SetCString("this");
832     } else if (m_in_objectivec_method) {
833       object_name.SetCString("self");
834     } else {
835       diagnostic_manager.PutString(
836           eDiagnosticSeverityError,
837           "need object pointer but don't know the language");
838       return false;
839     }
840 
841     Status object_ptr_error;
842 
843     if (m_ctx_obj) {
844       AddressType address_type;
845       object_ptr = m_ctx_obj->GetAddressOf(false, &address_type);
846       if (object_ptr == LLDB_INVALID_ADDRESS ||
847           address_type != eAddressTypeLoad)
848         object_ptr_error.SetErrorString("Can't get context object's "
849                                         "debuggee address");
850     } else
851       object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error);
852 
853     if (!object_ptr_error.Success()) {
854       exe_ctx.GetTargetRef().GetDebugger().GetAsyncOutputStream()->Printf(
855           "warning: `%s' is not accessible (substituting 0)\n",
856           object_name.AsCString());
857       object_ptr = 0;
858     }
859 
860     if (m_in_objectivec_method) {
861       ConstString cmd_name("_cmd");
862 
863       cmd_ptr = GetObjectPointer(frame_sp, cmd_name, object_ptr_error);
864 
865       if (!object_ptr_error.Success()) {
866         diagnostic_manager.Printf(
867             eDiagnosticSeverityWarning,
868             "couldn't get cmd pointer (substituting NULL): %s",
869             object_ptr_error.AsCString());
870         cmd_ptr = 0;
871       }
872     }
873 
874     args.push_back(object_ptr);
875 
876     if (m_in_objectivec_method)
877       args.push_back(cmd_ptr);
878 
879     args.push_back(struct_address);
880   } else {
881     args.push_back(struct_address);
882   }
883   return true;
884 }
885 
886 lldb::ExpressionVariableSP ClangUserExpression::GetResultAfterDematerialization(
887     ExecutionContextScope *exe_scope) {
888   return m_result_delegate.GetVariable();
889 }
890 
891 void ClangUserExpression::ClangUserExpressionHelper::ResetDeclMap(
892     ExecutionContext &exe_ctx,
893     Materializer::PersistentVariableDelegate &delegate,
894     bool keep_result_in_memory,
895     ValueObject *ctx_obj) {
896   m_expr_decl_map_up.reset(
897       new ClangExpressionDeclMap(keep_result_in_memory, &delegate, exe_ctx,
898                                  ctx_obj));
899 }
900 
901 clang::ASTConsumer *
902 ClangUserExpression::ClangUserExpressionHelper::ASTTransformer(
903     clang::ASTConsumer *passthrough) {
904   m_result_synthesizer_up.reset(
905       new ASTResultSynthesizer(passthrough, m_top_level, m_target));
906 
907   return m_result_synthesizer_up.get();
908 }
909 
910 void ClangUserExpression::ClangUserExpressionHelper::CommitPersistentDecls() {
911   if (m_result_synthesizer_up) {
912     m_result_synthesizer_up->CommitPersistentDecls();
913   }
914 }
915 
916 ConstString ClangUserExpression::ResultDelegate::GetName() {
917   auto prefix = m_persistent_state->GetPersistentVariablePrefix();
918   return m_persistent_state->GetNextPersistentVariableName(*m_target_sp,
919                                                            prefix);
920 }
921 
922 void ClangUserExpression::ResultDelegate::DidDematerialize(
923     lldb::ExpressionVariableSP &variable) {
924   m_variable = variable;
925 }
926 
927 void ClangUserExpression::ResultDelegate::RegisterPersistentState(
928     PersistentExpressionState *persistent_state) {
929   m_persistent_state = persistent_state;
930 }
931 
932 lldb::ExpressionVariableSP &ClangUserExpression::ResultDelegate::GetVariable() {
933   return m_variable;
934 }
935