LLDB mainline
ClangExpressionSourceCode.cpp
Go to the documentation of this file.
1//===-- ClangExpressionSourceCode.cpp -------------------------------------===//
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
10
11#include "ClangExpressionUtil.h"
12
13#include "clang/Basic/CharInfo.h"
14#include "clang/Basic/FileManager.h"
15#include "clang/Basic/SourceManager.h"
16#include "clang/Lex/Lexer.h"
17#include "llvm/ADT/ScopeExit.h"
18#include "llvm/ADT/StringRef.h"
19
22#include "lldb/Symbol/Block.h"
31#include "lldb/Target/Target.h"
33#include "lldb/lldb-forward.h"
34
35using namespace lldb_private;
36
37#define PREFIX_NAME "<lldb wrapper prefix>"
38#define SUFFIX_NAME "<lldb wrapper suffix>"
39
41
43"#line 1 \"" PREFIX_NAME R"("
44#ifndef offsetof
45#define offsetof(t, d) __builtin_offsetof(t, d)
46#endif
47#ifndef NULL
48#define NULL (__null)
49#endif
50#ifndef Nil
51#define Nil (__null)
52#endif
53#ifndef nil
54#define nil (__null)
55#endif
56#ifndef YES
57#define YES ((BOOL)1)
58#endif
59#ifndef NO
60#define NO ((BOOL)0)
61#endif
62typedef __INT8_TYPE__ int8_t;
63typedef __UINT8_TYPE__ uint8_t;
64typedef __INT16_TYPE__ int16_t;
65typedef __UINT16_TYPE__ uint16_t;
66typedef __INT32_TYPE__ int32_t;
67typedef __UINT32_TYPE__ uint32_t;
68typedef __INT64_TYPE__ int64_t;
69typedef __UINT64_TYPE__ uint64_t;
70typedef __INTPTR_TYPE__ intptr_t;
71typedef __UINTPTR_TYPE__ uintptr_t;
72typedef __SIZE_TYPE__ size_t;
73typedef __PTRDIFF_TYPE__ ptrdiff_t;
74typedef unsigned short unichar;
75extern "C"
76{
77 int printf(const char * __restrict, ...);
78}
79)";
80
82 "\n;\n#line 1 \"" SUFFIX_NAME "\"\n";
83
84namespace {
85
86class AddMacroState {
87 enum State {
88 CURRENT_FILE_NOT_YET_PUSHED,
89 CURRENT_FILE_PUSHED,
90 CURRENT_FILE_POPPED
91 };
92
93public:
94 AddMacroState(const FileSpec &current_file, const uint32_t current_file_line)
95 : m_current_file(current_file), m_current_file_line(current_file_line) {}
96
97 void StartFile(const FileSpec &file) {
98 m_file_stack.push_back(file);
99 if (file == m_current_file)
100 m_state = CURRENT_FILE_PUSHED;
101 }
102
103 void EndFile() {
104 if (m_file_stack.size() == 0)
105 return;
106
107 FileSpec old_top = m_file_stack.back();
108 m_file_stack.pop_back();
109 if (old_top == m_current_file)
110 m_state = CURRENT_FILE_POPPED;
111 }
112
113 // An entry is valid if it occurs before the current line in the current
114 // file.
115 bool IsValidEntry(uint32_t line) {
116 switch (m_state) {
117 case CURRENT_FILE_NOT_YET_PUSHED:
118 return true;
119 case CURRENT_FILE_PUSHED:
120 // If we are in file included in the current file, the entry should be
121 // added.
122 if (m_file_stack.back() != m_current_file)
123 return true;
124
125 return line < m_current_file_line;
126 default:
127 return false;
128 }
129 }
130
131private:
132 std::vector<FileSpec> m_file_stack;
133 State m_state = CURRENT_FILE_NOT_YET_PUSHED;
134 FileSpec m_current_file;
135 uint32_t m_current_file_line;
136};
137
138} // anonymous namespace
139
140static void AddMacros(const DebugMacros *dm, CompileUnit *comp_unit,
141 AddMacroState &state, StreamString &stream) {
142 if (dm == nullptr)
143 return;
144
145 // The macros directives below can potentially redefine builtin macros of the
146 // Clang instance which parses the user expression. The Clang diagnostics
147 // caused by this are not useful for the user as the source code here is
148 // generated by LLDB.
149 stream << "#pragma clang diagnostic push\n";
150 stream << "#pragma clang diagnostic ignored \"-Wmacro-redefined\"\n";
151 stream << "#pragma clang diagnostic ignored \"-Wbuiltin-macro-redefined\"\n";
152 llvm::scope_exit pop_warning(
153 [&stream]() { stream << "#pragma clang diagnostic pop\n"; });
154
155 for (size_t i = 0; i < dm->GetNumMacroEntries(); i++) {
156 const DebugMacroEntry &entry = dm->GetMacroEntryAtIndex(i);
157 uint32_t line;
158
159 switch (entry.GetType()) {
161 if (state.IsValidEntry(entry.GetLineNumber()))
162 stream.Printf("#define %s\n", entry.GetMacroString().AsCString());
163 else
164 return;
165 break;
167 if (state.IsValidEntry(entry.GetLineNumber()))
168 stream.Printf("#undef %s\n", entry.GetMacroString().AsCString());
169 else
170 return;
171 break;
173 line = entry.GetLineNumber();
174 if (state.IsValidEntry(line))
175 state.StartFile(entry.GetFileSpec(comp_unit));
176 else
177 return;
178 break;
180 state.EndFile();
181 break;
183 AddMacros(entry.GetIndirectDebugMacros(), comp_unit, state, stream);
184 break;
185 default:
186 // This is an unknown/invalid entry. Ignore.
187 break;
188 }
189 }
190}
191
193 llvm::StringRef filename, llvm::StringRef name, llvm::StringRef prefix,
194 llvm::StringRef body, Wrapping wrap, WrapKind wrap_kind)
195 : ExpressionSourceCode(name, prefix, body, wrap), m_wrap_kind(wrap_kind) {
196 // Use #line markers to pretend that we have a single-line source file
197 // containing only the user expression. This will hide our wrapper code
198 // from the user when we render diagnostics with Clang.
199 m_start_marker = "#line 1 \"" + filename.str() + "\"\n";
201}
202
203namespace {
204/// Allows checking if a token is contained in a given expression.
205class TokenVerifier {
206 /// The tokens we found in the expression.
207 llvm::StringSet<> m_tokens;
208
209public:
210 TokenVerifier(std::string body);
211 /// Returns true iff the given expression body contained a token with the
212 /// given content.
213 bool hasToken(llvm::StringRef token) const {
214 return m_tokens.contains(token);
215 }
216};
217
218// If we're evaluating from inside a lambda that captures a 'this' pointer,
219// add a "using" declaration to 'stream' for each capture used in the
220// expression (tokenized by 'verifier').
221//
222// If no 'this' capture exists, generate no using declarations. Instead
223// capture lookups will get resolved by the same mechanism as class member
224// variable lookup. That's because Clang generates an unnamed structure
225// representing the lambda closure whose members are the captured variables.
226void AddLambdaCaptureDecls(StreamString &stream, StackFrame *frame,
227 TokenVerifier const &verifier) {
228 assert(frame);
229
230 if (auto thisValSP = ClangExpressionUtil::GetLambdaValueObject(frame)) {
231 uint32_t numChildren = thisValSP->GetNumChildrenIgnoringErrors();
232 for (uint32_t i = 0; i < numChildren; ++i) {
233 auto childVal = thisValSP->GetChildAtIndex(i);
234 ConstString childName(childVal ? childVal->GetName() : ConstString(""));
235
236 if (!childName.IsEmpty() && verifier.hasToken(childName.GetStringRef()) &&
237 childName != "this") {
238 stream.Printf("using $__lldb_local_vars::%s;\n",
239 childName.GetCString());
240 }
241 }
242 }
243}
244
245} // namespace
246
247TokenVerifier::TokenVerifier(std::string body) {
248 using namespace clang;
249
250 // We only care about tokens and not their original source locations. If we
251 // move the whole expression to only be in one line we can simplify the
252 // following code that extracts the token contents.
253 llvm::replace(body, '\n', ' ');
254 llvm::replace(body, '\r', ' ');
255
256 FileSystemOptions file_opts;
257 FileManager file_mgr(file_opts,
258 FileSystem::Instance().GetVirtualFileSystem());
259
260 // Let's build the actual source code Clang needs and setup some utility
261 // objects.
262 DiagnosticOptions diags_opts;
263 DiagnosticsEngine diags(DiagnosticIDs::create(), diags_opts);
264 clang::SourceManager SM(diags, file_mgr);
265 auto buf = llvm::MemoryBuffer::getMemBuffer(body);
266
267 FileID FID = SM.createFileID(buf->getMemBufferRef());
268
269 // Let's just enable the latest ObjC and C++ which should get most tokens
270 // right.
271 LangOptions Opts;
272 Opts.ObjC = true;
273 Opts.DollarIdents = true;
274 Opts.CPlusPlus20 = true;
275 Opts.LineComment = true;
276
277 Lexer lex(FID, buf->getMemBufferRef(), SM, Opts);
278
279 Token token;
280 bool exit = false;
281 while (!exit) {
282 // Returns true if this is the last token we get from the lexer.
283 exit = lex.LexFromRawLexer(token);
284
285 // Extract the column number which we need to extract the token content.
286 // Our expression is just one line, so we don't need to handle any line
287 // numbers here.
288 bool invalid = false;
289 unsigned start = SM.getSpellingColumnNumber(token.getLocation(), &invalid);
290 if (invalid)
291 continue;
292 // Column numbers start at 1, but indexes in our string start at 0.
293 --start;
294
295 // Annotations don't have a length, so let's skip them.
296 if (token.isAnnotation())
297 continue;
298
299 // Extract the token string from our source code and store it.
300 std::string token_str = body.substr(start, token.getLength());
301 if (token_str.empty())
302 continue;
303 m_tokens.insert(token_str);
304 }
305}
306
308 const std::string &expr,
309 StackFrame *frame) const {
310 assert(frame);
311 TokenVerifier tokens(expr);
312
313 lldb::VariableListSP var_list_sp = frame->GetInScopeVariableList(false, true);
314
315 for (size_t i = 0; i < var_list_sp->GetSize(); i++) {
316 lldb::VariableSP var_sp = var_list_sp->GetVariableAtIndex(i);
317
318 ConstString var_name = var_sp->GetName();
319
320 if (var_name == "this" && m_wrap_kind == WrapKind::CppMemberFunction) {
321 AddLambdaCaptureDecls(stream, frame, tokens);
322
323 continue;
324 }
325
326 // We can check for .block_descriptor w/o checking for langauge since this
327 // is not a valid identifier in either C or C++.
328 if (!var_name || var_name == ".block_descriptor")
329 continue;
330
331 if (!expr.empty() && !tokens.hasToken(var_name.GetStringRef()))
332 continue;
333
334 const bool is_objc = m_wrap_kind == WrapKind::ObjCInstanceMethod ||
336 if ((var_name == "self" || var_name == "_cmd") && is_objc)
337 continue;
338
339 stream.Printf("using $__lldb_local_vars::%s;\n", var_name.AsCString());
340 }
341}
342
344 std::string &text, ExecutionContext &exe_ctx, bool add_locals,
345 bool force_add_all_locals, llvm::ArrayRef<std::string> modules) const {
346 const char *target_specific_defines = "typedef signed char BOOL;\n";
347 std::string module_macros;
348 llvm::raw_string_ostream module_macros_stream(module_macros);
349
350 Target *target = exe_ctx.GetTargetPtr();
351 if (target) {
352 if (target->GetArchitecture().GetMachine() == llvm::Triple::aarch64 ||
353 target->GetArchitecture().GetMachine() == llvm::Triple::aarch64_32) {
354 target_specific_defines = "typedef bool BOOL;\n";
355 }
356 if (target->GetArchitecture().GetMachine() == llvm::Triple::x86_64) {
357 if (lldb::PlatformSP platform_sp = target->GetPlatform()) {
358 if (platform_sp->GetPluginName() == "ios-simulator") {
359 target_specific_defines = "typedef bool BOOL;\n";
360 }
361 }
362 }
363
364 auto *persistent_vars = llvm::cast<ClangPersistentVariables>(
366 std::shared_ptr<ClangModulesDeclVendor> decl_vendor =
367 persistent_vars->GetClangModulesDeclVendor();
368 if (decl_vendor) {
369 const ClangModulesDeclVendor::ModuleVector &hand_imported_modules =
370 persistent_vars->GetHandLoadedClangModules();
371 ClangModulesDeclVendor::ModuleVector modules_for_macros;
372
373 for (ClangModulesDeclVendor::ModuleID module : hand_imported_modules) {
374 modules_for_macros.push_back(module);
375 }
376
377 if (target->GetEnableAutoImportClangModules()) {
378 if (StackFrame *frame = exe_ctx.GetFramePtr()) {
379 if (Block *block = frame->GetFrameBlock()) {
380 SymbolContext sc;
381
382 block->CalculateSymbolContext(&sc);
383
384 if (sc.comp_unit) {
385 if (auto err = decl_vendor->AddModulesForCompileUnit(
386 *sc.comp_unit, modules_for_macros))
388 GetLog(LLDBLog::Expressions), std::move(err),
389 "Error while loading hand-imported modules:\n{0}");
390 }
391 }
392 }
393 }
394
395 decl_vendor->ForEachMacro(
396 modules_for_macros,
397 [&module_macros_stream](llvm::StringRef token,
398 llvm::StringRef expansion) -> bool {
399 // Check if the macro hasn't already been defined in the
400 // g_expression_prefix (which defines a few builtin macros).
401 module_macros_stream << "#ifndef " << token << "\n";
402 module_macros_stream << expansion << "\n";
403 module_macros_stream << "#endif\n";
404 return false;
405 });
406 }
407 }
408
409 StreamString debug_macros_stream;
410 StreamString lldb_local_var_decls;
411 if (StackFrame *frame = exe_ctx.GetFramePtr()) {
412 const SymbolContext &sc = frame->GetSymbolContext(
413 lldb::eSymbolContextCompUnit | lldb::eSymbolContextLineEntry);
414
415 if (sc.comp_unit && sc.line_entry.IsValid()) {
417 if (dm) {
418 AddMacroState state(sc.line_entry.GetFile(), sc.line_entry.line);
419 AddMacros(dm, sc.comp_unit, state, debug_macros_stream);
420 }
421 }
422
423 if (add_locals)
424 if (target->GetInjectLocalVariables(&exe_ctx)) {
425 AddLocalVariableDecls(lldb_local_var_decls,
426 force_add_all_locals ? "" : m_body, frame);
427 }
428 }
429
430 if (m_wrap) {
431 // Generate a list of @import statements that will import the specified
432 // module into our expression.
433 std::string module_imports;
434 for (const std::string &module : modules) {
435 module_imports.append("@import ");
436 module_imports.append(module);
437 module_imports.append(";\n");
438 }
439
440 StreamString wrap_stream;
441
442 wrap_stream.Printf("%s\n%s\n%s\n%s\n%s\n", g_expression_prefix,
443 module_macros.c_str(), debug_macros_stream.GetData(),
444 target_specific_defines, m_prefix.c_str());
445
446 // First construct a tagged form of the user expression so we can find it
447 // later:
448 std::string tagged_body;
449 tagged_body.append(m_start_marker);
450 tagged_body.append(m_body);
451 tagged_body.append(m_end_marker);
452
453 switch (m_wrap_kind) {
455 wrap_stream.Printf("%s"
456 "void \n"
457 "%s(void *$__lldb_arg) \n"
458 "{ \n"
459 " %s; \n"
460 "%s"
461 "} \n",
462 module_imports.c_str(), m_name.c_str(),
463 lldb_local_var_decls.GetData(), tagged_body.c_str());
464 break;
466 wrap_stream.Printf("%s"
467 "void \n"
468 "$__lldb_class::%s(void *$__lldb_arg) \n"
469 "{ \n"
470 " %s; \n"
471 "%s"
472 "} \n",
473 module_imports.c_str(), m_name.c_str(),
474 lldb_local_var_decls.GetData(), tagged_body.c_str());
475 break;
477 wrap_stream.Printf(
478 "%s"
479 "@interface $__lldb_objc_class ($__lldb_category) \n"
480 "-(void)%s:(void *)$__lldb_arg; \n"
481 "@end \n"
482 "@implementation $__lldb_objc_class ($__lldb_category) \n"
483 "-(void)%s:(void *)$__lldb_arg \n"
484 "{ \n"
485 " %s; \n"
486 "%s"
487 "} \n"
488 "@end \n",
489 module_imports.c_str(), m_name.c_str(), m_name.c_str(),
490 lldb_local_var_decls.GetData(), tagged_body.c_str());
491 break;
492
494 wrap_stream.Printf(
495 "%s"
496 "@interface $__lldb_objc_class ($__lldb_category) \n"
497 "+(void)%s:(void *)$__lldb_arg; \n"
498 "@end \n"
499 "@implementation $__lldb_objc_class ($__lldb_category) \n"
500 "+(void)%s:(void *)$__lldb_arg \n"
501 "{ \n"
502 " %s; \n"
503 "%s"
504 "} \n"
505 "@end \n",
506 module_imports.c_str(), m_name.c_str(), m_name.c_str(),
507 lldb_local_var_decls.GetData(), tagged_body.c_str());
508 break;
509 }
510
511 text = std::string(wrap_stream.GetString());
512 } else {
513 text.append(m_body);
514 }
515
516 return true;
517}
518
520 std::string transformed_text, size_t &start_loc, size_t &end_loc) {
521 start_loc = transformed_text.find(m_start_marker);
522 if (start_loc == std::string::npos)
523 return false;
524 start_loc += m_start_marker.size();
525 end_loc = transformed_text.find(m_end_marker);
526 return end_loc != std::string::npos;
527}
#define PREFIX_NAME
static void AddMacros(const DebugMacros *dm, CompileUnit *comp_unit, AddMacroState &state, StreamString &stream)
#define SUFFIX_NAME
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:392
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:677
A class that describes a single lexical block.
Definition Block.h:41
ClangExpressionSourceCode(llvm::StringRef filename, llvm::StringRef name, llvm::StringRef prefix, llvm::StringRef body, Wrapping wrap, WrapKind wrap_kind)
WrapKind
The possible ways an expression can be wrapped.
@ ObjCStaticMethod
Wrapped in a static Objective-C method.
@ CppMemberFunction
Wrapped in a non-static member function of a C++ class.
@ ObjCInstanceMethod
Wrapped in an instance Objective-C method.
std::string m_start_marker
String marking the start of the user expression.
static const llvm::StringRef g_prefix_file_name
The file name we use for the wrapper code that we inject before the user expression.
bool GetText(std::string &text, ExecutionContext &exe_ctx, bool add_locals, bool force_add_all_locals, llvm::ArrayRef< std::string > modules) const
Generates the source code that will evaluate the expression.
bool GetOriginalBodyBounds(std::string transformed_text, size_t &start_loc, size_t &end_loc)
const WrapKind m_wrap_kind
How the expression has been wrapped.
std::string m_end_marker
String marking the end of the user expression.
void AddLocalVariableDecls(StreamString &stream, const std::string &expr, StackFrame *frame) const
Writes "using" declarations for local variables into the specified stream.
A class that describes a compilation unit.
Definition CompileUnit.h:43
DebugMacros * GetDebugMacros()
A uniqued constant string class.
Definition ConstString.h:40
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
ConstString GetMacroString() const
Definition DebugMacros.h:50
const FileSpec & GetFileSpec(CompileUnit *comp_unit) const
DebugMacros * GetIndirectDebugMacros() const
Definition DebugMacros.h:54
EntryType GetType() const
Definition DebugMacros.h:46
uint64_t GetLineNumber() const
Definition DebugMacros.h:48
DebugMacroEntry GetMacroEntryAtIndex(const size_t index) const
Definition DebugMacros.h:83
size_t GetNumMacroEntries() const
Definition DebugMacros.h:81
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
StackFrame * GetFramePtr() const
Returns a pointer to the frame object.
Target * GetTargetPtr() const
Returns a pointer to the target object.
ExpressionSourceCode(llvm::StringRef name, llvm::StringRef prefix, llvm::StringRef body, Wrapping wrap)
A file utility class.
Definition FileSpec.h:57
static FileSystem & Instance()
This base class provides an interface to stack frames.
Definition StackFrame.h:44
virtual lldb::VariableListSP GetInScopeVariableList(bool get_file_globals, bool must_have_valid_location=false)
Retrieve the list of variables that are in scope at this StackFrame's pc.
virtual const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
virtual Block * GetFrameBlock()
Get the current lexical scope block for this StackFrame, if possible.
const char * GetData() const
llvm::StringRef GetString() const
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
Defines a symbol context baton that can be handed other debug core functions.
CompileUnit * comp_unit
The CompileUnit for a given query.
LineEntry line_entry
The LineEntry for a given query.
bool GetEnableAutoImportClangModules() const
Definition Target.cpp:4857
bool GetInjectLocalVariables(ExecutionContext *exe_ctx) const
Definition Target.cpp:4540
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition Target.cpp:2683
lldb::PlatformSP GetPlatform()
Definition Target.h:1648
const ArchSpec & GetArchitecture() const
Definition Target.h:1153
lldb::ValueObjectSP GetLambdaValueObject(StackFrame *frame)
Returns a ValueObject for the lambda class in the current frame.
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:332
std::shared_ptr< lldb_private::Platform > PlatformSP
@ eLanguageTypeC
Non-standardized C, such as K&R.
std::shared_ptr< lldb_private::VariableList > VariableListSP
std::shared_ptr< lldb_private::Variable > VariableSP
bool IsValid() const
Check if a line entry object is valid.
Definition LineEntry.cpp:35
uint32_t line
The source line number, or LLDB_INVALID_LINE_NUMBER if there is no line number information.
Definition LineEntry.h:151
const FileSpec & GetFile() const
Helper to access the file.
Definition LineEntry.h:134