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