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