blob: f96723783509ff79a8e33083d5347fc2580f1e55 [file] [log] [blame]
Sean Callanan79763a42011-05-23 21:40:23 +00001//===-- ClangUserExpression.cpp ---------------------------------*- C++ -*-===//
Sean Callanan1a8d4092010-08-27 01:01:44 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Sean Callanan1a8d4092010-08-27 01:01:44 +00006//
7//===----------------------------------------------------------------------===//
8
Sean Callanan1a8d4092010-08-27 01:01:44 +00009#include <stdio.h>
10#if HAVE_SYS_TYPES_H
Kate Stoneb9c1b512016-09-06 20:57:50 +000011#include <sys/types.h>
Sean Callanan1a8d4092010-08-27 01:01:44 +000012#endif
13
Sean Callanan1a8d4092010-08-27 01:01:44 +000014#include <cstdlib>
Sean Callanan1a8d4092010-08-27 01:01:44 +000015#include <map>
Kate Stoneb9c1b512016-09-06 20:57:50 +000016#include <string>
Sean Callanan1a8d4092010-08-27 01:01:44 +000017
Sean Callanan4dbb2712015-09-25 20:35:58 +000018#include "ClangUserExpression.h"
19
20#include "ASTResultSynthesizer.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000021#include "ClangDiagnostic.h"
Sean Callanan4dbb2712015-09-25 20:35:58 +000022#include "ClangExpressionDeclMap.h"
23#include "ClangExpressionParser.h"
24#include "ClangModulesDeclVendor.h"
25#include "ClangPersistentVariables.h"
26
Sean Callananbda7ef82016-06-22 17:32:17 +000027#include "lldb/Core/Debugger.h"
Greg Clayton23f8c952014-03-24 23:10:19 +000028#include "lldb/Core/Module.h"
Greg Claytonc4e411f2011-01-18 19:36:39 +000029#include "lldb/Core/StreamFile.h"
Greg Claytonb71f3842010-10-05 03:13:51 +000030#include "lldb/Core/ValueObjectConstResult.h"
Sean Callanan9bc83842011-09-26 18:45:31 +000031#include "lldb/Expression/ExpressionSourceCode.h"
Sean Callanan14b1bae2013-04-16 23:25:35 +000032#include "lldb/Expression/IRExecutionUnit.h"
Sean Callanan1582ee62013-04-18 22:06:33 +000033#include "lldb/Expression/IRInterpreter.h"
Sean Callanan96d27302013-04-11 00:09:05 +000034#include "lldb/Expression/Materializer.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000035#include "lldb/Host/HostInfo.h"
Greg Clayton1f746072012-08-29 21:13:06 +000036#include "lldb/Symbol/Block.h"
Jim Ingham5fdeed42012-10-30 23:35:54 +000037#include "lldb/Symbol/ClangASTContext.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000038#include "lldb/Symbol/ClangExternalASTSourceCommon.h"
Jim Ingham5fdeed42012-10-30 23:35:54 +000039#include "lldb/Symbol/Function.h"
Greg Clayton23f8c952014-03-24 23:10:19 +000040#include "lldb/Symbol/ObjectFile.h"
41#include "lldb/Symbol/SymbolVendor.h"
Jim Ingham5fdeed42012-10-30 23:35:54 +000042#include "lldb/Symbol/Type.h"
Sean Callananfc55f5d2010-09-21 00:44:12 +000043#include "lldb/Symbol/VariableList.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000044#include "lldb/Target/ExecutionContext.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000045#include "lldb/Target/Process.h"
Jason Molendab57e4a12013-11-04 09:33:30 +000046#include "lldb/Target/StackFrame.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000047#include "lldb/Target/Target.h"
Jim Inghamf48169b2010-11-30 02:22:11 +000048#include "lldb/Target/ThreadPlan.h"
49#include "lldb/Target/ThreadPlanCallUserExpression.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000050#include "lldb/Utility/ConstString.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000051#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000052#include "lldb/Utility/StreamString.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000053
Sean Callanan72e49402011-08-05 23:43:37 +000054#include "clang/AST/DeclCXX.h"
55#include "clang/AST/DeclObjC.h"
56
Sean Callanan1a8d4092010-08-27 01:01:44 +000057using namespace lldb_private;
58
Kate Stoneb9c1b512016-09-06 20:57:50 +000059ClangUserExpression::ClangUserExpression(
Zachary Turnerc5d7df92016-11-08 04:52:16 +000060 ExecutionContextScope &exe_scope, llvm::StringRef expr,
61 llvm::StringRef prefix, lldb::LanguageType language,
Aleksandr Urakov40624a02019-02-05 09:14:36 +000062 ResultType desired_type, const EvaluateExpressionOptions &options,
63 ValueObject *ctx_obj)
Zachary Turnerc5d7df92016-11-08 04:52:16 +000064 : 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),
Aleksandr Urakov40624a02019-02-05 09:14:36 +000069 m_result_delegate(exe_scope.CalculateTarget()),
70 m_ctx_obj(ctx_obj) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000071 switch (m_language) {
72 case lldb::eLanguageTypeC_plus_plus:
73 m_allow_cxx = true;
74 break;
75 case lldb::eLanguageTypeObjC:
76 m_allow_objc = true;
77 break;
78 case lldb::eLanguageTypeObjC_plus_plus:
79 default:
80 m_allow_cxx = true;
81 m_allow_objc = true;
82 break;
83 }
Sean Callanan1a8d4092010-08-27 01:01:44 +000084}
85
Kate Stoneb9c1b512016-09-06 20:57:50 +000086ClangUserExpression::~ClangUserExpression() {}
Sean Callanan1a8d4092010-08-27 01:01:44 +000087
Zachary Turner97206d52017-05-12 04:51:55 +000088void ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Status &err) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000089 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan70385082012-12-01 00:08:33 +000090
Kate Stoneb9c1b512016-09-06 20:57:50 +000091 if (log)
92 log->Printf("ClangUserExpression::ScanContext()");
93
94 m_target = exe_ctx.GetTargetPtr();
95
96 if (!(m_allow_cxx || m_allow_objc)) {
Sean Callanan70385082012-12-01 00:08:33 +000097 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +000098 log->Printf(" [CUE::SC] Settings inhibit C++ and Objective-C");
99 return;
100 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000101
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102 StackFrame *frame = exe_ctx.GetFramePtr();
103 if (frame == NULL) {
104 if (log)
105 log->Printf(" [CUE::SC] Null stack frame");
106 return;
107 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000108
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
110 lldb::eSymbolContextBlock);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000111
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112 if (!sym_ctx.function) {
113 if (log)
114 log->Printf(" [CUE::SC] Null function");
115 return;
116 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000117
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118 // Find the block that defines the function represented by "sym_ctx"
119 Block *function_block = sym_ctx.GetFunctionBlock();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000120
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121 if (!function_block) {
122 if (log)
123 log->Printf(" [CUE::SC] Null function block");
124 return;
125 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000126
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127 CompilerDeclContext decl_context = function_block->GetDeclContext();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 if (!decl_context) {
130 if (log)
131 log->Printf(" [CUE::SC] Null decl context");
132 return;
133 }
Greg Clayton685c88c2012-07-14 00:53:55 +0000134
Aleksandr Urakov40624a02019-02-05 09:14:36 +0000135 if (m_ctx_obj) {
136 switch (m_ctx_obj->GetObjectRuntimeLanguage()) {
137 case lldb::eLanguageTypeC:
138 case lldb::eLanguageTypeC89:
139 case lldb::eLanguageTypeC99:
140 case lldb::eLanguageTypeC11:
141 case lldb::eLanguageTypeC_plus_plus:
142 case lldb::eLanguageTypeC_plus_plus_03:
143 case lldb::eLanguageTypeC_plus_plus_11:
144 case lldb::eLanguageTypeC_plus_plus_14:
145 m_in_cplusplus_method = true;
146 break;
147 case lldb::eLanguageTypeObjC:
148 case lldb::eLanguageTypeObjC_plus_plus:
149 m_in_objectivec_method = true;
150 break;
151 default:
152 break;
153 }
154 m_needs_object_ptr = true;
155 } else if (clang::CXXMethodDecl *method_decl =
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156 ClangASTContext::DeclContextGetAsCXXMethodDecl(decl_context)) {
157 if (m_allow_cxx && method_decl->isInstance()) {
158 if (m_enforce_valid_object) {
159 lldb::VariableListSP variable_list_sp(
160 function_block->GetBlockVariableList(true));
Greg Clayton685c88c2012-07-14 00:53:55 +0000161
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162 const char *thisErrorString = "Stopped in a C++ method, but 'this' "
163 "isn't available; pretending we are in a "
164 "generic context";
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000165
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166 if (!variable_list_sp) {
167 err.SetErrorString(thisErrorString);
168 return;
Sean Callanan3670ba52010-12-01 21:35:54 +0000169 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170
171 lldb::VariableSP this_var_sp(
172 variable_list_sp->FindVariable(ConstString("this")));
173
174 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
175 !this_var_sp->LocationIsValidForFrame(frame)) {
176 err.SetErrorString(thisErrorString);
177 return;
178 }
179 }
180
181 m_in_cplusplus_method = true;
182 m_needs_object_ptr = true;
Sean Callanan3670ba52010-12-01 21:35:54 +0000183 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184 } else if (clang::ObjCMethodDecl *method_decl =
185 ClangASTContext::DeclContextGetAsObjCMethodDecl(
186 decl_context)) {
187 if (m_allow_objc) {
188 if (m_enforce_valid_object) {
189 lldb::VariableListSP variable_list_sp(
190 function_block->GetBlockVariableList(true));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000191
Kate Stoneb9c1b512016-09-06 20:57:50 +0000192 const char *selfErrorString = "Stopped in an Objective-C method, but "
193 "'self' isn't available; pretending we "
194 "are in a generic context";
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000195
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196 if (!variable_list_sp) {
197 err.SetErrorString(selfErrorString);
198 return;
199 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000200
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201 lldb::VariableSP self_variable_sp =
202 variable_list_sp->FindVariable(ConstString("self"));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000203
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
205 !self_variable_sp->LocationIsValidForFrame(frame)) {
206 err.SetErrorString(selfErrorString);
207 return;
208 }
209 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000210
Kate Stoneb9c1b512016-09-06 20:57:50 +0000211 m_in_objectivec_method = true;
212 m_needs_object_ptr = true;
213
214 if (!method_decl->isInstanceMethod())
215 m_in_static_method = true;
216 }
217 } else if (clang::FunctionDecl *function_decl =
218 ClangASTContext::DeclContextGetAsFunctionDecl(decl_context)) {
219 // We might also have a function that said in the debug information that it
Adrian Prantl05097242018-04-30 16:49:04 +0000220 // captured an object pointer. The best way to deal with getting to the
221 // ivars at present is by pretending that this is a method of a class in
222 // whatever runtime the debug info says the object pointer belongs to. Do
223 // that here.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000224
225 ClangASTMetadata *metadata =
226 ClangASTContext::DeclContextGetMetaData(decl_context, function_decl);
227 if (metadata && metadata->HasObjectPtr()) {
228 lldb::LanguageType language = metadata->GetObjectPtrLanguage();
229 if (language == lldb::eLanguageTypeC_plus_plus) {
230 if (m_enforce_valid_object) {
231 lldb::VariableListSP variable_list_sp(
232 function_block->GetBlockVariableList(true));
233
234 const char *thisErrorString = "Stopped in a context claiming to "
235 "capture a C++ object pointer, but "
236 "'this' isn't available; pretending we "
237 "are in a generic context";
238
239 if (!variable_list_sp) {
240 err.SetErrorString(thisErrorString);
241 return;
242 }
243
244 lldb::VariableSP this_var_sp(
245 variable_list_sp->FindVariable(ConstString("this")));
246
247 if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
248 !this_var_sp->LocationIsValidForFrame(frame)) {
249 err.SetErrorString(thisErrorString);
250 return;
251 }
252 }
253
254 m_in_cplusplus_method = true;
255 m_needs_object_ptr = true;
256 } else if (language == lldb::eLanguageTypeObjC) {
257 if (m_enforce_valid_object) {
258 lldb::VariableListSP variable_list_sp(
259 function_block->GetBlockVariableList(true));
260
261 const char *selfErrorString =
262 "Stopped in a context claiming to capture an Objective-C object "
263 "pointer, but 'self' isn't available; pretending we are in a "
264 "generic context";
265
266 if (!variable_list_sp) {
267 err.SetErrorString(selfErrorString);
268 return;
269 }
270
271 lldb::VariableSP self_variable_sp =
272 variable_list_sp->FindVariable(ConstString("self"));
273
274 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
275 !self_variable_sp->LocationIsValidForFrame(frame)) {
276 err.SetErrorString(selfErrorString);
277 return;
278 }
279
280 Type *self_type = self_variable_sp->GetType();
281
282 if (!self_type) {
283 err.SetErrorString(selfErrorString);
284 return;
285 }
286
287 CompilerType self_clang_type = self_type->GetForwardCompilerType();
288
289 if (!self_clang_type) {
290 err.SetErrorString(selfErrorString);
291 return;
292 }
293
294 if (ClangASTContext::IsObjCClassType(self_clang_type)) {
295 return;
296 } else if (ClangASTContext::IsObjCObjectPointerType(
297 self_clang_type)) {
Dawn Perchik53f34c82015-07-01 00:54:02 +0000298 m_in_objectivec_method = true;
Sean Callanan9bc83842011-09-26 18:45:31 +0000299 m_needs_object_ptr = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000300 } else {
301 err.SetErrorString(selfErrorString);
302 return;
303 }
304 } else {
305 m_in_objectivec_method = true;
306 m_needs_object_ptr = true;
Sean Callanan9bc83842011-09-26 18:45:31 +0000307 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000308 }
Sean Callanan3670ba52010-12-01 21:35:54 +0000309 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000310 }
Sean Callananfc55f5d2010-09-21 00:44:12 +0000311}
312
Adrian Prantl05097242018-04-30 16:49:04 +0000313// This is a really nasty hack, meant to fix Objective-C expressions of the
314// form (int)[myArray count]. Right now, because the type information for
315// count is not available, [myArray count] returns id, which can't be directly
316// cast to int without causing a clang error.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000317static void ApplyObjcCastHack(std::string &expr) {
Sean Callanancf5498f2010-10-22 23:25:16 +0000318#define OBJC_CAST_HACK_FROM "(int)["
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319#define OBJC_CAST_HACK_TO "(int)(long long)["
Sean Callanancf5498f2010-10-22 23:25:16 +0000320
Kate Stoneb9c1b512016-09-06 20:57:50 +0000321 size_t from_offset;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000322
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 while ((from_offset = expr.find(OBJC_CAST_HACK_FROM)) != expr.npos)
324 expr.replace(from_offset, sizeof(OBJC_CAST_HACK_FROM) - 1,
325 OBJC_CAST_HACK_TO);
Sean Callanancf5498f2010-10-22 23:25:16 +0000326
327#undef OBJC_CAST_HACK_TO
328#undef OBJC_CAST_HACK_FROM
329}
330
Raphael Isemann12468902018-06-19 21:25:59 +0000331namespace {
332// Utility guard that calls a callback when going out of scope.
333class OnExit {
334public:
335 typedef std::function<void(void)> Callback;
336
337 OnExit(Callback const &callback) : m_callback(callback) {}
338
339 ~OnExit() { m_callback(); }
340
341private:
342 Callback m_callback;
343};
344} // namespace
345
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000346bool ClangUserExpression::SetupPersistentState(DiagnosticManager &diagnostic_manager,
347 ExecutionContext &exe_ctx) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348 if (Target *target = exe_ctx.GetTargetPtr()) {
349 if (PersistentExpressionState *persistent_state =
350 target->GetPersistentExpressionStateForLanguage(
351 lldb::eLanguageTypeC)) {
352 m_result_delegate.RegisterPersistentState(persistent_state);
353 } else {
Zachary Turnere2411fa2016-11-12 19:12:56 +0000354 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 eDiagnosticSeverityError,
356 "couldn't start parsing (no persistent data)");
357 return false;
Sean Callanan9fda9d22015-10-03 09:09:01 +0000358 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 } else {
Zachary Turnere2411fa2016-11-12 19:12:56 +0000360 diagnostic_manager.PutString(eDiagnosticSeverityError,
361 "error: couldn't start parsing (no target)");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 return false;
363 }
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000364 return true;
365}
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000367static void SetupDeclVendor(ExecutionContext &exe_ctx, Target *target) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000368 if (ClangModulesDeclVendor *decl_vendor =
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000369 target->GetClangModulesDeclVendor()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 const ClangModulesDeclVendor::ModuleVector &hand_imported_modules =
371 llvm::cast<ClangPersistentVariables>(
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000372 target->GetPersistentExpressionStateForLanguage(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 lldb::eLanguageTypeC))
374 ->GetHandLoadedClangModules();
375 ClangModulesDeclVendor::ModuleVector modules_for_macros;
376
377 for (ClangModulesDeclVendor::ModuleID module : hand_imported_modules) {
378 modules_for_macros.push_back(module);
379 }
380
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000381 if (target->GetEnableAutoImportClangModules()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 if (StackFrame *frame = exe_ctx.GetFramePtr()) {
383 if (Block *block = frame->GetFrameBlock()) {
384 SymbolContext sc;
385
386 block->CalculateSymbolContext(&sc);
387
388 if (sc.comp_unit) {
389 StreamString error_stream;
390
391 decl_vendor->AddModulesForCompileUnit(
392 *sc.comp_unit, modules_for_macros, error_stream);
393 }
394 }
395 }
396 }
397 }
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000398}
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399
Raphael Isemanndababf72018-09-27 10:12:54 +0000400void ClangUserExpression::UpdateLanguageForExpr(
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000401 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) {
Raphael Isemanndababf72018-09-27 10:12:54 +0000402 m_expr_lang = lldb::LanguageType::eLanguageTypeUnknown;
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000403
404 std::string prefix = m_expr_prefix;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405
406 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
407 m_transformed_text = m_expr_text;
408 } else {
409 std::unique_ptr<ExpressionSourceCode> source_code(
410 ExpressionSourceCode::CreateWrapped(prefix.c_str(),
411 m_expr_text.c_str()));
412
413 if (m_in_cplusplus_method)
Raphael Isemanndababf72018-09-27 10:12:54 +0000414 m_expr_lang = lldb::eLanguageTypeC_plus_plus;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 else if (m_in_objectivec_method)
Raphael Isemanndababf72018-09-27 10:12:54 +0000416 m_expr_lang = lldb::eLanguageTypeObjC;
Sean Callanan9fda9d22015-10-03 09:09:01 +0000417 else
Raphael Isemanndababf72018-09-27 10:12:54 +0000418 m_expr_lang = lldb::eLanguageTypeC;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419
Raphael Isemanndababf72018-09-27 10:12:54 +0000420 if (!source_code->GetText(m_transformed_text, m_expr_lang,
Aleksandr Urakov40624a02019-02-05 09:14:36 +0000421 m_in_static_method, exe_ctx,
422 !m_ctx_obj)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +0000423 diagnostic_manager.PutString(eDiagnosticSeverityError,
424 "couldn't construct expression body");
Raphael Isemanndababf72018-09-27 10:12:54 +0000425 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426 }
Raphael Isemann74829732018-08-30 17:29:37 +0000427
428 // Find and store the start position of the original code inside the
429 // transformed code. We need this later for the code completion.
430 std::size_t original_start;
431 std::size_t original_end;
432 bool found_bounds = source_code->GetOriginalBodyBounds(
Raphael Isemanndababf72018-09-27 10:12:54 +0000433 m_transformed_text, m_expr_lang, original_start, original_end);
Raphael Isemann74829732018-08-30 17:29:37 +0000434 if (found_bounds) {
435 m_user_expression_start_pos = original_start;
436 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437 }
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000438}
439
440bool ClangUserExpression::PrepareForParsing(
441 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) {
442 InstallContext(exe_ctx);
443
444 if (!SetupPersistentState(diagnostic_manager, exe_ctx))
445 return false;
446
447 Status err;
448 ScanContext(exe_ctx, err);
449
450 if (!err.Success()) {
451 diagnostic_manager.PutString(eDiagnosticSeverityWarning, err.AsCString());
452 }
453
454 ////////////////////////////////////
455 // Generate the expression
456 //
457
458 ApplyObjcCastHack(m_expr_text);
459
460 SetupDeclVendor(exe_ctx, m_target);
Raphael Isemanndababf72018-09-27 10:12:54 +0000461
462 UpdateLanguageForExpr(diagnostic_manager, exe_ctx);
Raphael Isemannba800e7d2018-07-10 22:12:39 +0000463 return true;
464}
465
466bool ClangUserExpression::Parse(DiagnosticManager &diagnostic_manager,
467 ExecutionContext &exe_ctx,
468 lldb_private::ExecutionPolicy execution_policy,
469 bool keep_result_in_memory,
470 bool generate_debug_info) {
471 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
472
473 if (!PrepareForParsing(diagnostic_manager, exe_ctx))
474 return false;
475
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476 if (log)
477 log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str());
478
479 ////////////////////////////////////
480 // Set up the target and compiler
481 //
482
483 Target *target = exe_ctx.GetTargetPtr();
484
485 if (!target) {
Zachary Turnere2411fa2016-11-12 19:12:56 +0000486 diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid target");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000487 return false;
488 }
489
490 //////////////////////////
491 // Parse the expression
492 //
493
494 m_materializer_ap.reset(new Materializer());
495
496 ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory);
497
Kate Stoneb9c1b512016-09-06 20:57:50 +0000498 OnExit on_exit([this]() { ResetDeclMap(); });
499
500 if (!DeclMap()->WillParse(exe_ctx, m_materializer_ap.get())) {
Zachary Turnere2411fa2016-11-12 19:12:56 +0000501 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000502 eDiagnosticSeverityError,
503 "current process state is unsuitable for expression parsing");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000504 return false;
505 }
506
507 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
508 DeclMap()->SetLookupsEnabled(true);
509 }
510
511 Process *process = exe_ctx.GetProcessPtr();
512 ExecutionContextScope *exe_scope = process;
513
514 if (!exe_scope)
515 exe_scope = exe_ctx.GetTargetPtr();
516
517 // We use a shared pointer here so we can use the original parser - if it
Adrian Prantl05097242018-04-30 16:49:04 +0000518 // succeeds or the rewrite parser we might make if it fails. But the
519 // parser_sp will never be empty.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520
521 ClangExpressionParser parser(exe_scope, *this, generate_debug_info);
522
523 unsigned num_errors = parser.Parse(diagnostic_manager);
524
525 // Check here for FixItHints. If there are any try to apply the fixits and
Adrian Prantl05097242018-04-30 16:49:04 +0000526 // set the fixed text in m_fixed_text before returning an error.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000527 if (num_errors) {
528 if (diagnostic_manager.HasFixIts()) {
529 if (parser.RewriteExpression(diagnostic_manager)) {
530 size_t fixed_start;
531 size_t fixed_end;
532 const std::string &fixed_expression =
533 diagnostic_manager.GetFixedExpression();
534 if (ExpressionSourceCode::GetOriginalBodyBounds(
Raphael Isemanndababf72018-09-27 10:12:54 +0000535 fixed_expression, m_expr_lang, fixed_start, fixed_end))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536 m_fixed_text =
537 fixed_expression.substr(fixed_start, fixed_end - fixed_start);
538 }
Sean Callanan9fda9d22015-10-03 09:09:01 +0000539 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540 return false;
541 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000542
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543 //////////////////////////////////////////////////////////////////////////////////////////
Adrian Prantl05097242018-04-30 16:49:04 +0000544 // Prepare the output of the parser for execution, evaluating it statically
545 // if possible
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546 //
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000547
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 {
Zachary Turner97206d52017-05-12 04:51:55 +0000549 Status jit_error = parser.PrepareForExecution(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550 m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
551 m_can_interpret, execution_policy);
Sean Callananfc55f5d2010-09-21 00:44:12 +0000552
Kate Stoneb9c1b512016-09-06 20:57:50 +0000553 if (!jit_error.Success()) {
554 const char *error_cstr = jit_error.AsCString();
555 if (error_cstr && error_cstr[0])
Zachary Turnere2411fa2016-11-12 19:12:56 +0000556 diagnostic_manager.PutString(eDiagnosticSeverityError, error_cstr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557 else
Zachary Turnere2411fa2016-11-12 19:12:56 +0000558 diagnostic_manager.PutString(eDiagnosticSeverityError,
559 "expression can't be interpreted or run");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 return false;
561 }
562 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000563
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564 if (exe_ctx.GetProcessPtr() && execution_policy == eExecutionPolicyTopLevel) {
Zachary Turner97206d52017-05-12 04:51:55 +0000565 Status static_init_error =
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566 parser.RunStaticInitializers(m_execution_unit_sp, exe_ctx);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000567
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 if (!static_init_error.Success()) {
569 const char *error_cstr = static_init_error.AsCString();
570 if (error_cstr && error_cstr[0])
571 diagnostic_manager.Printf(eDiagnosticSeverityError,
572 "couldn't run static initializers: %s\n",
573 error_cstr);
574 else
Zachary Turnere2411fa2016-11-12 19:12:56 +0000575 diagnostic_manager.PutString(eDiagnosticSeverityError,
576 "couldn't run static initializers\n");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577 return false;
578 }
579 }
580
581 if (m_execution_unit_sp) {
582 bool register_execution_unit = false;
583
584 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
585 register_execution_unit = true;
Sean Callananb9951192011-08-01 18:18:33 +0000586 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000587
Adrian Prantl05097242018-04-30 16:49:04 +0000588 // If there is more than one external function in the execution unit, it
589 // needs to keep living even if it's not top level, because the result
590 // could refer to that function.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000591
592 if (m_execution_unit_sp->GetJittedFunctions().size() > 1) {
593 register_execution_unit = true;
Sean Callanan00294b32016-03-22 21:05:51 +0000594 }
595
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596 if (register_execution_unit) {
597 llvm::cast<PersistentExpressionState>(
598 exe_ctx.GetTargetPtr()->GetPersistentExpressionStateForLanguage(
599 m_language))
600 ->RegisterExecutionUnit(m_execution_unit_sp);
Sean Callanan1a8d4092010-08-27 01:01:44 +0000601 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000602 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000603
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604 if (generate_debug_info) {
605 lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000606
Kate Stoneb9c1b512016-09-06 20:57:50 +0000607 if (jit_module_sp) {
608 ConstString const_func_name(FunctionName());
609 FileSpec jit_file;
610 jit_file.GetFilename() = const_func_name;
611 jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
612 m_jit_module_wp = jit_module_sp;
613 target->GetImages().Append(jit_module_sp);
Sean Callanan00294b32016-03-22 21:05:51 +0000614 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615 }
Sean Callanan00294b32016-03-22 21:05:51 +0000616
Kate Stoneb9c1b512016-09-06 20:57:50 +0000617 if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS)
618 m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
619 return true;
Sean Callanan1a8d4092010-08-27 01:01:44 +0000620}
621
Raphael Isemann74829732018-08-30 17:29:37 +0000622//------------------------------------------------------------------
623/// Converts an absolute position inside a given code string into
624/// a column/line pair.
625///
626/// @param[in] abs_pos
627/// A absolute position in the code string that we want to convert
628/// to a column/line pair.
629///
630/// @param[in] code
631/// A multi-line string usually representing source code.
632///
633/// @param[out] line
634/// The line in the code that contains the given absolute position.
635/// The first line in the string is indexed as 1.
636///
637/// @param[out] column
638/// The column in the line that contains the absolute position.
639/// The first character in a line is indexed as 0.
640//------------------------------------------------------------------
Raphael Isemannbfc5ef62018-09-22 13:33:08 +0000641static void AbsPosToLineColumnPos(size_t abs_pos, llvm::StringRef code,
Raphael Isemann74829732018-08-30 17:29:37 +0000642 unsigned &line, unsigned &column) {
643 // Reset to code position to beginning of the file.
644 line = 0;
645 column = 0;
646
647 assert(abs_pos <= code.size() && "Absolute position outside code string?");
648
649 // We have to walk up to the position and count lines/columns.
650 for (std::size_t i = 0; i < abs_pos; ++i) {
651 // If we hit a line break, we go back to column 0 and enter a new line.
652 // We only handle \n because that's what we internally use to make new
653 // lines for our temporary code strings.
654 if (code[i] == '\n') {
655 ++line;
656 column = 0;
657 continue;
658 }
659 ++column;
660 }
661}
662
663bool ClangUserExpression::Complete(ExecutionContext &exe_ctx,
Raphael Isemannc11a7802018-08-30 21:26:32 +0000664 CompletionRequest &request,
665 unsigned complete_pos) {
Raphael Isemann74829732018-08-30 17:29:37 +0000666 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
667
668 // We don't want any visible feedback when completing an expression. Mostly
669 // because the results we get from an incomplete invocation are probably not
670 // correct.
671 DiagnosticManager diagnostic_manager;
672
673 if (!PrepareForParsing(diagnostic_manager, exe_ctx))
674 return false;
675
Raphael Isemann74829732018-08-30 17:29:37 +0000676 if (log)
677 log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str());
678
679 //////////////////////////
680 // Parse the expression
681 //
682
683 m_materializer_ap.reset(new Materializer());
684
685 ResetDeclMap(exe_ctx, m_result_delegate, /*keep result in memory*/ true);
686
687 OnExit on_exit([this]() { ResetDeclMap(); });
688
689 if (!DeclMap()->WillParse(exe_ctx, m_materializer_ap.get())) {
690 diagnostic_manager.PutString(
691 eDiagnosticSeverityError,
692 "current process state is unsuitable for expression parsing");
693
694 return false;
695 }
696
697 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
698 DeclMap()->SetLookupsEnabled(true);
699 }
700
701 Process *process = exe_ctx.GetProcessPtr();
702 ExecutionContextScope *exe_scope = process;
703
704 if (!exe_scope)
705 exe_scope = exe_ctx.GetTargetPtr();
706
707 ClangExpressionParser parser(exe_scope, *this, false);
708
709 // We have to find the source code location where the user text is inside
710 // the transformed expression code. When creating the transformed text, we
711 // already stored the absolute position in the m_transformed_text string. The
712 // only thing left to do is to transform it into the line:column format that
713 // Clang expects.
714
715 // The line and column of the user expression inside the transformed source
716 // code.
717 unsigned user_expr_line, user_expr_column;
718 if (m_user_expression_start_pos.hasValue())
719 AbsPosToLineColumnPos(*m_user_expression_start_pos, m_transformed_text,
720 user_expr_line, user_expr_column);
721 else
722 return false;
723
724 // The actual column where we have to complete is the start column of the
725 // user expression + the offset inside the user code that we were given.
726 const unsigned completion_column = user_expr_column + complete_pos;
Raphael Isemannc11a7802018-08-30 21:26:32 +0000727 parser.Complete(request, user_expr_line, completion_column, complete_pos);
Raphael Isemann74829732018-08-30 17:29:37 +0000728
729 return true;
730}
731
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732bool ClangUserExpression::AddArguments(ExecutionContext &exe_ctx,
733 std::vector<lldb::addr_t> &args,
734 lldb::addr_t struct_address,
735 DiagnosticManager &diagnostic_manager) {
736 lldb::addr_t object_ptr = LLDB_INVALID_ADDRESS;
737 lldb::addr_t cmd_ptr = LLDB_INVALID_ADDRESS;
Sean Callanan579e70c2016-03-19 00:03:59 +0000738
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 if (m_needs_object_ptr) {
740 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
741 if (!frame_sp)
742 return true;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000743
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744 ConstString object_name;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000745
Kate Stoneb9c1b512016-09-06 20:57:50 +0000746 if (m_in_cplusplus_method) {
747 object_name.SetCString("this");
748 } else if (m_in_objectivec_method) {
749 object_name.SetCString("self");
750 } else {
Zachary Turnere2411fa2016-11-12 19:12:56 +0000751 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 eDiagnosticSeverityError,
753 "need object pointer but don't know the language");
754 return false;
Jim Ingham51148e92015-11-05 00:24:18 +0000755 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756
Zachary Turner97206d52017-05-12 04:51:55 +0000757 Status object_ptr_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000758
Aleksandr Urakov40624a02019-02-05 09:14:36 +0000759 if (m_ctx_obj) {
760 AddressType address_type;
761 object_ptr = m_ctx_obj->GetAddressOf(false, &address_type);
762 if (object_ptr == LLDB_INVALID_ADDRESS ||
763 address_type != eAddressTypeLoad)
764 object_ptr_error.SetErrorString("Can't get context object's "
765 "debuggee address");
766 } else
767 object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768
769 if (!object_ptr_error.Success()) {
770 exe_ctx.GetTargetRef().GetDebugger().GetAsyncOutputStream()->Printf(
Jason Molenda599558e2017-02-21 05:09:26 +0000771 "warning: `%s' is not accessible (substituting 0)\n",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 object_name.AsCString());
773 object_ptr = 0;
Jim Ingham36f3b362010-10-14 23:45:03 +0000774 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775
776 if (m_in_objectivec_method) {
777 ConstString cmd_name("_cmd");
778
779 cmd_ptr = GetObjectPointer(frame_sp, cmd_name, object_ptr_error);
780
781 if (!object_ptr_error.Success()) {
782 diagnostic_manager.Printf(
783 eDiagnosticSeverityWarning,
784 "couldn't get cmd pointer (substituting NULL): %s",
785 object_ptr_error.AsCString());
786 cmd_ptr = 0;
787 }
788 }
789
790 args.push_back(object_ptr);
791
792 if (m_in_objectivec_method)
793 args.push_back(cmd_ptr);
794
795 args.push_back(struct_address);
796 } else {
797 args.push_back(struct_address);
798 }
799 return true;
Jim Ingham36f3b362010-10-14 23:45:03 +0000800}
801
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802lldb::ExpressionVariableSP ClangUserExpression::GetResultAfterDematerialization(
803 ExecutionContextScope *exe_scope) {
804 return m_result_delegate.GetVariable();
Sean Callanan9fda9d22015-10-03 09:09:01 +0000805}
806
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807void ClangUserExpression::ClangUserExpressionHelper::ResetDeclMap(
808 ExecutionContext &exe_ctx,
809 Materializer::PersistentVariableDelegate &delegate,
Aleksandr Urakov40624a02019-02-05 09:14:36 +0000810 bool keep_result_in_memory,
811 ValueObject *ctx_obj) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000812 m_expr_decl_map_up.reset(
Aleksandr Urakov40624a02019-02-05 09:14:36 +0000813 new ClangExpressionDeclMap(keep_result_in_memory, &delegate, exe_ctx,
814 ctx_obj));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000815}
Jim Ingham36f3b362010-10-14 23:45:03 +0000816
Jim Ingham151c0322015-09-15 21:13:50 +0000817clang::ASTConsumer *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818ClangUserExpression::ClangUserExpressionHelper::ASTTransformer(
819 clang::ASTConsumer *passthrough) {
820 m_result_synthesizer_up.reset(
821 new ASTResultSynthesizer(passthrough, m_top_level, m_target));
Sean Callananc673a6e2010-12-07 10:00:20 +0000822
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 return m_result_synthesizer_up.get();
Sean Callanan1a8d4092010-08-27 01:01:44 +0000824}
825
Kate Stoneb9c1b512016-09-06 20:57:50 +0000826void ClangUserExpression::ClangUserExpressionHelper::CommitPersistentDecls() {
827 if (m_result_synthesizer_up.get()) {
828 m_result_synthesizer_up->CommitPersistentDecls();
829 }
Sean Callanan00294b32016-03-22 21:05:51 +0000830}
831
Kate Stoneb9c1b512016-09-06 20:57:50 +0000832ConstString ClangUserExpression::ResultDelegate::GetName() {
Adrian Prantl03219f72018-04-30 23:59:17 +0000833 auto prefix = m_persistent_state->GetPersistentVariablePrefix();
834 return m_persistent_state->GetNextPersistentVariableName(*m_target_sp,
835 prefix);
Sean Callanan9fda9d22015-10-03 09:09:01 +0000836}
837
Kate Stoneb9c1b512016-09-06 20:57:50 +0000838void ClangUserExpression::ResultDelegate::DidDematerialize(
839 lldb::ExpressionVariableSP &variable) {
840 m_variable = variable;
Sean Callanan9fda9d22015-10-03 09:09:01 +0000841}
842
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843void ClangUserExpression::ResultDelegate::RegisterPersistentState(
844 PersistentExpressionState *persistent_state) {
845 m_persistent_state = persistent_state;
Sean Callanan9fda9d22015-10-03 09:09:01 +0000846}
847
Kate Stoneb9c1b512016-09-06 20:57:50 +0000848lldb::ExpressionVariableSP &ClangUserExpression::ResultDelegate::GetVariable() {
849 return m_variable;
Sean Callanan9fda9d22015-10-03 09:09:01 +0000850}