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