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 && 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                  TypeSystemClang::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                  TypeSystemClang::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         TypeSystemClang::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 (TypeSystemClang::IsObjCClassType(self_clang_type)) {
296             return;
297           } else if (TypeSystemClang::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                             DiagnosticManager &diagnostic_manager) {
352   ClangModulesDeclVendor *decl_vendor = target->GetClangModulesDeclVendor();
353   if (!decl_vendor)
354     return;
355 
356   if (!target->GetEnableAutoImportClangModules())
357     return;
358 
359   auto *persistent_state = llvm::cast<ClangPersistentVariables>(
360       target->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC));
361   if (!persistent_state)
362     return;
363 
364   StackFrame *frame = exe_ctx.GetFramePtr();
365   if (!frame)
366     return;
367 
368   Block *block = frame->GetFrameBlock();
369   if (!block)
370     return;
371   SymbolContext sc;
372 
373   block->CalculateSymbolContext(&sc);
374 
375   if (!sc.comp_unit)
376     return;
377   StreamString error_stream;
378 
379   ClangModulesDeclVendor::ModuleVector modules_for_macros =
380       persistent_state->GetHandLoadedClangModules();
381   if (decl_vendor->AddModulesForCompileUnit(*sc.comp_unit, modules_for_macros,
382                                             error_stream))
383     return;
384 
385   // Failed to load some modules, so emit the error stream as a diagnostic.
386   if (!error_stream.Empty()) {
387     // The error stream already contains several Clang diagnostics that might
388     // be either errors or warnings, so just print them all as one remark
389     // diagnostic to prevent that the message starts with "error: error:".
390     diagnostic_manager.PutString(eDiagnosticSeverityRemark,
391                                  error_stream.GetString());
392     return;
393   }
394 
395   diagnostic_manager.PutString(eDiagnosticSeverityError,
396                                "Unknown error while loading modules needed for "
397                                "current compilation unit.");
398 }
399 
400 void ClangUserExpression::UpdateLanguageForExpr() {
401   m_expr_lang = lldb::LanguageType::eLanguageTypeUnknown;
402   if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel)
403     return;
404   if (m_in_cplusplus_method)
405     m_expr_lang = lldb::eLanguageTypeC_plus_plus;
406   else if (m_in_objectivec_method)
407     m_expr_lang = lldb::eLanguageTypeObjC;
408   else
409     m_expr_lang = lldb::eLanguageTypeC;
410 }
411 
412 void ClangUserExpression::CreateSourceCode(
413     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
414     std::vector<std::string> modules_to_import, bool for_completion) {
415 
416   m_filename = m_clang_state->GetNextExprFileName();
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(ClangExpressionSourceCode::CreateWrapped(
423         m_filename, prefix.c_str(), m_expr_text.c_str()));
424 
425     if (!m_source_code->GetText(m_transformed_text, m_expr_lang,
426                                 m_in_static_method, exe_ctx, !m_ctx_obj,
427                                 for_completion, modules_to_import)) {
428       diagnostic_manager.PutString(eDiagnosticSeverityError,
429                                    "couldn't construct expression body");
430       return;
431     }
432 
433     // Find and store the start position of the original code inside the
434     // transformed code. We need this later for the code completion.
435     std::size_t original_start;
436     std::size_t original_end;
437     bool found_bounds = m_source_code->GetOriginalBodyBounds(
438         m_transformed_text, m_expr_lang, original_start, original_end);
439     if (found_bounds)
440       m_user_expression_start_pos = original_start;
441   }
442 }
443 
444 static bool SupportsCxxModuleImport(lldb::LanguageType language) {
445   switch (language) {
446   case lldb::eLanguageTypeC_plus_plus:
447   case lldb::eLanguageTypeC_plus_plus_03:
448   case lldb::eLanguageTypeC_plus_plus_11:
449   case lldb::eLanguageTypeC_plus_plus_14:
450   case lldb::eLanguageTypeObjC_plus_plus:
451     return true;
452   default:
453     return false;
454   }
455 }
456 
457 /// Utility method that puts a message into the expression log and
458 /// returns an invalid module configuration.
459 static CppModuleConfiguration LogConfigError(const std::string &msg) {
460   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
461   LLDB_LOG(log, "[C++ module config] {0}", msg);
462   return CppModuleConfiguration();
463 }
464 
465 CppModuleConfiguration GetModuleConfig(lldb::LanguageType language,
466                                        ExecutionContext &exe_ctx) {
467   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
468 
469   // Don't do anything if this is not a C++ module configuration.
470   if (!SupportsCxxModuleImport(language))
471     return LogConfigError("Language doesn't support C++ modules");
472 
473   Target *target = exe_ctx.GetTargetPtr();
474   if (!target)
475     return LogConfigError("No target");
476 
477   if (!target->GetEnableImportStdModule())
478     return LogConfigError("Importing std module not enabled in settings");
479 
480   StackFrame *frame = exe_ctx.GetFramePtr();
481   if (!frame)
482     return LogConfigError("No frame");
483 
484   Block *block = frame->GetFrameBlock();
485   if (!block)
486     return LogConfigError("No block");
487 
488   SymbolContext sc;
489   block->CalculateSymbolContext(&sc);
490   if (!sc.comp_unit)
491     return LogConfigError("Couldn't calculate symbol context");
492 
493   // Build a list of files we need to analyze to build the configuration.
494   FileSpecList files;
495   for (const FileSpec &f : sc.comp_unit->GetSupportFiles())
496     files.AppendIfUnique(f);
497   // We also need to look at external modules in the case of -gmodules as they
498   // contain the support files for libc++ and the C library.
499   llvm::DenseSet<SymbolFile *> visited_symbol_files;
500   sc.comp_unit->ForEachExternalModule(
501       visited_symbol_files, [&files](Module &module) {
502         for (std::size_t i = 0; i < module.GetNumCompileUnits(); ++i) {
503           const FileSpecList &support_files =
504               module.GetCompileUnitAtIndex(i)->GetSupportFiles();
505           for (const FileSpec &f : support_files) {
506             files.AppendIfUnique(f);
507           }
508         }
509         return false;
510       });
511 
512   LLDB_LOG(log, "[C++ module config] Found {0} support files to analyze",
513            files.GetSize());
514   if (log && log->GetVerbose()) {
515     for (const FileSpec &f : files)
516       LLDB_LOGV(log, "[C++ module config] Analyzing support file: {0}",
517                 f.GetPath());
518   }
519 
520   // Try to create a configuration from the files. If there is no valid
521   // configuration possible with the files, this just returns an invalid
522   // configuration.
523   return CppModuleConfiguration(files);
524 }
525 
526 bool ClangUserExpression::PrepareForParsing(
527     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
528     bool for_completion) {
529   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
530 
531   InstallContext(exe_ctx);
532 
533   if (!SetupPersistentState(diagnostic_manager, exe_ctx))
534     return false;
535 
536   Status err;
537   ScanContext(exe_ctx, err);
538 
539   if (!err.Success()) {
540     diagnostic_manager.PutString(eDiagnosticSeverityWarning, err.AsCString());
541   }
542 
543   ////////////////////////////////////
544   // Generate the expression
545   //
546 
547   ApplyObjcCastHack(m_expr_text);
548 
549   SetupDeclVendor(exe_ctx, m_target, diagnostic_manager);
550 
551   CppModuleConfiguration module_config = GetModuleConfig(m_language, exe_ctx);
552   llvm::ArrayRef<std::string> imported_modules =
553       module_config.GetImportedModules();
554   m_imported_cpp_modules = !imported_modules.empty();
555   m_include_directories = module_config.GetIncludeDirs();
556 
557   LLDB_LOG(log, "List of imported modules in expression: {0}",
558            llvm::make_range(imported_modules.begin(), imported_modules.end()));
559   LLDB_LOG(log, "List of include directories gathered for modules: {0}",
560            llvm::make_range(m_include_directories.begin(),
561                             m_include_directories.end()));
562 
563   UpdateLanguageForExpr();
564   CreateSourceCode(diagnostic_manager, exe_ctx, imported_modules,
565                    for_completion);
566   return true;
567 }
568 
569 bool ClangUserExpression::Parse(DiagnosticManager &diagnostic_manager,
570                                 ExecutionContext &exe_ctx,
571                                 lldb_private::ExecutionPolicy execution_policy,
572                                 bool keep_result_in_memory,
573                                 bool generate_debug_info) {
574   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
575 
576   if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ false))
577     return false;
578 
579   LLDB_LOGF(log, "Parsing the following code:\n%s", m_transformed_text.c_str());
580 
581   ////////////////////////////////////
582   // Set up the target and compiler
583   //
584 
585   Target *target = exe_ctx.GetTargetPtr();
586 
587   if (!target) {
588     diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid target");
589     return false;
590   }
591 
592   //////////////////////////
593   // Parse the expression
594   //
595 
596   m_materializer_up.reset(new Materializer());
597 
598   ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory);
599 
600   auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); });
601 
602   if (!DeclMap()->WillParse(exe_ctx, GetMaterializer())) {
603     diagnostic_manager.PutString(
604         eDiagnosticSeverityError,
605         "current process state is unsuitable for expression parsing");
606     return false;
607   }
608 
609   if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
610     DeclMap()->SetLookupsEnabled(true);
611   }
612 
613   Process *process = exe_ctx.GetProcessPtr();
614   ExecutionContextScope *exe_scope = process;
615 
616   if (!exe_scope)
617     exe_scope = exe_ctx.GetTargetPtr();
618 
619   // We use a shared pointer here so we can use the original parser - if it
620   // succeeds or the rewrite parser we might make if it fails.  But the
621   // parser_sp will never be empty.
622 
623   ClangExpressionParser parser(exe_scope, *this, generate_debug_info,
624                                m_include_directories, m_filename);
625 
626   unsigned num_errors = parser.Parse(diagnostic_manager);
627 
628   // Check here for FixItHints.  If there are any try to apply the fixits and
629   // set the fixed text in m_fixed_text before returning an error.
630   if (num_errors) {
631     if (diagnostic_manager.HasFixIts()) {
632       if (parser.RewriteExpression(diagnostic_manager)) {
633         size_t fixed_start;
634         size_t fixed_end;
635         m_fixed_text = diagnostic_manager.GetFixedExpression();
636         // Retrieve the original expression in case we don't have a top level
637         // expression (which has no surrounding source code).
638         if (m_source_code &&
639             m_source_code->GetOriginalBodyBounds(m_fixed_text, m_expr_lang,
640                                                  fixed_start, fixed_end))
641           m_fixed_text =
642               m_fixed_text.substr(fixed_start, fixed_end - fixed_start);
643       }
644     }
645     return false;
646   }
647 
648   //////////////////////////////////////////////////////////////////////////////
649   // Prepare the output of the parser for execution, evaluating it statically
650   // if possible
651   //
652 
653   {
654     Status jit_error = parser.PrepareForExecution(
655         m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
656         m_can_interpret, execution_policy);
657 
658     if (!jit_error.Success()) {
659       const char *error_cstr = jit_error.AsCString();
660       if (error_cstr && error_cstr[0])
661         diagnostic_manager.PutString(eDiagnosticSeverityError, error_cstr);
662       else
663         diagnostic_manager.PutString(eDiagnosticSeverityError,
664                                      "expression can't be interpreted or run");
665       return false;
666     }
667   }
668 
669   if (exe_ctx.GetProcessPtr() && execution_policy == eExecutionPolicyTopLevel) {
670     Status static_init_error =
671         parser.RunStaticInitializers(m_execution_unit_sp, exe_ctx);
672 
673     if (!static_init_error.Success()) {
674       const char *error_cstr = static_init_error.AsCString();
675       if (error_cstr && error_cstr[0])
676         diagnostic_manager.Printf(eDiagnosticSeverityError,
677                                   "%s\n",
678                                   error_cstr);
679       else
680         diagnostic_manager.PutString(eDiagnosticSeverityError,
681                                      "couldn't run static initializers\n");
682       return false;
683     }
684   }
685 
686   if (m_execution_unit_sp) {
687     bool register_execution_unit = false;
688 
689     if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
690       register_execution_unit = true;
691     }
692 
693     // If there is more than one external function in the execution unit, it
694     // needs to keep living even if it's not top level, because the result
695     // could refer to that function.
696 
697     if (m_execution_unit_sp->GetJittedFunctions().size() > 1) {
698       register_execution_unit = true;
699     }
700 
701     if (register_execution_unit) {
702       if (auto *persistent_state =
703               exe_ctx.GetTargetPtr()->GetPersistentExpressionStateForLanguage(
704                   m_language))
705         persistent_state->RegisterExecutionUnit(m_execution_unit_sp);
706     }
707   }
708 
709   if (generate_debug_info) {
710     lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
711 
712     if (jit_module_sp) {
713       ConstString const_func_name(FunctionName());
714       FileSpec jit_file;
715       jit_file.GetFilename() = const_func_name;
716       jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
717       m_jit_module_wp = jit_module_sp;
718       target->GetImages().Append(jit_module_sp);
719     }
720   }
721 
722   if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS)
723     m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
724   return true;
725 }
726 
727 /// Converts an absolute position inside a given code string into
728 /// a column/line pair.
729 ///
730 /// \param[in] abs_pos
731 ///     A absolute position in the code string that we want to convert
732 ///     to a column/line pair.
733 ///
734 /// \param[in] code
735 ///     A multi-line string usually representing source code.
736 ///
737 /// \param[out] line
738 ///     The line in the code that contains the given absolute position.
739 ///     The first line in the string is indexed as 1.
740 ///
741 /// \param[out] column
742 ///     The column in the line that contains the absolute position.
743 ///     The first character in a line is indexed as 0.
744 static void AbsPosToLineColumnPos(size_t abs_pos, llvm::StringRef code,
745                                   unsigned &line, unsigned &column) {
746   // Reset to code position to beginning of the file.
747   line = 0;
748   column = 0;
749 
750   assert(abs_pos <= code.size() && "Absolute position outside code string?");
751 
752   // We have to walk up to the position and count lines/columns.
753   for (std::size_t i = 0; i < abs_pos; ++i) {
754     // If we hit a line break, we go back to column 0 and enter a new line.
755     // We only handle \n because that's what we internally use to make new
756     // lines for our temporary code strings.
757     if (code[i] == '\n') {
758       ++line;
759       column = 0;
760       continue;
761     }
762     ++column;
763   }
764 }
765 
766 bool ClangUserExpression::Complete(ExecutionContext &exe_ctx,
767                                    CompletionRequest &request,
768                                    unsigned complete_pos) {
769   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
770 
771   // We don't want any visible feedback when completing an expression. Mostly
772   // because the results we get from an incomplete invocation are probably not
773   // correct.
774   DiagnosticManager diagnostic_manager;
775 
776   if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ true))
777     return false;
778 
779   LLDB_LOGF(log, "Parsing the following code:\n%s", m_transformed_text.c_str());
780 
781   //////////////////////////
782   // Parse the expression
783   //
784 
785   m_materializer_up.reset(new Materializer());
786 
787   ResetDeclMap(exe_ctx, m_result_delegate, /*keep result in memory*/ true);
788 
789   auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); });
790 
791   if (!DeclMap()->WillParse(exe_ctx, GetMaterializer())) {
792     diagnostic_manager.PutString(
793         eDiagnosticSeverityError,
794         "current process state is unsuitable for expression parsing");
795 
796     return false;
797   }
798 
799   if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
800     DeclMap()->SetLookupsEnabled(true);
801   }
802 
803   Process *process = exe_ctx.GetProcessPtr();
804   ExecutionContextScope *exe_scope = process;
805 
806   if (!exe_scope)
807     exe_scope = exe_ctx.GetTargetPtr();
808 
809   ClangExpressionParser parser(exe_scope, *this, false);
810 
811   // We have to find the source code location where the user text is inside
812   // the transformed expression code. When creating the transformed text, we
813   // already stored the absolute position in the m_transformed_text string. The
814   // only thing left to do is to transform it into the line:column format that
815   // Clang expects.
816 
817   // The line and column of the user expression inside the transformed source
818   // code.
819   unsigned user_expr_line, user_expr_column;
820   if (m_user_expression_start_pos.hasValue())
821     AbsPosToLineColumnPos(*m_user_expression_start_pos, m_transformed_text,
822                           user_expr_line, user_expr_column);
823   else
824     return false;
825 
826   // The actual column where we have to complete is the start column of the
827   // user expression + the offset inside the user code that we were given.
828   const unsigned completion_column = user_expr_column + complete_pos;
829   parser.Complete(request, user_expr_line, completion_column, complete_pos);
830 
831   return true;
832 }
833 
834 bool ClangUserExpression::AddArguments(ExecutionContext &exe_ctx,
835                                        std::vector<lldb::addr_t> &args,
836                                        lldb::addr_t struct_address,
837                                        DiagnosticManager &diagnostic_manager) {
838   lldb::addr_t object_ptr = LLDB_INVALID_ADDRESS;
839   lldb::addr_t cmd_ptr = LLDB_INVALID_ADDRESS;
840 
841   if (m_needs_object_ptr) {
842     lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
843     if (!frame_sp)
844       return true;
845 
846     ConstString object_name;
847 
848     if (m_in_cplusplus_method) {
849       object_name.SetCString("this");
850     } else if (m_in_objectivec_method) {
851       object_name.SetCString("self");
852     } else {
853       diagnostic_manager.PutString(
854           eDiagnosticSeverityError,
855           "need object pointer but don't know the language");
856       return false;
857     }
858 
859     Status object_ptr_error;
860 
861     if (m_ctx_obj) {
862       AddressType address_type;
863       object_ptr = m_ctx_obj->GetAddressOf(false, &address_type);
864       if (object_ptr == LLDB_INVALID_ADDRESS ||
865           address_type != eAddressTypeLoad)
866         object_ptr_error.SetErrorString("Can't get context object's "
867                                         "debuggee address");
868     } else
869       object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error);
870 
871     if (!object_ptr_error.Success()) {
872       exe_ctx.GetTargetRef().GetDebugger().GetAsyncOutputStream()->Printf(
873           "warning: `%s' is not accessible (substituting 0)\n",
874           object_name.AsCString());
875       object_ptr = 0;
876     }
877 
878     if (m_in_objectivec_method) {
879       ConstString cmd_name("_cmd");
880 
881       cmd_ptr = GetObjectPointer(frame_sp, cmd_name, object_ptr_error);
882 
883       if (!object_ptr_error.Success()) {
884         diagnostic_manager.Printf(
885             eDiagnosticSeverityWarning,
886             "couldn't get cmd pointer (substituting NULL): %s",
887             object_ptr_error.AsCString());
888         cmd_ptr = 0;
889       }
890     }
891 
892     args.push_back(object_ptr);
893 
894     if (m_in_objectivec_method)
895       args.push_back(cmd_ptr);
896 
897     args.push_back(struct_address);
898   } else {
899     args.push_back(struct_address);
900   }
901   return true;
902 }
903 
904 lldb::ExpressionVariableSP ClangUserExpression::GetResultAfterDematerialization(
905     ExecutionContextScope *exe_scope) {
906   return m_result_delegate.GetVariable();
907 }
908 
909 void ClangUserExpression::ClangUserExpressionHelper::ResetDeclMap(
910     ExecutionContext &exe_ctx,
911     Materializer::PersistentVariableDelegate &delegate,
912     bool keep_result_in_memory,
913     ValueObject *ctx_obj) {
914   std::shared_ptr<ClangASTImporter> ast_importer;
915   auto *state = exe_ctx.GetTargetSP()->GetPersistentExpressionStateForLanguage(
916       lldb::eLanguageTypeC);
917   if (state) {
918     auto *persistent_vars = llvm::cast<ClangPersistentVariables>(state);
919     ast_importer = persistent_vars->GetClangASTImporter();
920   }
921   m_expr_decl_map_up.reset(
922       new ClangExpressionDeclMap(keep_result_in_memory, &delegate,
923                                  exe_ctx.GetTargetSP(), ast_importer, ctx_obj));
924 }
925 
926 clang::ASTConsumer *
927 ClangUserExpression::ClangUserExpressionHelper::ASTTransformer(
928     clang::ASTConsumer *passthrough) {
929   m_result_synthesizer_up.reset(
930       new ASTResultSynthesizer(passthrough, m_top_level, m_target));
931 
932   return m_result_synthesizer_up.get();
933 }
934 
935 void ClangUserExpression::ClangUserExpressionHelper::CommitPersistentDecls() {
936   if (m_result_synthesizer_up) {
937     m_result_synthesizer_up->CommitPersistentDecls();
938   }
939 }
940 
941 ConstString ClangUserExpression::ResultDelegate::GetName() {
942   return m_persistent_state->GetNextPersistentVariableName(false);
943 }
944 
945 void ClangUserExpression::ResultDelegate::DidDematerialize(
946     lldb::ExpressionVariableSP &variable) {
947   m_variable = variable;
948 }
949 
950 void ClangUserExpression::ResultDelegate::RegisterPersistentState(
951     PersistentExpressionState *persistent_state) {
952   m_persistent_state = persistent_state;
953 }
954 
955 lldb::ExpressionVariableSP &ClangUserExpression::ResultDelegate::GetVariable() {
956   return m_variable;
957 }
958