blob: f42955df07aa32d97707a281b942e366d5e5d10d [file] [log] [blame]
Sean Callanan79763a42011-05-23 21:40:23 +00001//===-- ClangUserExpression.cpp ---------------------------------*- C++ -*-===//
Sean Callanan1a8d4092010-08-27 01:01:44 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Sean Callanan1a8d4092010-08-27 01:01:44 +000010#include <stdio.h>
11#if HAVE_SYS_TYPES_H
Kate Stoneb9c1b512016-09-06 20:57:50 +000012#include <sys/types.h>
Sean Callanan1a8d4092010-08-27 01:01:44 +000013#endif
14
Sean Callanan1a8d4092010-08-27 01:01:44 +000015#include <cstdlib>
Sean Callanan1a8d4092010-08-27 01:01:44 +000016#include <map>
Kate Stoneb9c1b512016-09-06 20:57:50 +000017#include <string>
Sean Callanan1a8d4092010-08-27 01:01:44 +000018
Sean Callanan4dbb2712015-09-25 20:35:58 +000019#include "ClangUserExpression.h"
20
21#include "ASTResultSynthesizer.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000022#include "ClangDiagnostic.h"
Sean Callanan4dbb2712015-09-25 20:35:58 +000023#include "ClangExpressionDeclMap.h"
24#include "ClangExpressionParser.h"
25#include "ClangModulesDeclVendor.h"
26#include "ClangPersistentVariables.h"
27
Sean Callananbda7ef82016-06-22 17:32:17 +000028#include "lldb/Core/Debugger.h"
Greg Clayton23f8c952014-03-24 23:10:19 +000029#include "lldb/Core/Module.h"
Greg Claytonc4e411f2011-01-18 19:36:39 +000030#include "lldb/Core/StreamFile.h"
Greg Claytonb71f3842010-10-05 03:13:51 +000031#include "lldb/Core/ValueObjectConstResult.h"
Sean Callanan9bc83842011-09-26 18:45:31 +000032#include "lldb/Expression/ExpressionSourceCode.h"
Sean Callanan14b1bae2013-04-16 23:25:35 +000033#include "lldb/Expression/IRExecutionUnit.h"
Sean Callanan1582ee62013-04-18 22:06:33 +000034#include "lldb/Expression/IRInterpreter.h"
Sean Callanan96d27302013-04-11 00:09:05 +000035#include "lldb/Expression/Materializer.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000036#include "lldb/Host/HostInfo.h"
Greg Clayton1f746072012-08-29 21:13:06 +000037#include "lldb/Symbol/Block.h"
Jim Ingham5fdeed42012-10-30 23:35:54 +000038#include "lldb/Symbol/ClangASTContext.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000039#include "lldb/Symbol/ClangExternalASTSourceCommon.h"
Jim Ingham5fdeed42012-10-30 23:35:54 +000040#include "lldb/Symbol/Function.h"
Greg Clayton23f8c952014-03-24 23:10:19 +000041#include "lldb/Symbol/ObjectFile.h"
42#include "lldb/Symbol/SymbolVendor.h"
Jim Ingham5fdeed42012-10-30 23:35:54 +000043#include "lldb/Symbol/Type.h"
Sean Callananfc55f5d2010-09-21 00:44:12 +000044#include "lldb/Symbol/VariableList.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000045#include "lldb/Target/ExecutionContext.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000046#include "lldb/Target/Process.h"
Jason Molendab57e4a12013-11-04 09:33:30 +000047#include "lldb/Target/StackFrame.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000048#include "lldb/Target/Target.h"
Jim Inghamf48169b2010-11-30 02:22:11 +000049#include "lldb/Target/ThreadPlan.h"
50#include "lldb/Target/ThreadPlanCallUserExpression.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000051#include "lldb/Utility/ConstString.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000052#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000053#include "lldb/Utility/StreamString.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000054
Sean Callanan72e49402011-08-05 23:43:37 +000055#include "clang/AST/DeclCXX.h"
56#include "clang/AST/DeclObjC.h"
57
Sean Callanan1a8d4092010-08-27 01:01:44 +000058using namespace lldb_private;
59
Kate Stoneb9c1b512016-09-06 20:57:50 +000060ClangUserExpression::ClangUserExpression(
Zachary Turnerc5d7df92016-11-08 04:52:16 +000061 ExecutionContextScope &exe_scope, llvm::StringRef expr,
62 llvm::StringRef prefix, lldb::LanguageType language,
63 ResultType desired_type, const EvaluateExpressionOptions &options)
64 : LLVMUserExpression(exe_scope, expr, prefix, language, desired_type,
Kate Stoneb9c1b512016-09-06 20:57:50 +000065 options),
66 m_type_system_helper(*m_target_wp.lock().get(),
67 options.GetExecutionPolicy() ==
Adrian Prantl5435f782018-04-30 23:59:15 +000068 eExecutionPolicyTopLevel),
69 m_result_delegate(exe_scope.CalculateTarget()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000070 switch (m_language) {
71 case lldb::eLanguageTypeC_plus_plus:
72 m_allow_cxx = true;
73 break;
74 case lldb::eLanguageTypeObjC:
75 m_allow_objc = true;
76 break;
77 case lldb::eLanguageTypeObjC_plus_plus:
78 default:
79 m_allow_cxx = true;
80 m_allow_objc = true;
81 break;
82 }
Sean Callanan1a8d4092010-08-27 01:01:44 +000083}
84
Kate Stoneb9c1b512016-09-06 20:57:50 +000085ClangUserExpression::~ClangUserExpression() {}
Sean Callanan1a8d4092010-08-27 01:01:44 +000086
Zachary Turner97206d52017-05-12 04:51:55 +000087void ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Status &err) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan70385082012-12-01 00:08:33 +000089
Kate Stoneb9c1b512016-09-06 20:57:50 +000090 if (log)
91 log->Printf("ClangUserExpression::ScanContext()");
92
93 m_target = exe_ctx.GetTargetPtr();
94
95 if (!(m_allow_cxx || m_allow_objc)) {
Sean Callanan70385082012-12-01 00:08:33 +000096 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +000097 log->Printf(" [CUE::SC] Settings inhibit C++ and Objective-C");
98 return;
99 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000100
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101 StackFrame *frame = exe_ctx.GetFramePtr();
102 if (frame == NULL) {
103 if (log)
104 log->Printf(" [CUE::SC] Null stack frame");
105 return;
106 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000107
Kate Stoneb9c1b512016-09-06 20:57:50 +0000108 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
109 lldb::eSymbolContextBlock);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000110
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111 if (!sym_ctx.function) {
112 if (log)
113 log->Printf(" [CUE::SC] Null function");
114 return;
115 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000116
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 // Find the block that defines the function represented by "sym_ctx"
118 Block *function_block = sym_ctx.GetFunctionBlock();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000119
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120 if (!function_block) {
121 if (log)
122 log->Printf(" [CUE::SC] Null function block");
123 return;
124 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000125
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126 CompilerDeclContext decl_context = function_block->GetDeclContext();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000127
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128 if (!decl_context) {
129 if (log)
130 log->Printf(" [CUE::SC] Null decl context");
131 return;
132 }
Greg Clayton685c88c2012-07-14 00:53:55 +0000133
Kate Stoneb9c1b512016-09-06 20:57:50 +0000134 if (clang::CXXMethodDecl *method_decl =
135 ClangASTContext::DeclContextGetAsCXXMethodDecl(decl_context)) {
136 if (m_allow_cxx && method_decl->isInstance()) {
137 if (m_enforce_valid_object) {
138 lldb::VariableListSP variable_list_sp(
139 function_block->GetBlockVariableList(true));
Greg Clayton685c88c2012-07-14 00:53:55 +0000140
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 const char *thisErrorString = "Stopped in a C++ method, but 'this' "
142 "isn't available; pretending we are in a "
143 "generic context";
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000144
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145 if (!variable_list_sp) {
146 err.SetErrorString(thisErrorString);
147 return;
Sean Callanan3670ba52010-12-01 21:35:54 +0000148 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149
150 lldb::VariableSP this_var_sp(
151 variable_list_sp->FindVariable(ConstString("this")));
152
153 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
154 !this_var_sp->LocationIsValidForFrame(frame)) {
155 err.SetErrorString(thisErrorString);
156 return;
157 }
158 }
159
160 m_in_cplusplus_method = true;
161 m_needs_object_ptr = true;
Sean Callanan3670ba52010-12-01 21:35:54 +0000162 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000163 } else if (clang::ObjCMethodDecl *method_decl =
164 ClangASTContext::DeclContextGetAsObjCMethodDecl(
165 decl_context)) {
166 if (m_allow_objc) {
167 if (m_enforce_valid_object) {
168 lldb::VariableListSP variable_list_sp(
169 function_block->GetBlockVariableList(true));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000170
Kate Stoneb9c1b512016-09-06 20:57:50 +0000171 const char *selfErrorString = "Stopped in an Objective-C method, but "
172 "'self' isn't available; pretending we "
173 "are in a generic context";
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000174
Kate Stoneb9c1b512016-09-06 20:57:50 +0000175 if (!variable_list_sp) {
176 err.SetErrorString(selfErrorString);
177 return;
178 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000179
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180 lldb::VariableSP self_variable_sp =
181 variable_list_sp->FindVariable(ConstString("self"));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000182
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
184 !self_variable_sp->LocationIsValidForFrame(frame)) {
185 err.SetErrorString(selfErrorString);
186 return;
187 }
188 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000189
Kate Stoneb9c1b512016-09-06 20:57:50 +0000190 m_in_objectivec_method = true;
191 m_needs_object_ptr = true;
192
193 if (!method_decl->isInstanceMethod())
194 m_in_static_method = true;
195 }
196 } else if (clang::FunctionDecl *function_decl =
197 ClangASTContext::DeclContextGetAsFunctionDecl(decl_context)) {
198 // We might also have a function that said in the debug information that it
Adrian Prantl05097242018-04-30 16:49:04 +0000199 // captured an object pointer. The best way to deal with getting to the
200 // ivars at present is by pretending that this is a method of a class in
201 // whatever runtime the debug info says the object pointer belongs to. Do
202 // that here.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203
204 ClangASTMetadata *metadata =
205 ClangASTContext::DeclContextGetMetaData(decl_context, function_decl);
206 if (metadata && metadata->HasObjectPtr()) {
207 lldb::LanguageType language = metadata->GetObjectPtrLanguage();
208 if (language == lldb::eLanguageTypeC_plus_plus) {
209 if (m_enforce_valid_object) {
210 lldb::VariableListSP variable_list_sp(
211 function_block->GetBlockVariableList(true));
212
213 const char *thisErrorString = "Stopped in a context claiming to "
214 "capture a C++ object pointer, but "
215 "'this' isn't available; pretending we "
216 "are in a generic context";
217
218 if (!variable_list_sp) {
219 err.SetErrorString(thisErrorString);
220 return;
221 }
222
223 lldb::VariableSP this_var_sp(
224 variable_list_sp->FindVariable(ConstString("this")));
225
226 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
227 !this_var_sp->LocationIsValidForFrame(frame)) {
228 err.SetErrorString(thisErrorString);
229 return;
230 }
231 }
232
233 m_in_cplusplus_method = true;
234 m_needs_object_ptr = true;
235 } else if (language == lldb::eLanguageTypeObjC) {
236 if (m_enforce_valid_object) {
237 lldb::VariableListSP variable_list_sp(
238 function_block->GetBlockVariableList(true));
239
240 const char *selfErrorString =
241 "Stopped in a context claiming to capture an Objective-C object "
242 "pointer, but 'self' isn't available; pretending we are in a "
243 "generic context";
244
245 if (!variable_list_sp) {
246 err.SetErrorString(selfErrorString);
247 return;
248 }
249
250 lldb::VariableSP self_variable_sp =
251 variable_list_sp->FindVariable(ConstString("self"));
252
253 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
254 !self_variable_sp->LocationIsValidForFrame(frame)) {
255 err.SetErrorString(selfErrorString);
256 return;
257 }
258
259 Type *self_type = self_variable_sp->GetType();
260
261 if (!self_type) {
262 err.SetErrorString(selfErrorString);
263 return;
264 }
265
266 CompilerType self_clang_type = self_type->GetForwardCompilerType();
267
268 if (!self_clang_type) {
269 err.SetErrorString(selfErrorString);
270 return;
271 }
272
273 if (ClangASTContext::IsObjCClassType(self_clang_type)) {
274 return;
275 } else if (ClangASTContext::IsObjCObjectPointerType(
276 self_clang_type)) {
Dawn Perchik53f34c82015-07-01 00:54:02 +0000277 m_in_objectivec_method = true;
Sean Callanan9bc83842011-09-26 18:45:31 +0000278 m_needs_object_ptr = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000279 } else {
280 err.SetErrorString(selfErrorString);
281 return;
282 }
283 } else {
284 m_in_objectivec_method = true;
285 m_needs_object_ptr = true;
Sean Callanan9bc83842011-09-26 18:45:31 +0000286 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000287 }
Sean Callanan3670ba52010-12-01 21:35:54 +0000288 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000289 }
Sean Callananfc55f5d2010-09-21 00:44:12 +0000290}
291
Adrian Prantl05097242018-04-30 16:49:04 +0000292// This is a really nasty hack, meant to fix Objective-C expressions of the
293// form (int)[myArray count]. Right now, because the type information for
294// count is not available, [myArray count] returns id, which can't be directly
295// cast to int without causing a clang error.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000296static void ApplyObjcCastHack(std::string &expr) {
Sean Callanancf5498f2010-10-22 23:25:16 +0000297#define OBJC_CAST_HACK_FROM "(int)["
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298#define OBJC_CAST_HACK_TO "(int)(long long)["
Sean Callanancf5498f2010-10-22 23:25:16 +0000299
Kate Stoneb9c1b512016-09-06 20:57:50 +0000300 size_t from_offset;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000301
Kate Stoneb9c1b512016-09-06 20:57:50 +0000302 while ((from_offset = expr.find(OBJC_CAST_HACK_FROM)) != expr.npos)
303 expr.replace(from_offset, sizeof(OBJC_CAST_HACK_FROM) - 1,
304 OBJC_CAST_HACK_TO);
Sean Callanancf5498f2010-10-22 23:25:16 +0000305
306#undef OBJC_CAST_HACK_TO
307#undef OBJC_CAST_HACK_FROM
308}
309
Raphael Isemann12468902018-06-19 21:25:59 +0000310namespace {
311// Utility guard that calls a callback when going out of scope.
312class OnExit {
313public:
314 typedef std::function<void(void)> Callback;
315
316 OnExit(Callback const &callback) : m_callback(callback) {}
317
318 ~OnExit() { m_callback(); }
319
320private:
321 Callback m_callback;
322};
323} // namespace
324
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000325bool ClangUserExpression::SetupPersistentState(DiagnosticManager &diagnostic_manager,
326 ExecutionContext &exe_ctx) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327 if (Target *target = exe_ctx.GetTargetPtr()) {
328 if (PersistentExpressionState *persistent_state =
329 target->GetPersistentExpressionStateForLanguage(
330 lldb::eLanguageTypeC)) {
331 m_result_delegate.RegisterPersistentState(persistent_state);
332 } else {
Zachary Turnere2411fa2016-11-12 19:12:56 +0000333 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000334 eDiagnosticSeverityError,
335 "couldn't start parsing (no persistent data)");
336 return false;
Sean Callanan9fda9d22015-10-03 09:09:01 +0000337 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338 } else {
Zachary Turnere2411fa2016-11-12 19:12:56 +0000339 diagnostic_manager.PutString(eDiagnosticSeverityError,
340 "error: couldn't start parsing (no target)");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 return false;
342 }
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000343 return true;
344}
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000346static void SetupDeclVendor(ExecutionContext &exe_ctx, Target *target) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347 if (ClangModulesDeclVendor *decl_vendor =
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000348 target->GetClangModulesDeclVendor()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 const ClangModulesDeclVendor::ModuleVector &hand_imported_modules =
350 llvm::cast<ClangPersistentVariables>(
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000351 target->GetPersistentExpressionStateForLanguage(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 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
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000360 if (target->GetEnableAutoImportClangModules()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 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 }
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000377}
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378
Raphael Isemanndababf72018-09-27 10:12:54 +0000379void ClangUserExpression::UpdateLanguageForExpr(
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000380 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) {
Raphael Isemanndababf72018-09-27 10:12:54 +0000381 m_expr_lang = lldb::LanguageType::eLanguageTypeUnknown;
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000382
383 std::string prefix = m_expr_prefix;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384
385 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
386 m_transformed_text = m_expr_text;
387 } else {
388 std::unique_ptr<ExpressionSourceCode> source_code(
389 ExpressionSourceCode::CreateWrapped(prefix.c_str(),
390 m_expr_text.c_str()));
391
392 if (m_in_cplusplus_method)
Raphael Isemanndababf72018-09-27 10:12:54 +0000393 m_expr_lang = lldb::eLanguageTypeC_plus_plus;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 else if (m_in_objectivec_method)
Raphael Isemanndababf72018-09-27 10:12:54 +0000395 m_expr_lang = lldb::eLanguageTypeObjC;
Sean Callanan9fda9d22015-10-03 09:09:01 +0000396 else
Raphael Isemanndababf72018-09-27 10:12:54 +0000397 m_expr_lang = lldb::eLanguageTypeC;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398
Raphael Isemanndababf72018-09-27 10:12:54 +0000399 if (!source_code->GetText(m_transformed_text, m_expr_lang,
400 m_in_static_method, exe_ctx)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +0000401 diagnostic_manager.PutString(eDiagnosticSeverityError,
402 "couldn't construct expression body");
Raphael Isemanndababf72018-09-27 10:12:54 +0000403 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 }
Raphael Isemann74829732018-08-30 17:29:37 +0000405
406 // Find and store the start position of the original code inside the
407 // transformed code. We need this later for the code completion.
408 std::size_t original_start;
409 std::size_t original_end;
410 bool found_bounds = source_code->GetOriginalBodyBounds(
Raphael Isemanndababf72018-09-27 10:12:54 +0000411 m_transformed_text, m_expr_lang, original_start, original_end);
Raphael Isemann74829732018-08-30 17:29:37 +0000412 if (found_bounds) {
413 m_user_expression_start_pos = original_start;
414 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 }
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000416}
417
418bool ClangUserExpression::PrepareForParsing(
419 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) {
420 InstallContext(exe_ctx);
421
422 if (!SetupPersistentState(diagnostic_manager, exe_ctx))
423 return false;
424
425 Status err;
426 ScanContext(exe_ctx, err);
427
428 if (!err.Success()) {
429 diagnostic_manager.PutString(eDiagnosticSeverityWarning, err.AsCString());
430 }
431
432 ////////////////////////////////////
433 // Generate the expression
434 //
435
436 ApplyObjcCastHack(m_expr_text);
437
438 SetupDeclVendor(exe_ctx, m_target);
Raphael Isemanndababf72018-09-27 10:12:54 +0000439
440 UpdateLanguageForExpr(diagnostic_manager, exe_ctx);
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000441 return true;
442}
443
444bool ClangUserExpression::Parse(DiagnosticManager &diagnostic_manager,
445 ExecutionContext &exe_ctx,
446 lldb_private::ExecutionPolicy execution_policy,
447 bool keep_result_in_memory,
448 bool generate_debug_info) {
449 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
450
451 if (!PrepareForParsing(diagnostic_manager, exe_ctx))
452 return false;
453
Kate Stoneb9c1b512016-09-06 20:57:50 +0000454 if (log)
455 log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str());
456
457 ////////////////////////////////////
458 // Set up the target and compiler
459 //
460
461 Target *target = exe_ctx.GetTargetPtr();
462
463 if (!target) {
Zachary Turnere2411fa2016-11-12 19:12:56 +0000464 diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid target");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000465 return false;
466 }
467
468 //////////////////////////
469 // Parse the expression
470 //
471
472 m_materializer_ap.reset(new Materializer());
473
474 ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory);
475
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476 OnExit on_exit([this]() { ResetDeclMap(); });
477
478 if (!DeclMap()->WillParse(exe_ctx, m_materializer_ap.get())) {
Zachary Turnere2411fa2016-11-12 19:12:56 +0000479 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000480 eDiagnosticSeverityError,
481 "current process state is unsuitable for expression parsing");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482 return false;
483 }
484
485 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
486 DeclMap()->SetLookupsEnabled(true);
487 }
488
489 Process *process = exe_ctx.GetProcessPtr();
490 ExecutionContextScope *exe_scope = process;
491
492 if (!exe_scope)
493 exe_scope = exe_ctx.GetTargetPtr();
494
495 // We use a shared pointer here so we can use the original parser - if it
Adrian Prantl05097242018-04-30 16:49:04 +0000496 // succeeds or the rewrite parser we might make if it fails. But the
497 // parser_sp will never be empty.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000498
499 ClangExpressionParser parser(exe_scope, *this, generate_debug_info);
500
501 unsigned num_errors = parser.Parse(diagnostic_manager);
502
503 // Check here for FixItHints. If there are any try to apply the fixits and
Adrian Prantl05097242018-04-30 16:49:04 +0000504 // set the fixed text in m_fixed_text before returning an error.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505 if (num_errors) {
506 if (diagnostic_manager.HasFixIts()) {
507 if (parser.RewriteExpression(diagnostic_manager)) {
508 size_t fixed_start;
509 size_t fixed_end;
510 const std::string &fixed_expression =
511 diagnostic_manager.GetFixedExpression();
512 if (ExpressionSourceCode::GetOriginalBodyBounds(
Raphael Isemanndababf72018-09-27 10:12:54 +0000513 fixed_expression, m_expr_lang, fixed_start, fixed_end))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000514 m_fixed_text =
515 fixed_expression.substr(fixed_start, fixed_end - fixed_start);
516 }
Sean Callanan9fda9d22015-10-03 09:09:01 +0000517 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000518 return false;
519 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000520
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 //////////////////////////////////////////////////////////////////////////////////////////
Adrian Prantl05097242018-04-30 16:49:04 +0000522 // Prepare the output of the parser for execution, evaluating it statically
523 // if possible
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524 //
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000525
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526 {
Zachary Turner97206d52017-05-12 04:51:55 +0000527 Status jit_error = parser.PrepareForExecution(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
529 m_can_interpret, execution_policy);
Sean Callananfc55f5d2010-09-21 00:44:12 +0000530
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531 if (!jit_error.Success()) {
532 const char *error_cstr = jit_error.AsCString();
533 if (error_cstr && error_cstr[0])
Zachary Turnere2411fa2016-11-12 19:12:56 +0000534 diagnostic_manager.PutString(eDiagnosticSeverityError, error_cstr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000535 else
Zachary Turnere2411fa2016-11-12 19:12:56 +0000536 diagnostic_manager.PutString(eDiagnosticSeverityError,
537 "expression can't be interpreted or run");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538 return false;
539 }
540 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000541
Kate Stoneb9c1b512016-09-06 20:57:50 +0000542 if (exe_ctx.GetProcessPtr() && execution_policy == eExecutionPolicyTopLevel) {
Zachary Turner97206d52017-05-12 04:51:55 +0000543 Status static_init_error =
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 parser.RunStaticInitializers(m_execution_unit_sp, exe_ctx);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000545
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546 if (!static_init_error.Success()) {
547 const char *error_cstr = static_init_error.AsCString();
548 if (error_cstr && error_cstr[0])
549 diagnostic_manager.Printf(eDiagnosticSeverityError,
550 "couldn't run static initializers: %s\n",
551 error_cstr);
552 else
Zachary Turnere2411fa2016-11-12 19:12:56 +0000553 diagnostic_manager.PutString(eDiagnosticSeverityError,
554 "couldn't run static initializers\n");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 return false;
556 }
557 }
558
559 if (m_execution_unit_sp) {
560 bool register_execution_unit = false;
561
562 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
563 register_execution_unit = true;
Sean Callananb9951192011-08-01 18:18:33 +0000564 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000565
Adrian Prantl05097242018-04-30 16:49:04 +0000566 // If there is more than one external function in the execution unit, it
567 // needs to keep living even if it's not top level, because the result
568 // could refer to that function.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569
570 if (m_execution_unit_sp->GetJittedFunctions().size() > 1) {
571 register_execution_unit = true;
Sean Callanan00294b32016-03-22 21:05:51 +0000572 }
573
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 if (register_execution_unit) {
575 llvm::cast<PersistentExpressionState>(
576 exe_ctx.GetTargetPtr()->GetPersistentExpressionStateForLanguage(
577 m_language))
578 ->RegisterExecutionUnit(m_execution_unit_sp);
Sean Callanan1a8d4092010-08-27 01:01:44 +0000579 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000580 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000581
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 if (generate_debug_info) {
583 lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000584
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585 if (jit_module_sp) {
586 ConstString const_func_name(FunctionName());
587 FileSpec jit_file;
588 jit_file.GetFilename() = const_func_name;
589 jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
590 m_jit_module_wp = jit_module_sp;
591 target->GetImages().Append(jit_module_sp);
Sean Callanan00294b32016-03-22 21:05:51 +0000592 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000593 }
Sean Callanan00294b32016-03-22 21:05:51 +0000594
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595 if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS)
596 m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
597 return true;
Sean Callanan1a8d4092010-08-27 01:01:44 +0000598}
599
Raphael Isemann74829732018-08-30 17:29:37 +0000600//------------------------------------------------------------------
601/// Converts an absolute position inside a given code string into
602/// a column/line pair.
603///
604/// @param[in] abs_pos
605/// A absolute position in the code string that we want to convert
606/// to a column/line pair.
607///
608/// @param[in] code
609/// A multi-line string usually representing source code.
610///
611/// @param[out] line
612/// The line in the code that contains the given absolute position.
613/// The first line in the string is indexed as 1.
614///
615/// @param[out] column
616/// The column in the line that contains the absolute position.
617/// The first character in a line is indexed as 0.
618//------------------------------------------------------------------
Raphael Isemannbfc5ef62018-09-22 13:33:08 +0000619static void AbsPosToLineColumnPos(size_t abs_pos, llvm::StringRef code,
Raphael Isemann74829732018-08-30 17:29:37 +0000620 unsigned &line, unsigned &column) {
621 // Reset to code position to beginning of the file.
622 line = 0;
623 column = 0;
624
625 assert(abs_pos <= code.size() && "Absolute position outside code string?");
626
627 // We have to walk up to the position and count lines/columns.
628 for (std::size_t i = 0; i < abs_pos; ++i) {
629 // If we hit a line break, we go back to column 0 and enter a new line.
630 // We only handle \n because that's what we internally use to make new
631 // lines for our temporary code strings.
632 if (code[i] == '\n') {
633 ++line;
634 column = 0;
635 continue;
636 }
637 ++column;
638 }
639}
640
641bool ClangUserExpression::Complete(ExecutionContext &exe_ctx,
Raphael Isemannc11a7802018-08-30 21:26:32 +0000642 CompletionRequest &request,
643 unsigned complete_pos) {
Raphael Isemann74829732018-08-30 17:29:37 +0000644 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
645
646 // We don't want any visible feedback when completing an expression. Mostly
647 // because the results we get from an incomplete invocation are probably not
648 // correct.
649 DiagnosticManager diagnostic_manager;
650
651 if (!PrepareForParsing(diagnostic_manager, exe_ctx))
652 return false;
653
Raphael Isemann74829732018-08-30 17:29:37 +0000654 if (log)
655 log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str());
656
657 //////////////////////////
658 // Parse the expression
659 //
660
661 m_materializer_ap.reset(new Materializer());
662
663 ResetDeclMap(exe_ctx, m_result_delegate, /*keep result in memory*/ true);
664
665 OnExit on_exit([this]() { ResetDeclMap(); });
666
667 if (!DeclMap()->WillParse(exe_ctx, m_materializer_ap.get())) {
668 diagnostic_manager.PutString(
669 eDiagnosticSeverityError,
670 "current process state is unsuitable for expression parsing");
671
672 return false;
673 }
674
675 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
676 DeclMap()->SetLookupsEnabled(true);
677 }
678
679 Process *process = exe_ctx.GetProcessPtr();
680 ExecutionContextScope *exe_scope = process;
681
682 if (!exe_scope)
683 exe_scope = exe_ctx.GetTargetPtr();
684
685 ClangExpressionParser parser(exe_scope, *this, false);
686
687 // We have to find the source code location where the user text is inside
688 // the transformed expression code. When creating the transformed text, we
689 // already stored the absolute position in the m_transformed_text string. The
690 // only thing left to do is to transform it into the line:column format that
691 // Clang expects.
692
693 // The line and column of the user expression inside the transformed source
694 // code.
695 unsigned user_expr_line, user_expr_column;
696 if (m_user_expression_start_pos.hasValue())
697 AbsPosToLineColumnPos(*m_user_expression_start_pos, m_transformed_text,
698 user_expr_line, user_expr_column);
699 else
700 return false;
701
702 // The actual column where we have to complete is the start column of the
703 // user expression + the offset inside the user code that we were given.
704 const unsigned completion_column = user_expr_column + complete_pos;
Raphael Isemannc11a7802018-08-30 21:26:32 +0000705 parser.Complete(request, user_expr_line, completion_column, complete_pos);
Raphael Isemann74829732018-08-30 17:29:37 +0000706
707 return true;
708}
709
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710bool ClangUserExpression::AddArguments(ExecutionContext &exe_ctx,
711 std::vector<lldb::addr_t> &args,
712 lldb::addr_t struct_address,
713 DiagnosticManager &diagnostic_manager) {
714 lldb::addr_t object_ptr = LLDB_INVALID_ADDRESS;
715 lldb::addr_t cmd_ptr = LLDB_INVALID_ADDRESS;
Sean Callanan579e70c2016-03-19 00:03:59 +0000716
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717 if (m_needs_object_ptr) {
718 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
719 if (!frame_sp)
720 return true;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000721
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722 ConstString object_name;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000723
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724 if (m_in_cplusplus_method) {
725 object_name.SetCString("this");
726 } else if (m_in_objectivec_method) {
727 object_name.SetCString("self");
728 } else {
Zachary Turnere2411fa2016-11-12 19:12:56 +0000729 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 eDiagnosticSeverityError,
731 "need object pointer but don't know the language");
732 return false;
Jim Ingham51148e92015-11-05 00:24:18 +0000733 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000734
Zachary Turner97206d52017-05-12 04:51:55 +0000735 Status object_ptr_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000736
737 object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error);
738
739 if (!object_ptr_error.Success()) {
740 exe_ctx.GetTargetRef().GetDebugger().GetAsyncOutputStream()->Printf(
Jason Molenda599558e2017-02-21 05:09:26 +0000741 "warning: `%s' is not accessible (substituting 0)\n",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000742 object_name.AsCString());
743 object_ptr = 0;
Jim Ingham36f3b362010-10-14 23:45:03 +0000744 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000745
746 if (m_in_objectivec_method) {
747 ConstString cmd_name("_cmd");
748
749 cmd_ptr = GetObjectPointer(frame_sp, cmd_name, object_ptr_error);
750
751 if (!object_ptr_error.Success()) {
752 diagnostic_manager.Printf(
753 eDiagnosticSeverityWarning,
754 "couldn't get cmd pointer (substituting NULL): %s",
755 object_ptr_error.AsCString());
756 cmd_ptr = 0;
757 }
758 }
759
760 args.push_back(object_ptr);
761
762 if (m_in_objectivec_method)
763 args.push_back(cmd_ptr);
764
765 args.push_back(struct_address);
766 } else {
767 args.push_back(struct_address);
768 }
769 return true;
Jim Ingham36f3b362010-10-14 23:45:03 +0000770}
771
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772lldb::ExpressionVariableSP ClangUserExpression::GetResultAfterDematerialization(
773 ExecutionContextScope *exe_scope) {
774 return m_result_delegate.GetVariable();
Sean Callanan9fda9d22015-10-03 09:09:01 +0000775}
776
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777void ClangUserExpression::ClangUserExpressionHelper::ResetDeclMap(
778 ExecutionContext &exe_ctx,
779 Materializer::PersistentVariableDelegate &delegate,
780 bool keep_result_in_memory) {
781 m_expr_decl_map_up.reset(
782 new ClangExpressionDeclMap(keep_result_in_memory, &delegate, exe_ctx));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000783}
Jim Ingham36f3b362010-10-14 23:45:03 +0000784
Jim Ingham151c0322015-09-15 21:13:50 +0000785clang::ASTConsumer *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786ClangUserExpression::ClangUserExpressionHelper::ASTTransformer(
787 clang::ASTConsumer *passthrough) {
788 m_result_synthesizer_up.reset(
789 new ASTResultSynthesizer(passthrough, m_top_level, m_target));
Sean Callananc673a6e2010-12-07 10:00:20 +0000790
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791 return m_result_synthesizer_up.get();
Sean Callanan1a8d4092010-08-27 01:01:44 +0000792}
793
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794void ClangUserExpression::ClangUserExpressionHelper::CommitPersistentDecls() {
795 if (m_result_synthesizer_up.get()) {
796 m_result_synthesizer_up->CommitPersistentDecls();
797 }
Sean Callanan00294b32016-03-22 21:05:51 +0000798}
799
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800ConstString ClangUserExpression::ResultDelegate::GetName() {
Adrian Prantl03219f72018-04-30 23:59:17 +0000801 auto prefix = m_persistent_state->GetPersistentVariablePrefix();
802 return m_persistent_state->GetNextPersistentVariableName(*m_target_sp,
803 prefix);
Sean Callanan9fda9d22015-10-03 09:09:01 +0000804}
805
Kate Stoneb9c1b512016-09-06 20:57:50 +0000806void ClangUserExpression::ResultDelegate::DidDematerialize(
807 lldb::ExpressionVariableSP &variable) {
808 m_variable = variable;
Sean Callanan9fda9d22015-10-03 09:09:01 +0000809}
810
Kate Stoneb9c1b512016-09-06 20:57:50 +0000811void ClangUserExpression::ResultDelegate::RegisterPersistentState(
812 PersistentExpressionState *persistent_state) {
813 m_persistent_state = persistent_state;
Sean Callanan9fda9d22015-10-03 09:09:01 +0000814}
815
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816lldb::ExpressionVariableSP &ClangUserExpression::ResultDelegate::GetVariable() {
817 return m_variable;
Sean Callanan9fda9d22015-10-03 09:09:01 +0000818}