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